Академический Документы
Профессиональный Документы
Культура Документы
The term Java refers to more than just a computer language like C or Pascal. Java encompasses several distinct components: highA high-level language Java is an object-oriented computer programming language whose source code at a glance looks very similar to C and C++ but is unique in many ways. Java bytecode A compiler transforms the Java language source code to files of binary instructions and data called bytecode that run in the Java Virtual Machine. Java Virtual Machine (JVM) A JVM program takes bytecode as input and interprets the instructions just as if it were a physical processor executing machine code. All language compilers translate source code in machine code for a specific computer. Java compiler does the same thing. Java compiler produces an intermediate code known as byte code for a machine that does not exist physically, this machine is called Java Virtual Machine(JVM) and it exists only inside the computer memory, it is a simulated computer with in a computer. This virtual machine is not machine specific code, the machine specific code is generated by the java interpreter by acting as a intermediate between virtual machine and real machine.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 1
History of Java:
During 1990, James Gosling, Bill Joy and others at Sun Microsystems began developing a language called Oak. They primarily intended it as a language for microprocessors embedded in consumer devices such as cable set-top boxes, VCRs, and handheld computers (now known as personal data assistants or PDAs). To serve these goals, Oak needed the following features: independence, platform independence since it must run on devices from multiple manufacturers extreme compactness, reliability (cant expect consumers to reboot their VCRs!) compactness since embedded processors typically have limited memory. They also wanted a next-generation language that built on the strengths and avoided the weaknesses of earlier languages. Such features would help the new language provide more rapid software development and faster debugging. By 1993 the interactiveTVand PDAmarkets had failed to take off, but internet and web activity began its upward zoom. So Sun shifted the target market to internet applications and changed the name of the project to Java. The portability of Java made it ideal for the Web, and in 1995 Suns HotJava browser appeared. Written in Java in only a few months, it illustrated the power of applets programs that run within a browser and the ability of Java to accelerate program development. Java: Versions of Java: Since its introduction, Sun has released new versions of the Java core language with significant enhancements about every two years or so. Until recently, Sun denoted the versions with a 1.x number, where x reached up to 4. (Less drastic releases with bug fixes were indicated with a third number as in 1.4.2.) The next version, however, will be called Java 5.0. Furthermore, Sun has split its development kits into so-called editions, each aimed towards a platform with different capabilities. Standard Edition Below is a time line for the different versions of the Standard Edition (SE) of Java, which offers the core language libraries (called packages in Java) and is aimed at desktop platforms. We include a sampling of the new features that came with each release. 1995 Version 1.0. The Java Development Kit (JDK) included: 8 packages with 212 classes. Netscape 2.04.0 included Java 1.0. Microsoft and other companies licensed Java.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 2
1997 Version 1.1 23 packages, 504 classes. Improvements included better event handling, inner classes, improved VM. Microsoft developed its own 1.1-compatible Java Virtual Machine for the Internet Explorer. Many browsers in use are still compatible only with 1.1. Swing packages with greatly improved graphics became available during this time but were not included with the core language. 1999 Version 1.2. Sun began referring to the 1.2 and above versions as the Java 2 Platform. The Software Development Kit (SDK) included: 59 packages, 1520 classes. Java Foundation Classes (JFC), based on Swing, for improved graphics and user interfaces, now included with the core language. Collections Framework API included support for various lists, sets, and hash maps. 2000 Version 1.3: 76 packages, 1842 classes. Performance enhancements including the Hotspot virtual machine. 2002 Version 1.4: 135 packages, 2991 classes. 2004 Version 5.0 (previously known as 1.5). It includes a number of tools and additions to the language to enhance program development, such as: 4faster startup and smaller memory footprint, metadata, formatted output, generics improved multithreading features. 165 packages, over 3000 classes
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 3
Features Of Java:
Before we examine how Java can benefit technical applications, we look at the features that make Java a powerful and popular general programming language. These features include: Compiler/interpreter combination Code is compiled to bytecode, which is interpreted by a Java Virtual Machine (JVM). This provides portability to any base operating system platform for which a virtual machine has been written.The two-step procedure of compilation and interpretation allows for extensive code checking and improved security. Simple Java was designed to be easy for the professional programmer to learn and use effectively. Assuming that you have some programming experience, you will not find Java hard to master. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the objectoriented features of C++, most programmers have little trouble learning Java. ObjectObject-oriented Object-oriented programming (OOP) throughout no coding outside of class definitions. The bytecode retains an object structure. An extensive class library available in the core language packages. Automatic memory management A garbage collector in the JVM takes care of allocating and reclaiming memory. Robust Exception handling built-in, strong type checking (that is, all variables must be assigned an explicit data type), local variables must be initialized. Platform independence The bytecode runs on any platform with a compatible JVM. The Write Once Run Anywhere ideal has not been achieved (tuning for different platforms usually required), but is closer than with other languages.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 4
Secure The elimination of direct memory pointers and automatic array limit checking . Untrusted programs are restricted to run inside the virtual machine sandbox. Access to the platform can be strictly controlled by a Security Manager. Code is checked for pathologies by a class loader and a bytecode verifier. Multithreaded Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously Dynamic binding Classes, methods, and variables are linked at runtime.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 5
acting on data. Procedural languages such as C employ this model to considerable success. The
problems with this approach appear as programs grow larger and more complex. To manage increasing complexity, approach, The second approach called object-oriented programming, was conceived. Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling
access to code
Principles The Three OOP Principles All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism. Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse. One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper/class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 6
Inheritance
Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification. Without the use of hierarchies, each object would need to define all of its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Polymorphism
Polymorphism (from the Greek, meaning many forms) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of the situation. Polymorphism is a way by which an object can exhibit multiple behaviour in multiple instances or situations.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 7
Constructors in Java:
Constructors are special methods of class. A constructor initializes an object immediately after creation. Once defined, the constructor is automatically called immediately after the object is creation.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 9
Inheritance in Java:
Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification. Without the use of hierarchies, each object would need to define all of its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Features of Inheritance: One of the key concepts of OOP. Establishes a hierarchical relationship among classes. Establishes a super class/sub class relationship. Establishes is a relationships. A super class defines a general set of functionality, whereas subclasses define functionalities specific to them. In other sense, inheritance in Java builds a hierarchy of classes & thus supports the concept of classification. Inheritance is implemented in Java using extends keyword. Benefits of Inheritance: Reusability of code. Put code in one class, use it in all the subclasses. Write general purpose code designed for a super type that works for all subtypes. Points to Remember : Private members of the super class are not accessible by the sub class and can only be indirectly accessed. Constructors and Initializer blocks are not inherited by a subclass. When you construct an object, the default base class constructor is called implicitly, before the body of the derived class constructor is executed. So, objects are constructed top-down under inheritance.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 10
Example :
class A{ A(){ System.out.println("Default constructor of class A"); } A(int val){ System.out.println(Parameterized constructor of class A"); } } class B extends A{ B(){ System.out.println("Default constructor of class B"); } B(int val){ System.out.println(Parameterized constructor of class B"); } }
Predict the output. B ref1 = new B(); B ref2 = new B(5); Output : Default constructor of class A Default constructor of class B Default constructor of class A Parameterised constructor of class B
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 11
Inheritance Example :
class Calculator { float num1, num2, ans; float add() { ans = num1 + num2; return ans; } float sub() { ans = num1 + num2; return ans; } float mul() { ans = num1 * num2; return ans; } }//End of Calculator Class class ScientificCalculator extends Calculator { float sqrt() { ans = (float)Math.sqrt(num1); return ans; } }//End of ScientificCalculator Class class CalculatorDemo { public static void main(String [] args) { ScientificCalculator sc = new ScientificCalculator(); sc.num1 = 20.0f; sc.add(); sc.mul(); } }//End of CalculatorDemo Class sc.num2 = 10.0f; sc.sub(); sc.sqrt();
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 12
{a,b,c,d}; char [] ch = {a,b,c,d}; String s = new String(ch); Using String Literal ; String s = abcd; String Operation :
1. Concatenation :
Method that concatenates two strings, producing a String object as the result. Eg : String s1 = abcd; String s2 = xyz; String s3 = s1.concat(s2); //Using concat method of String class. String s3 = s1 + s2; // Using + Operator for concatenation.
2. Length :
Returns the length of String as integer represents number of character encapsulated in String objects
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 13
3. Character Extraction : char charAt(int index) byte [] getBytes() char [] toCharArray() 4. Comparison :
boolean equals(String str ) and boolean equalsIgnoreCase(String str) Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase( ). equalsIgnoreCase( ) When it compares two strings, it considers A-Z to be the same as a-z.
5. Other Utility Method : String toUpperCase() String toLowerCase() String trim() int indexOf(char) int indexOf(String str) .etc
Java.lang.StringBuffer Java.lang.StringBuffer : StringBuffer is a peer class of String, that represents mutable type String objects in Java. StringBuffer defines these three constructors: StringBuffer( ) Default Constructor StringBuffer(int size) - int Defines size of String Object StringBuffer(String str) to get StringBuffer object from String object Example: String s = new String(abc); StringBuffer sb = new StringBuffer(s);
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 14
Package in Java:
Java provides a mechanism for partitioning the class name space into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package. Defining a Package To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. package MyPackage; Finding Packages and CLASSPATH As just explained, packages are mirrored by directories. This raises an important question: How does the Java run-time system know where to look for packages that you create? The answer has two parts. First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in the current directory, or a subdirectory of the current directory, it will be found. Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable. Importing Packages: Java includes the import statement to bring certain classes, or entire packages, into visibility. Once imported, a class can be referred to directly, using only its name. The import statement is a convenience to the programmer and is not technically needed to write a complete Java program. If you are going to refer to a few dozen classes in your application, however, the import statement will save a lot of typing. In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. This is the general form of the import statement: import pack1.subaack.* or class/interface Name
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 15
package com; public class Message { public void showMessage(String name) { System.out.println("Hello "+name); } } // End Of Message Class
Compiling Message.java Test.java SourceCode : Test.java javac d . Message.java
import com.Message; class Test { public static void main(String [] args) { Message m = new Message(); m.showMessage("United, Allahabad"); } }//End Of Test Class.
Compile and Run Test.java Output javac Test.java java Test Hello United, Allahabad
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 16
The three access specifiers, private public and protected provide a variety of ways to produce private, public, protected, the many levels of access required by these categories. While Javas access control mechanism may seem complicated, we can simplify it as follows: PUBLIC : Anything declared public can be accessed from anywhere. PRIVATE : Anything declared private cannot be seen outside of its class. DEFAULT : When a member does not have an explicit access specification, it is visible to subclasses as well as to other classes in the same package. This is the default access. PROTECTED : If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected. protected ted.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 17
A super class that only defines a generalized form that will be shared by all its sub classes, leaving the implementation details to its subclasses is said to an abstract class. A concrete class has concrete methods, including implementations of any abstract methods inherited from its super classes. Any class with abstract methods should be declared abstract. Abstract Method & Class Example :
abstract class Shape { //abstract class abstract double area(); //abstract method void displayDetail() { //concrete method System.out.println(Showing Details of Shape.); } } class Square extends Shape{ double side; double area() { //Overriding the abstract method. return side*side; } }
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 18
classes Pointes to remember : Abstract classes and methods An abstract class cannot have objects because it is not complete, but it can have references.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 19
Interface in Java:
Javas interfaces are an improvement over multiple inheritance mechanism of C++. While designing a software system in java, Interfaces help us defining the interfaces between the components. Interfaces help us achieve a special kind of multiple inheritance : multiple inheritance of interfaces without multiple inheritance of implementation. When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. An interface is a contract. Interfaces can be implemented by any class, from any inheritance tree. This lets you take radically different classes and give them a common characteristic. But while an abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods. Another way interfaces differ from abstract classes is that interfaces have very little flexibility in how the methods and variables defined in the interface are declared. These rules are strict:
All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
All variables defined in an interface must be public, static, and finalin other words, interfaces can declare only constants, not instance variables. Interface methods must not be static. Because interface methods are abstract, they cannot be marked final. An interface can extend one or more other interfaces. An interface cannot extend any class. An interface cannot implement another interface or class. An interface must be declared with the keyword interface.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 20
Interface Example :
//by default public, static and final //by default public and abstract
class Square implements Shape { float side ; public void area() { return side*side } }
class ShapeDemo { public static void main(String [] ar) { Square s = new Square(); s.side = 2.3f; float sarea = s.area(); System.out.println(AREA IS : +sarea); } }
OUTPUT:
AREA IS : 5.29
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 21
Polymorphism:
Polymorphism (from the Greek, meaning many forms) is a feature that allows one
interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. Polymorphism is a way by which an object can exhibit multiple behaviour in multiple instances or situations. Types of polymorphism: Compile Time Polymorphism Method Overloading Run Time Polymorphism Method Overriding Method Overloading : Method overloading is a mechanism by which we can create more than one method with the same name in the same class but their parameter or argument list should be different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. We can overload the method by any one of the following changes in argument list:
Change the number of arguments. Change the type of arguments. Change the order of arguments.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 22
class Result { void showResult() { //Display the result of all students. System.out.println("Display Results); } void showResult(String rollno) { //Display the result of a student whose rollno is passed as argument. System.out.println("Display Result : "+rollno); } } class OverloadDemo { public static void main(String [] args) { Result ob = new Result(); ob.showResult(); ob.showResult("0901010071"); } }
Output:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 23
Method Overriding : In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its super class, then the method in the subclass is said to override the method in the super class. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass Method Overriding Example :
class Alto { void speedoMeter() { System.out.println("Analog System."); } void breakControl() { System.out.println("Power Break System."); } }//End Of Alto Class class AltoK10 extends Alto { void speedoMeter() { System.out.println("Digital System."); } }//End Of AltoK10 Class class TestDrive { public static void main(String [] args) { Alto ob1 = new Alto(); Alto ob2 = new AltoK10(); ob1.speedoMeter(); ob2.speedoMeter(); } //End Of TestDrive Class ob1.breakControl(); ob2.breakControl();
}
Output :
Analog System. Power Break System. Digital System. Power Break System.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 24
o o o o
Inner Class. Nested Class. Method Local Inner Class. Anonymous Inner Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 25
Inner Class :
o One of the key benefits of an inner class is the special relationship an inner
marked private.
o The members of inner of class cannot be declared as static. Inner Class Example :
class Outer { void show() { System.out.println("Hello From Show of Outer Class."); } class Inner { void display() { System.out.println("Hello From Display of Inner Class."); } }//End Of Inner Class }//End Of Outer Class class MemberClassDemo { public static void main(String [] args) { Outer o = new Outer(); o.show(); Outer.Inner i = o.new Inner(); //or Outer.Inner i = new Outer.new Inner(); i.display(); } }//End Of MemberClassDemo
Output :
Hello From Show of Outer Class. Hello From Display of Inner Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 26
Nested Class :
o If we mark or specify the member class as static that member class is called Nested Class. o Nested Class can have static member data and methods. o We can instantiate static member class outside the outer class without object of outer class. Nested Class Example :
class Outer { static class Nested { void display() { System.out.println("Hello From Display of Nested Class."); } static void show() { System.out.println("Hello From Static Show of Nested Class."); } }//End Of Nested Class }//End Of Outer Class class MemberClassDemo { public static void main(String [] args) { Outer.Nested.show(); Outer.Nested n = Outer.new Nested(); n.display(); } }//End Of MemberClassDemo
Output :
Hello From Static Show of Nested Class. Hello From Display of Nested Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 27
class Test { void show() { class Local { void print() { System.out.println("Hello From Local Inner Class."); } }//End Of Local Class Local l = new Local(); l.print(); } }//End Of Test Class class MLICDemo { public static void main(String [] ar) { Test t = new Test(); t.show(); } }//End Of MLICDemo Class.
Output :
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 28
class Test { void show() { System.out.println("Hello World from United!!!"); } }//End Of Test Class class AICDemo { public static void main(String [] args) { Test t1 = new Test(); //Anonymous Inner Class Test t2 = new Test(){ { void show() { System.out.println("Hello World from UCER!!!"); } }; //End Of Anonymous Inner Class t1.show(); t2.show(); } }//End Of AICDemo Class
Output Output :
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 29
(InputJava IO (Input-Output)
Java programs perform Input Output through streams. A stream is an abstraction that either produces or consumes information. A stream is simply a sequence of bytes that flows
into or out of our program. Its an abstract representation of an input or output device.
A stream is linked to a physical device by the Java IO stream. All streams behave in the same manner even if the actual physical devices to which they are linked differ.
Thus, the same IO classes and method can be applied to any type of decvice. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard or a network socket.
Java implements stream within class hierarchies define in the java.io package.
Similarly, we have methods for writing byte to stream; write( data) IOException void write(int data) throws IOException void write(byte [] array) throws IOException write(byte
Character Stream:
Character streams provide a convenient means for handling IO of characters. They use Unicode and therefore internationalized. Also, in some cases character stream are more efficient than byte stream. Character streams are defined by using two class hierarchies. At the top are two abstract class: java.io.Reader and java.io.Writer These abstracter class handle Unicode character java.io.Reader java.io.Writer Writer. streams. Java has several concrete subclasses of each of these. . The abstract classes Reader and Writer several key methods, that the other stream classes implement. Two of the most important methods are read() and write(). write(). Methods for performing character based reading operation: read( IOException int read( ) throws IOException read( array) int read(char [] array) throws IOException
Methods for performing character based writing operation: write( data) void write(int data) throws IOException void write(char [] array) throws IOException
InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println(Please Enter Your Name : ); String name = br.readLine(); System.out.println(Hello : +name);
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 31
FileInputStream(String fileName) throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException FileOutputStream(String filename,boolean mode) throws FileNotFoundException
The FileReader and FileWriter classes creates a Reader and Writer that you can use to read and write the contents from and to a file. Its most commonly used constructors are shown here:
FileReader(String filePath) throws FileNotFoundException FileWriter(String filePath) throws IOException FileWriter(String filePath, boolean mode) throws IOException File Content: Data.txt
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 32
File(Data. ata.txt) File Reading Example : Read File(Data.txt) Content byte by byte
import java.io.*; class ReadFileByteByByte { public static void main(String [] args) throws Exception { FileInputStream fis = new FileInputStream("Data.txt"); int ch; while(true) { //infinite loop ch = fis.read(); if(ch==-1) { //Check for EOF(End Of File) break; } System.out.print((char)ch); }//End Of While Block. }//End Of Main Method. }//End Of ReadFileByteByByte Class.
File(Data.txt) File Reading Example : Read File(Data.txt) Content Line By Line import java.io.*; class ReadFileLineByLine { public static void main(String [] args) throws Exception { FileInputStream fis = new FileInputStream("Data.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String line; while(true) { //infinite loop //Check for EOL(End Of Line) line = br.readLine(); if(line==null) { break; } System.out.println(line); }//End Of While Block. }//End Of Main Method. }//End Of ReadFileLineByLine Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 33
File(WriteD WriteData.txt) File Writing Example : Write Content to File(WriteData.txt) byte by byte
import java.io.*; class WriteFileByteByByte { public static void main(String [] args) throws Exception { FileOutputStream fos = new FileOutputStream("WriteData.txt"); String data = "Pepsi - Nothing Official About It."; for(int i=0;i<data.length();i++) { fos.write(data.charAt(i)); } //End Of For Loop System.out.print("Data Saved"); }//End Of Main Method. }//End Of WriteFileByteByByte Class.
Output:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 34
class Test{ public static void main(String[] args){ System.out.println("Hello"); System.out.println(5/0); System.out.println("Hello Again"); // do something else } }
output Hello Exception in thread "main" java.lang.ArithmeticException: / by zero at NewClass.main(NewClass.java:3) Throwing an Exception: When an error occurs within a method, the run-time system creates an object and hands it off to the method. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the relevant method is called throwing an exception. After a method throws an exception, the runtime system attempts to find the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 35
Exception Handler: The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception object to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. Exception: Handling an Exception: Java exception handling is managed via five keywords: try catch finally, throw and try, catch, finally, throw, throws. throws Briefly, here is how they work. Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch and handle it in some catch) rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw Any throw. exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block. This is the general form of an exception-handling block:
try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends }
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 36
Type Of Exception:
All exception types are subclasses of the built-in class Throwable Thus, Throwable. Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses into that two partition distinct exceptions
branches. One branch is headed by Exception Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception called RuntimeException Exception, RuntimeException.
Remember: Points To Remember: o java.lang.Exception and its sub classes are checked or compile time exception. o For checked exceptions, compiler prompts either to provide exception handler
block or exception to be thrown.
o o o o o o o
java.lang.RuntimeException and its sub classes are unchecked or run time exception. For unchecked exceptions, compiler does not prompt to provide handler. Exception handler blocks contains try catch and finally try, finally(optional) blocks. A try block can be associated with zero or more catch blocks. try block can be associated with zero or one finally block. Each try statement requires at least one catch or a finally block. We cannot write catch or finally block without try block.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 37
class Calculator { void divide(int a,int b) { try { System.out.println(Result : +(a/b)); } catch(ArithmeticException ae) { System.out.println("Error Found : "+ae.getMessage()); } finally { System.out.println("Task Completed."); } } // End Of Divide Method. } // End Of Calulator Class. class TestCalulator { public static void main(String [] ar) { Calculator ob = new Calculator(); ob.divide(20,10); ob.divide(20, 0); } //End Of Main Method. } //End Of TestCalculator Class.
Output:
Result : 2 Task Completed. Error Found : java.lang.ArithmeticException: /by zero Task Completed.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 38
throw Keyword:
So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Throwable The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. throw Example :
class ThrowDemo { public static void main(String args[]) { int a = 10; int b = 20; int c = a / b; if(c < 1){ ArithmeticException ae = new ArithmeticException(Denominator is Greater); throw ae; } System.out.println(Division : +c); }//End Of Main }//End Of ThrowDemo class
Output : Exception in thread "main" java.lang.ArithmeticException: Denominator is Greater. at NewClass.main(NewClass.java:8)
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 39
MultiMulti-Threading:
Unlike most other computer languages, Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.
The benefit of Javas multithreading is that the main loop/polling mechanism is eliminated. One thread can pause without stopping other parts of your program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere. Multithreading allows animation loops to sleep for a second between each frame without causing the whole system to pause. When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run.
suspended,
which its
suspends be
resumed,
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 40
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 41
class ThreadDemo { public static void main(String [] ar) { Thread t = Thread.currentThread(); System.out.printlb("Thread Name : "+t.getName()); System.out.printlb("Thread Priority : "+t.getPriority()); }//End Of Main }//End Of ThreadDemo.
Output:
import java.util.Date; class ClearScreen extends Thread { public void run() { while(true) { System.out.print("\r"); try { Thread.sleep(1000); }catch(Exception e){} } //End Of While Loop }//End Of run method }//End Of ClearScreen class class ThreadDemo { public static void main(String ... a)throws Exception { ClearScreen cs = new ClearScreen(); cs.start(); while(true) { Date d = new Date(); System.out.printf("%tr",d); Thread.sleep(1000); }//End Of While Loop }//End Of main method }//Enf Of ThreadDemo class
Output :
03:53:27 pm
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 43
Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. language-level support for it. Key to synchronization is the concept of the monitor (also called a semaphore). A As you will see, Java provides unique,
monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor.
Using Synchronized Methods Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. To enter an objects monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait.
Statement/Block The Synchronized Statement/Block While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. To understand why, consider the following. Imagine that you want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by you, but by a third party, and you do not have access to the source code. Thus, you cant add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 44
User Datagram Protocol (UDP) : sits next to TCP and can be used directly
to support fast, connectionless, unreliable transport of packets. UDP is a connection-less protocol that allows for packets of data to be transmitted between applications.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 45
Reserved Sockets
Once connected, a higher-level protocol ensues, which is dependent on which port you are using. TCP/IP reserves the lower 1,024 ports for specific protocols. Many of these will seem familiar to you if you have spent any time surfing the Internet. Port number 21 is for FTP, 23 is for Telnet, 25 is for e-mail, 79 is for finger, 80 is for HTTP and the list goes on. It is up to each protocol to determine how a client should interact with the port. You often hear the term client/server mentioned in the context of networking.
Server : A server is anything that has some resource that can be shared. There
are compute servers, which provide computing power; print servers, which manage a collection of printers; disk servers, which provide networked disk space; and web servers, which store web pages.
Client : A client is simply any other entity that wants to gain access to a
particular server. The interaction between client and server is just like the interaction between a lamp and an electrical socket. The power grid of the house is the server, and the lamp is a power client. The server is a permanently available resource, while the client is free to unplug after it is has been served.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 46
InetAddress class:
Whether you are making a phone call, sending mail, or establishing a connection across the Internet, addresses are fundamental. The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. Three commonly used InetAddress factory methods are shown here:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 47
InetAddress Example :
import java.net.*; class InetDemo { public static void main(String args[]) throws UnknownHostException { InetAddress address = InetAddress.getLocalHost(); System.out.println("Address : "+address); System.out.println("Host Address : "+address.getHostAddress()); System.out.println("Host Name : "+address.getHostName()); } // End Of main method. } // End Of InetDemo class.
OUTPUT :
ServerSocket class:
The java.net.ServerSocket class is used to create server that listen for either local machine or remote machine. The ServerSocket class has following contructors:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 48
If the ServerSocket constructor does not throw an exception, it means that our application has successfully bound to the specified port and is ready for client request. The ServerSocket class has following instance method:
Socket class:
The java.net.Socket class is design to connect to server socket and initiate protocol java.net.Socket exchanges. The client obtains a Socket object by instantiating one, whereas the sever obtains a Socket object from the return value of the accept() method. The Socket class has the following constructors:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 49
SOURCE : ServerConsole.java import java.io.*; import java.net.*; public class ServerConsole { public static void main(String [] args) { ServerSocket server=null; Socket client; try { server = new ServerSocket(1234); //1234 is an unused port number } catch (IOException ie) { System.out.println("Cannot open socket."); System.exit(1); } while(true) { try { client = server.accept(); OutputStream clientOut = client.getOutputStream(); PrintWriter pw = new PrintWriter(clientOut, true); InputStream clientIn = client.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 50
String msg = br.readLine(); System.out.println("Client : "+msg); msg = System.console().readLine("Server : "); pw.println(msg); } catch (IOException ie) {} }//End Of Main method }//End Of SeverConsole class. SOURCE : ClientConsole.java ClientConsole.java import java.io.*; import java.net.*; public class ClientConsole { public static void main(String args[]) { try { Socket client =new Socket("localhost", 1234); InputStream clientIn = client.getInputStream(); OutputStream clientOut = client.getOutputStream(); PrintWriter pw = new PrintWriter(clientOut,true); BufferedReader br = new BufferedReader(new InputStreamReader(clientIn)); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Client : "); pw.println(stdIn.readLine()); System.out.print("Server : "); System.out.println(br.readLine()); pw.close(); br.close(); client.close(); } catch (ConnectException ce) { System.out.println("Cannot connect to the server."); } catch (IOException ie) { System.out.println("I/O Error."); } }//End Of Main method }//End Of ClientConsole class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 51
Output:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 52
Collection API:
Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection. It provides a convenient API to many of the ADTs like maps, sets, lists, trees, arrays, hash tables, and other collections. All the classes and interfaces of collection framework are available in a java.util package. The java.util package contains one of Javas most powerful subsystems: collections. Collections were added by the initial release of Java 2, and enhanced by Java 2, version 1.4. A collection is a group of objects. Collection Framework Hierarchy :
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 53
java.util.Collection java.util.Collection Interface The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have.
Collection Example:
import java.util.*; class CollectionDemo { public static void main(String [] args) { List al = new ArrayList(); al.add("UCER"); al.add("UIT"); al.add("UIM"); al.add("UIP"); List v = new Vector(); v.addAll(al); Set s = new HashSet(); s.addAll(al); Set ss = new TreeSet(); ss.addAll(al); System.out.println("ArrayList : "+al); System.out.println("Vector : "+v); System.out.println("Set :"+s); System.out.println("Sorted Set : "+ss); }//End Of Main Method }//End Of CollectionDemo class
Output: Output: ArrayList : [UCER, UIT, UIM, UIP, UCER] Vector Set : [UCER, UIT, UIM, UIP, UCER] : [UIT, UCER, UIP, UIM] Sorted Set : [UCER, UIM, UIP, UIT] Note:
al.add("UCER");
Unsorted and Ordered Unsorted and Ordered Unordered and No Duplicate Sorted and No Duplicate
55
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai
values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. The methods declared by Map are:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 56
import java.util.*; class MapDemo { public static void main(String [] ar) { Map m = new TreeMap(); m.put(1,"Nuzhat Haleem); m.put(3,"Abhinav Mishra"); m.put(4,"Abhinav Srivastava"); m.put(2,"Abhinav Malviya); Set<Map.Entry> em = m.entrySet(); for(Map.Entry me : em) { System.out.println(me.getKey()+" : "+me.getValue()); } }//End Of Main Method. }//End Of Map Demo
Output: - Well get the elements in sorted order because of TreeMap 1 : 2 : 3 : 4 : Nuzhat Haleem Abhinav Malviya Abhinav Mishra Abhinav Srivastava
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 57
Java Beans:
The JavaBeans architecture is based on a component model which enables developers to create software units called components Java bean is a software component that is components. reusable in a variety of different environments. Java bean is just a java class with the following requirements: It has public constructor with no arguments. It has private properties. It has setters and getters methods for its properties. It may have some other general methods. If required it can be Serializable.
Application Builder Tool : When working with Java Beans, most developers use an application builder tool, a utility that enables you to configure a set of Beans, connect them together, and produce a working application. In general, Bean builder tools have the following capabilities. A palette is provided that lists all of the available Beans. As additional Beans are developed or purchased, they can be added to the palette. A worksheet is displayed that allows the designer to layout Beans in a graphical user interface. A designer may drag and drop a Bean from the palette to this worksheet. Special editors and customizers allow a Bean to be configured. This is the mechanism by which the behavior of a Bean may be adapted for a particular environment. Capabilities exist to interconnect Beans. This means that events generated by one component are mapped to method invocations on other components. When a collection of Beans has been configured and connected, it is possible to save all of this information in a persistent storage area. At a later time, this information can then be used to restore the state of the application.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 58
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 59
A manifest file may reference several .class files. If a .class file is a Java Bean, its entry must be immediately followed by the line Java-Bean: True. The JAR Utility A utility is used to generate a JAR file. Its syntax is shown here: jar options files Creating a JAR File The following command creates a JAR file named Xyz.jar that contains all of the .class and .gif files in the current directory: jar cf Xyz.jar *.class *.gif Option Description
c C f i m M t u v x 0 A new archive is to be created. Change directories during command execution. first element in the file list is the name of the archive that is to be created or accessed. Index information should be provided. The second element in the file list is the name of the external manifest file. Manifest file not created. The archive contents should be tabulated. Update existing JAR file. Verbose output should be provided by the utility as it executes. Files are to be extracted from the archive. Do not use compression.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 60
Introspection
Introspection is the process of analyzing a Bean to determine its capabilities. This is an essential
feature of the Java Beans There are two ways in which the developer of a Bean can indicate which of its properties, events, and methods should be exposed by an application builder tool. With the first method, simple naming conventions are used. In the second way, an additional class is provided that explicitly supplies this information.
Design Patterns for Properties A property is a subset of a Beans state. The values assigned to the properties determine
the behavior and appearance of that component. Simple Properties A simple property has a single value. It can be identified by the following design patterns, where N is the name of the property and T is its type.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 61
Example :
public class MediaPlayer { private String name; //Simple Property private boolean on; // Boolean Property private String [] playlist; //Indexed Property public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isOn() { return on; } public boolean getOn() { return on; } public void setOn(boolean on) { this.on = on; } public String getPlayList(int index) { return playList[index]; } public void setPlayList(int index, String value) { this.playList[index] = value; } public String [] getPlayList() { return playList; } public void setPlayList(String [] playList) { this.playList = playList; } }//End Of MediaPlayer Class
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 62
Design Patterns for Events Beans use the delegation event model that was discussed earlier in this book. Beans can generate events and send them to other objects. These can be identified by the following design patterns, where T is the type of the event:
public class PlayList { public void addPlayListListener(PlayListListener tl) { ....... .. } public void removePlayListListener(PlayListListener tl) { .......... } }//End Of PlayList class
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 63
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 64
This class analyzes a Bean and constructs a BeanInfo object that describes the component. Instances of this class describe a method of a Bean. This event is generated when bound or constrained properties are changed. It is sent to objects that registered an interest in these events and implement either the PropertyChangeListener or VetoableChangeListener interfaces. Beans that support bound properties can use this class to notify PropertyChangeListener objects.
PropertyChangeSupport
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 66
Types of Enterprise Beans There are three types of enterprise beans. Enterprise Bean Type and Purpose Session Bean Entity Bean Message-Driven Bean Performs a task for a client; implements a web service. Represents a business entity object that exists in persistent storage. Acts as a listener for the Java Message Service API, processing messages asynchronously.
Session Beans:
What Is a Session Bean? A session bean represents a single client inside the Application Server. To access an application that is deployed on the server, the client invokes the session beans methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server. As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one user. Like an interactive session, a session bean is not persistent. (That is, its data is not saved to a database.) When the client terminates, its session bean appears to terminate and is no longer associated with the client. There are two types of session beans: stateless and stateful. Beans: Stateless Session Beans: A stateless session bean does not maintain a conversational state for the client. When a client invokes the method of a stateless bean, the beans instance variables may contain a state, but only for the duration of the invocation. When the method is finished, the state is no longer retained. Beans: Stateful Session Beans: The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts (talks) with its bean, this state is often called the conversational
state.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 68
Entity Beans:
What Is an Entity Bean? An entity bean represents a business object in a persistent storage mechanism. Some examples of business objects are customers, orders, and products. In the Application Server, the persistent storage mechanism is a relational database. Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table. There are two types of entity beans: ContainerPersistence(CMP) Container-Managed Persistence(CMP) Entity Bean : CMP beans persistence is managed by the EJB container which is responsible for saving and retrieving the data from the underlying database for us. CMP beans are easier to develop and work well with database access. BeanPersistence(BMP) Bean-Managed Persistence(BMP) Entity Bean : BMP beans persistence has to be managed by the EJB itself. While it gives more control to the EJB developer to save and retrieve data, they are harder to build as more coding is required. On use of BMP beans would be to retrieve and save data from non-database sources like XML files.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Bhanu Pratap Rai 69