You are on page 1of 784

1

Contents

Chapter-1: Object Oriented Programming Fundamentals Chapter-2: Evolution of java programming language Chapter-3: Basic elements of java Chapter-4: Operators in java Chapter-5: Conditional statements and loops Chapter-6: Class fundamentals Chapter-7: Object reference Chapter-8: Array in java Chapter-9: Inheritance Chapter-10: Inner class Chapter-11: Exception Handling Chapter-12: Package Chapter-13: JAR File Chapter-14: String Chapter-15: StringBuffer Chapter-16: Wrapper class Chapter-17: Taking the input from keyboard Chapter-18: Java Native Interface Chapter-19: Multithreading Chapter-20: Generics

Chapter-21: Files and Streams Chapter-22: Exploring java.lang package Chapter-23: java.util package(part-I):Collection Framework Chapter-24: java.util package(part-II) Chapter-25:The Applets Chapter-26:The java.awt package Chapter-27:Java Foundation classes Chapter-28:The java.net package Chapter-29:The java.sql package Chapter-30:Brain Teasers

Chapter1:

Object oriented programming fundamentals


While teaching new comers in java the first question that comes in my mind to ask is What is object. All most all the new comer in java knows C++. So the question is quite obvious & I expect to get a nice answer. The answer usually is: OBJECT IS AN INSTANCE OF A CLASS which is absolutely correct. Then, the next question from my side is WHAT EXACTLY A CLASS IS & CAN YOU GIVE ME A REAL LIFE EXAMPLE OF AN OBJECT & surprisingly most of the time no satisfactory answers. They know the definition, but they have not visualized concept of object. Before migrating from traditional programming world to OOP (Object Oriented Programming) world, one has to have a strong fundamental concept of object. Object is the instance of a class. Class is a template, i.e. it contains various characteristics or attributes which were satisfied by the object belonging to it, e.g. if human is a class, then SAM KOOL (Obliviously Name of a MAN!!) is an object of human class.

Object is the entity which communicates with the environment. Class is an abstract concept. It is merely a collection of attributes & characteristics. Object gives life to those characteristics present in the class, & that is why object can communicate with the surrounding. Since class is a template it doesnt have memory but, the object has. Class template combines data and functions or methods to manipulate those data. The data present in an object can only be manipulated by the methods or functions belonging to that object.

Overview of Object Oriented Programming Way back in 1960s OOP gives its first hint of birth. In traditional language like C, FORTRAN logic pays the highest priority. One question I would like to ask reader whether the logic should have highest priority in every aspect of programming. My answer is no, because logic always whirls around data. Data should always enjoy highest priority. Programmer should concentrate on data security & integrity while developing the software. Procedural programming language does not have the tools to encapsulate the data to prevent it to be accessed by any random methods. Along with this fact code reusability is another issue that is not achieved by procedural programming language. With the increase of complexity of software, security of data, code reusability, polymorphic behavior of programs & communication among various entities has to be addressed perfectly, but traditional programming language has no answer at all. Then it comes Simula, the first OOP language has answers to these issues. It introduces the concept of class, object, method, virtual methods, inheritance & polymorphism. Object Oriented Programming is simply a collection of objects where objects interact with each other through the methods that have been embedded in them. You can think of a object as a self sufficient machine. What I mean to convey here is that like a machine object has concretely defined way to take input, it has separate component to process the input & has completely unique component to produce the output. Each object has unique identification & existence. In Object oriented Programming the data & the operations to access & manipulate the data are closely entangled to each other.

Quarks of OOP Class: class is an abstract concept. It is simply a template. When a class is instantiated object is created. Class contains data & methods to manipulate the data. Class is simply a blueprint of a thing. In programming prospective class encapsulate various primitive data types as well as user defined data types.

Object Object is the instance of a class. It is a bundle of variables and related methods. The basic idea behind an object is the simulation of data & methods to manipulate them. Method Methods are the entities through which objects interacts with the external environment. Whatever object is going do, can only be done through the methods. Methods are concretely entangled with a particular object. Let me explain it through an example. Assume that MyClass is a user defined class

Example-1 Class MyClass { Data_1; Data_2; Method_to_manipulate_data_1() { Required codes } }; If o1 & o2 are the two objects of MyClass. o2 cannot manipulate its Data_1 through the use of Method_to_manipulat_data_1() of o1 just like you cannot eat for yourself through your friends mouth.

Message passing The process by which objects communicate with each Obliviously communication can only be done through methods. Abstraction Abstraction means simplification complex reality of a problem. In lay man language abstraction means, HIDING THE DETAILS. Programmer hides the complexity of the program from the end user. End users only have the methods or functions to interact with the data without knowing how the manipulation is done. Consider the case of a cell phone. Cell phone users know only about various functionalities available in the phone without knowing how they are implemented. Encapsulation: Encapsulation means binding both code and data together. Code implies the methods or functions that manipulate the data. This technique protects the data from outside interference & behaves as protective wrapper. User can interact with the data through the methods that are available in the specific object. Apart from those available methods it is not possible for user to manipulate the data. But, in case of structured programming language like C data can be manipulated by any function which decreases the security & integrity of data e.g. other.

Example-2

struct xxx { int a; }; main( ) { struct xxx x; void fun1(struct xxx*); x.a=9; fun1(&x); printf(%d,x.a); } void fun1(struct xxx *ptr) { ptr->a=10; } The output is 10. Structured programming language gives a mean to handle the real world data. But, any function can manipulate the data belonging to any structure variable as shown in the above example. Encapsulation prevents these entire unsecured mean to modify & access the data. Each method has well defined task & they are strongly entangled with the corresponding object. Encapsulation also abstracts the complexity involve in a class from the end user. Inheritance: Inheritance is a technique by which an object acquires the feature of other object along with its own features. The object from which

property is acquired is known as parent object & the object which acquires the property is known as child object. It depends upon the programmer to decide what the properties are that has to be inherited from parent to child. In java the parent class is known as super class & the child class is known as sub class. Sub class can add new feature to it along with the inherited properties. Inheritance facilitates code reusability.

Why inheritance is required? Suppose you are developing software for market complex whose task is to show the viewer what are the various items available. If you are developing this project in C then you are going to declare a structure

Example-3: struct xxx{

10

char item1_name[20]; char item2_name[20]; char item3_name[20]; char item4_name[20]; char item5_name[20]; };

You have designed the functions to show these items to the customers. In latter stage if some new item is introduced than you have to again change the structure template. But, in case of OOP just you have to create the sub class or child class, then all the existing attributes are inherited to the sub class & you just add the new items to it. Great!! Job is over & quite simple also. By creating the base class you can add new items in future to the existing class. In this way you can also add new methods to the sub-class to improve functionality & accessibility.

Polymorphism: Polymorphism in OOP is the technique through which when a method is called invocation of appropriate method is performed by the appropriate type specification. Only name is not enough, argument type is important along with the contents of the invoking object. In lay man language polymorphism means one name many forms. In OOP terminology polymorphism implies one method performing many tasks. A novice object oriented programmer definitely going to ask Do the programmers really have scarcity of name?, again lets go through an example. In the early version of cell phones one can only send text message. For sending the messages assume the function is send which has the following signature. return_acknowledgement send(text_data,receiver_name); All the cell-phone users are quite comfortable with send function. But when multimedia messaging technique is discovered, send function need to be

11

redefined. In traditional programming technique one can not have same named two or more function. One solution is that provide another function a totally new one to send mms. Again this is awful because one function to send text message and another one for mms. So the best solution to this situation is the use of polymorphism through which we can have another send function to send mms. In OOP a method is recognized through its entire signature. Entire signature includes name of the function along with the parameters it is taking. return_acknowledgement send (mms_data,receiver_name); These two functions are entirely different, see the signature. Great solution!!!.Finally Novice Object Oriented programmer got the reason for the birth Object Oriented Programming. Conclusion: Logic is highly important for programming. But for which we have to program & answer is data. Procedural language helps you to develop logic but remain silent when it comes for the security & integrity of data. With the evolution of distributed application, data is not stationary. What do you think when sends some thing in internet how it goes? Not in raw data format but in the form of objects. OOP provides a wrapper to the data which is almost impossible to penetrate.

12

Chapter: 2

Evolution of java programming language.


Way back in 1991 James Gosling who took his first step in the development of Java programming language. Previously java was called as Oak, (yes! Name of a tree). Then the name Green comes finally ended with Java. Java is developed by SUN Microsystem. Most of its syntax has been derived from C/C++. SUN released the 1st JDK1.0 in 1995. It promises to the programmer as a platform independent language. The language is syntactically similar to C and C++ but works on a higher abstraction level as compared to them. First Java 1.0 was released by Sun Microsystem in 1995. "Write Once, Run Anywhere" (WORA) was the tagline for java 1.0.It was secure and allowed network and file-access restrictions. Very soon java got popular due to which java 1.2 is released in December 1998.After the success of java 1.2 sun launched the new and different versions of java for different purposes,e.g J2EE is for enterprise applications i.e for server side programming , J2ME for mobile applications , J2SE is for Standard Edition. Finally java evolved as: A simple and object oriented language. A robust and secure language. A architecture neutral and portable language. A language with high performance rate. A language which is interpreted, multi threaded, and dynamic. Portability is one of the most important characteristics , it means the compile byte-codes i.e. the class file written in the Java language runs similarly independent of the system hardware and operating system i.e write a code once, compile it once, and run it anywhere. The platform independent feature of java is achieved by compiling the java source code not to a machine code but to a intermediate code called byte codes. Byte codes are collection of instructions for java virtual machine which are later interpreted to native codes. Java provides a reach set library functions for graphics designing, applet programs, GUI design through swing, remote method invocation & for multi threading applications. Some virtual machine implements techniques for the conversion java source code to native machine codes. In Linux gcj compiler converts java source code to native machine codes resulting faster execution of java programs. When java file is compiled class file is created. Class file is merely a collection of byte-codes. Byte codes are then interpreted by JVM. Interpretation is quite slow. Therefore the execution of java program is slow as compared to executable native codes. This is great performance issue for java program. Over the years effort has given for the increase the execution of java program. Just In Time compiler is a solution to improve the performance. By the implementation of JIT compiler when for the first time the byte codes are translated to native codes, it caches it. There is another technique in which java source code is directly converted to machine readable native codes. This is done by AOT (Ahead Of Time) compiler. This technique increases the performance because native code executes faster than byte codes. GCJ compiler available in Linux is a AOT compiler. AOT compilation disables the most important feature in java, i.e. the platform independence feature. I have seen most of the new comers in java, treat it as a language having more functionality, abstraction & a lot of similarity with C/C++. This because of large set

13 of keywords & operators are matched with keywords & operators of C/C++. But, this is not true at all. Java survives & grows in this world because of its own unique identity. Let me address on those issues. y Java has neither preprocessor directive nor header files. Predefined methods & classes are available to java through the packages. Packages are collection of class files. y All the methods, variables & all sorts of codes always reside within the class template. y Through wrapper class java provides an object oriented view of primitive data type like integer, float, byte, char, boolean etc. This wrapper class package has enabled java as a complete object oriented programming language. y Java does not support global variables. In C++ global variables does not belong to a particular class & can be modified by any function. This is the unsecure mean of data manipulation. Java has restricted this controversial issue by not supporting the global variable. y Memory management is not provided to the programmer. Unused data is deleted from memory by the invocation of the demon thread named garbage collector. Memory leak problem is quite optimized in java. y Non existence of memory pointers. Memory pointers are always threat to any automated system. These are used to break the security & can crash a system. Not having these memory pointers is an advantage to java. y During any assignment operation java strictly follows type checking. Due to this feature precession loss or data loss is minimal in java. y Java strictly follows type safety. Programmer can not arbitrarily cast on datatype to another one. y Local variables in side a method can be declared when they are needed. y Implementation of floating point variables is platform dependent. There fore java provides the keyword strictfp to maintain its platform independent property. y Union provides memory over lapping feature which is discarded in java. y No typdef to create alias of data-type. y Array index out of bound is checked in java to prevent the unauthorized manipulation of memory. WHY JAVA ? y Platform Independence The Write-Once-Run-Anywhere (Java Virtual Machine for different platforms usually required), concept is strictly followed. y Introduction of wrapper class makes java a complete object oriented programming language. y When a java source file is compiled, class file is generated which is collection of byte-codes. These byte-codes are latter interpreted to native codes by JVM. Byte-codes are portable. y Byte codes are least affected by virus as compared to executable files. If it is affected, then JVM recognize then & never allow them to be executed. y Built in support for exception handling. y Built in support for multi threading application development.

14 Java provides communication with C/C++ source codes through Java Native Interface. By the use of Compiler class java source code can be compiled to native machine codes. Package like java.lang.SecurityManager provides permission to the object to have an access on variables, files & other resources. Built in support for networking.

y y y y

Virtual Machine When you read the java language, java virtual machine is quite a familiar term. But, what is a virtual machine? The philosophy behind virtual machine is to abstract the system hardware of a single computer in to several different virtual systems such that it makes the user to feel that different environment or platform is implemented on a single system.

15 Diagram:

Diagram-2

16

System that implement the virtual machine. Each virtual machine provides different environment or platform to the user. According to the platform provided, only a particular set of processes can be executed in a particular virtual machine. Processes those are executed in Virtual Machine-1 cannot be executed in Virtual Machine-2. Implicitly these virtual machine perform appropriate system call for the execution of different processes.

When different processes are running, virtual machine makes the end user to feel that different processes are running not only in different platform, but also in different CPUs. This illusion is created by the implementation of different CPU scheduling algorithm by the underlying OS.

17 The Java Virtual Machine. JVM consists of following components shown in the diagram.

These components are abstract in nature. It completely depend upon the designer to develop these components. Class loader Sub System: when a java file is compiled class file is generated. When we invoke the class file for execution class loader subsystem is called by Java Virtual Machine to load the class file into JVM memory space. The task of Class loader sub system is to load the classes & interfaces in the memory. In Java Virtual Machine there are two types of loader is available. A boot strap loader & other one is user defined class loader. The job of the class loader sub-system is not only to load the class file but also it checks correctness of the loaded class, allocates required memory to static variables (static variables are explained in class fundamental). The class loader sub-system performs its task in sequential way 1st: Loading of class file. 2nd: Checks the correctness of class file. If you have read the class file by notepad or word-pad in a windows system, then that class file cannot be executed. For this behavior class

18 loader sub-system is responsible. 3rd: allocates memory to static variables. Static variables are otherwise known as class variables. They are the property of classes rather than the property of objects. 4th: transformation of symbolic reference into direct reference. 5th: sets default value of all static variables. Method Area: it is a logical memory component of JVM. This logical section of memory holds the information about classes & interfaces. Static variables are treated as class variable, because they take memory from method area. The size of the method area is not fixed. It shrinks & expands according to the size of the application. Heap: In java when an object or array is created, memory is allocated to them from heap. The Java virtual machine through the use of new operator allocates memory from the heap for a new object. Java does not provide any technique to the programmer to free the memory that has been allocated by new operator. Once memory is allocated from heap to an object or array, programmer cannot free the memory. The JVM has demon thread known as Garbage Collector whose task is to free those objects from heap whose reference is not alive in stack. Java stacks: Method codes are stored inside method area. When method starts execution, it needs memory because of the local variables & the arguments it has taken. For this purpose java stack is there. All the local variables & the arguments method have taken acquires memory from stack. PC registers: It keeps track of the sequence of execution of the program. PC registers or Program Counter registers holds the address of the instruction to be executed next. Native method stacks: When a java application invokes a native method, that application is not going to use Java stack only, rather it uses the native method stack also for the execution of native methods. Native methods are generally in C/C++ & executed in side native method stack. The libraries required for the execution of native methods are available to the Java Virtual Machine through Java Native Interface. Execution Engine: Execution engine is there to generate & execute the java byte code. It contains an interpreter & Just In Time Compiler. Java Run-time Environment Byte-Codes Byte code is the unique characteristic property of java programming language. It is something like a normal text file. Thats why it cannot be affected by virus. You can say that it is a intermediate human readable source & machine readable source. Byte codes are plat form independent & thats why JVM is plat form dependent to make the java programming as platform independent. Just like C source codes are portable, byte codes are portable. The cost of platform independence behavior of byte codes is paid by its slower execution speed when it is compared with execution of native codes even in just in time compiler. How to Construct the FAMOUS Hello, World!!! Program in JAVA Dont get surprised with the name its just our first program in java that we are going to write. Example public class hello { public static void main(String ag[]) { System.out.println(Hello, World!!!);

19 } } Output: Hello, World!!! 1: Now in the above program we have declared the class containing the main method as public so we have to save it in a file which has the same name as that of class name. e.g. hello.java 2: after the file is saved we have to compile the hello.java file using the javac command. e.g. javac hello.java 3: After compilation hello.class file will be generated. Then to get the output we have to run the .class file using java command. e.g.: java hello note : if we are not declaring the class containing the main method as public , then we can save the file in any name. But when we will compile the .java file then the name of the class file generated will be same to the name of the class containing the main method. To get the output we have to run the program using the name of the .class file. Example-2 xyz.java class hello { public static void main (String ag []) { System.out.println(Hello); } } Output: Hello To get the output: 1: javac xyz.java 2: the class file will be generated in name of hello.class. Now run it with the java command to get the output. 3: java hello Restrictions:- 1:-In java top level class is declared either through public or no access modifier. 2:-When the class is declared through public access modifier class name must be same as the file name. 3:-When the class is declared through no access modifier class name and file name may same or may not

20

CHAPTER 3:

Basic Elements of JAVA 1. IDENTIFIERS


Identifier are the set of rules for giving the names of the variables of primitive data types, methods, user defined classes, interfaces and reference variables of classes. Java is said to be strongly typed language, means you must declare the identifier & initialize it before it is used. Identifiers should not begin with a number and an identifier should not contain these following characters ; {} () // [] * \ + , ; # % ! ^.

21

Like C/C++ (dollar)$ &(underscore) _ is allowed in java.

KEYWORDS

The table below lists the keywords, or reserved words, as of Java 5.0. We will discuss the meaning and function of most of them during this course.

KEYWORDS abstract

assert

boolean

break byte case

DESCRIPTION it is used to declare a class or method to be abstract. An abstract method does not contain its body. Abstarct methods only have the declaration, but their body is defined else where. In interface the methods are by default public & abstract which has to be defined concretely where these interfaces are implemented. This keyword was introduced in J2SE 1.4. This keyword is used in the program to check whether a specified condition is true or not. If the condition is true then the program execute in a normal way otherwise an AssertionError is thrown. Boolean is a primitive data type in java. It can have either true or false value. Internally Boolean is represented as integral value in JVM. When Boolean variable is use as instance or static variable its default vaue is false. When ever a condition checking is done in java, Boolean value is returned by the condition checking operator. Size of a Boolean variable is 8 bit. Break keyword is used in loops & switch case. It is particularly used to break the normal flow of the program. Byte is a primitive data type in java. Its size is 1byte or 8 bit. Default vale of byte variable when it is used as instance variable or static variable is zero. The case keyword is used to create individual cases in a switch statement. Case clause preceded with integral constant & enum members. In place integer constant you can have character constants and bytes since they are auto converted to integer.

22

catch

char class const continue

default

do

This is a component of exception handling mechanism. Always follows the try block to catch the exception object thrown from catch block. It is a primitive data type in java. Unlike c/c++ it is of 16 bit used to hold the Unicode character. Class is the key word through which programmer defines the user defined class template. const keyword is not available to the programmer. When continue keyword is encountered the control jumps to the condition checking part of do, do-while loop & the increment part of for loop . Continue statement can be followed with a level name to resume execution from the specified level name. The default is an optional component of switch case. When no condition is satisfied default case is executed in switch case. Solely do has no existence. It always entangled with while o form the do-while loop. It is a primitive data type in java of 64 bit used to store real numbers. It is used along with if statement following the if block. Used for condition checking. When if part is not executed control jumps to else part. Solely else has no existance. In an if-else statement else part is optional. JDK 1.5 has introduces this key word used to create constant. Enum is a class in java. Extend key word is used to support inheritance in java A boolean constant.. Final keyword is used in case of variables to create constants. Where used in case of class, that class cannot be inherited. When used in case of methods, that method cannot be overridden. It is a component of exception handling in java. whenever try block is executed , it is mandatory that the codes inside the catch block has to be executed. This keyword is used to store real numbers. Its size is 32 bit.

double else

enum extends false final

finally

float

23

for Goto If implements import instanceof int

It is used to create looping statement. This keyword is not available to the java programmer. It is used for condition checking purpose It is used to inherit multiple number of interfaces It is used to import existing packages. Packages are the collection of class files. It is a binary operator used to determine the parent child relationship between two objects. It is used to store the natural numbers. Its size is 4 bytes

interface

long native new null package private

protected public return short static

Interface is used to support multiple inheritance in java. By default all the methods declared are public and abstract. To use the methods declared inside a interface u have to override it in the child class. It is used to store integral values . its size is 8 bytes Like abstract method the body of native method is defined elsewhere in foreign language. Used to create an object. It is a operator. A reference literal value. Package is a collection of class files. Package keyword is used to declare a package. It is a access modifier. When an entity inside a class is declared as private it cannot be inherited to its child class. Private variables are only accessed inside the class. It is a access specifier. Protected entities are accessed out side the package through inheritance. It is an access specifier. Public variables can be accessed from anywhere. Used to return control from method along with a value. Primitive data type in java. It is of 8 bit size. Static keyword is associate with method and constructor. Static variables are treated as class variable. Static entities are accessed through class name.

24

strictfp super

Floating point numbers are stored in the memory depending upon the platforms to have a platform independent representation of real numbers strictfp is used Used to acess the parent class element.

switch Switch case is used for condition checking. synchronized Synchronized keyword is used to avoid dead lock in thread. Synchronized keyword can be used for block or method. this This keyword is used by object to refer to itself. throw It is a component of java exception handling mechanism. Used throw an exception object.

throws

transient true try void volatile

Throws keyword Is used along with the method signature. It used by the called method to throw the UnhandledException to the calling method. Transient keyword is used for those variables if programmer does not want to strew the variable persistently. A boolean constant. A component of exception handling mechanism of java. All the exception generated codes are embedded inside try block If a method does not return anything then void is used to denote its return type during the definition of method. Volatile is used along with a variable name. volatile variable changes their value without informing the JVM. System clock values are stored in volatile variable. While is a key word in java used for creating a loop.

while

25

Java Primitive Data Types Type byte short int long Values Natural numbers Natural numbers Natural numbers Natural numbers Size 8 bits 16 bits 32 bits 64 bits Range -128 to 127 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807 +/-1.4E-45 to +/3.4028235E+38, +/-infinity, +/-0, NAN +/-4.9E-324 to +/1.7976931348623157E+308, +/-infinity, +/-0, NaN \u0000 to \uFFFF

Default 0 0 0 0

float

Real numbers

0.0

32 bits

double

Real numbers

0.0

64 bits

char

Unicode character \u0000 16 bits 1 bit used in 32 bit integer

boolean

true, false

false

NA

26 Chapter-4

Operator

Since java maintains most of the syntactical similarity with C/C++ there fore most of the operators those are available in C/C++ are also available in java. In C++ operators can be overloaded by the programmer, but that is not possible in java. Java provides user a large set of operators to the programmers. Operators acts upon operand to provide desired output. e.g. a=b+c a,b,c are operand where as + and = are operators. There is an important aspect that has to be understood by the reader before getting in to the depth of the operators i.e. how the positive & negative integers are stored in memory. int x=12. x will be stored in the memory in the form of binary as 00000000 00000000 00000000 00001100 but things are became twisted when it comes for negative numbers. Negative numbers are stored in the form of twos complement & left most bit is treated as sign bit. When the value of sign bit is one, the number is a negative number. Lets have an example to clear the idea. Int x=-12. How to have twos complement form 1: convert the no. into binary leaving the negative sign. The binary form of 12 is 00000000 00000000 00000000 00001100 2: reverse the polarity of each bit to ones complement of the number 11111111 11111111 11111111 11110011 3: add 1 to have the final result that is twos complement 11111111 11111111 11111111 11110100 in this format -12 is stored in memory.

27

Operators available to the java programmer Type:1 (Unary Operators) + ++ -() ~ ! Unary plus Unary minus Postfix increment increment Postfix decrement Casting operator Bitwise inversion Boolean complement operator & prefix

Unary Plus Operator & minus operator Unary plus & minus operator is used to represent positive & negative number. Programs below will give you a clear picture. I dont think explanations are required. Output in each program is simple & straight forward. class Demo { public static void main(String []args) { int x=12; System.out.print(-x); } } Output: -12

28 class Demo { public static void main(String[]args) { int x=12; System.out.print(+x); } } Output: 12

class Demo { public static void main(String[]args) { int x=12; System.out.print(-+x); } } Output: -12

class Demo { public static void main(String[]args) { int x=12; System.out.print(-(-x)); } } Output: 12

29

The postfix operator: class Demo { public static void main(String args[]) { int i=6; int j=i++; System.out.println(i); System.out.println(j); } } Output: 7 6 Explanation: Variable i is initialized to 6. Incase post fix increment operation use of the variable enjoys the highest priority where as increment is done in second phase. In the statement j=i++ 1st value of i i.e. 6 is assigned to j & then i is incremented to 7. Now you can think of why the output is 7 & 6. See another interesting behavior of post fix operation class Demo { public static void main(String args[]){ int i=6; i=i++;

30 System.out.println(i);

} } Output 6 Foxed dear!!! See I have already said in post fix operation use of the variable enjoys highest priority. In the above piece of code since assignment & increment is done over one variable the increment part is rejected because of its lower privilege. Its a rule. Similarly you can try for postfix decrement operator. Prefix operation class Demo { public static void main(String args[]){ int i=6; int j=++i; System.out.println(i); System.out.println(j); } } Output 7 7 In the above code I have used the pre fix increment operator. In this case increment enjoys the highest priority. So first value of i is incremented to 7 & then it is assigned to j.

31 class Demo { public static void main(String args[]){ int i=6; i=++i; System.out.println(i);

} } Output 7 Since increment enjoys the highest priority output is straight forward.

Cast Operator: (type) Casting is used to convert the value of one type to another. In other words casting is used to explicitly convert the value of one type to another. The result of cast is a new reference or a value. In java not only data types are casted but also object is casted. In java casting is of two types: y y Casting of primitive data types Casting of object type

Casting primitive types: Casting between primitive types allows explicitly convert one primitive data type into another. In java boolean data type cannot be casted to any data type. If you want to cast a smaller data type to a larger one then implicit casting is done in java.

32

The larger type provides more precision than the smaller type and hence no information is lost when the value is cast. When the larger type is assign to the smaller type then explicit cast must be required. See the diagram if the flow of data moves from opposite direction then explicit conversion is required. Example: public class Cast1 { public static void main(String args[]) { int i=10; long l=1; double d=3.4; byte b; b=(byte)i; // type casting System.out.println(b); i=(int)l; // type casting

System.out.println(i); l=(long)d; // type casting System.out.println(l); }

33 } Output:10 1 3

Casting Object Instance of one class can be casted to instance of another class. Restriction of this principle is that class that is being casted must be related by inheritance. An instance of the sub class is casted when the super class instance is assign to the sub class object as the sub class contains all the information that the super class contains.

Example: class Test1 { void show() { System.out.println("Super Class"); } } class Test2 extends Test1 { void display() { System.out.println("Sub Class"); }

34 } public class Test { public static void main(String args[]) { Test1 t1=new Test1(); Test2 t2=(Test2)t1; t2.show(); t2.display(); } } Output:The program compiles successfully but at the runtime the program is terminated by Exception in thread main java.lang.ClassCastException

Bit wise inversion operator: (~) class Demo{ public static void main(String args[]) { int x=12; System.out.println(~x); }} Output : -13 Lets have a deeper look. Binary representation of x is 00000000 00000000 00000000 00001100 . When ~ operator is operated on x then 0 turns to 1 & 1 turns to 0. Hence the value of x is now

35 11111111 11111111 11111111 11110011 . The left most bit is the sign bit, since it is turned to 1 because of ~ operator, therefore the number becomes a negative number. All the negative numbers are stored in memory in the form of twos complement. Twos complement= 1s complement+1 To get the final out put 1st determine the ones complement of 111111111 11111111 11111111 11110011 which is(by converting 0 to 1 & 1 to 0) 10000000 00000000 00000000 00001100 here sign bit never change its polarity. Finally add 1 & the output is 10000000 00000000 00000000 00001101 Sign bit says its a negative number & rest other says the final output is -13. Lets have another example class Demo{ public static void main(String args[]) { int x=-12; System.out.println(~x); }} Output: 11 Here the number is a negative number. It will be stored in the memory in two complement form. 11111111 11111111 11111111 11110100 When ~ is operated on these bits then the output will be 0000000 0000000 00000000 00001011. This is the binary form of 11 got it! Boolean complement operator As the name suggests this operator work only for Boolean data type, other wise compilation error will occour. class Demo {

36 public static void main(String[]args) { boolean x=true; System.out.print(!x); } } Output: false This operator just inverse the value of Boolean variable. Type 2 (Binary Operators) Arithmetic operators + ,-, *, /, %

Assignment operators

= ,+=,-=,*=,/=,%=,&=,^=,|=

Conditional operator

==,>=,<=,>,<

Bitwise operator

&,|,^

Shift operator

>>,<<,>>>

instanceof operator

Short circuit operator

&&,||

37 Arithmetic operators Arithmetic operators are used to evaluate mathematical expressions. All the operators are simple & their behavior is straight forward. A novice programmer may be confused about the %, the modulus operator. This operator is used to determine the remainder when a division is performed. See the example class Demo { public static void main(String[]args) { int x=12; int y=5; x=x%y; System.out.print(x); } } Output: 2

Assignment operators An interesting fact about assignment operator: class Thread1 { public static void main(String args[]){ byte i=10; byte j=9; i=j+i; System.out.println(i); } }

38 Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte at demo.Thread1.main(Thread1.java:9) see the output is compilation error. Why ? because = operator accepts an integer variable in the left hand side when arithmetic operation is done. But, check the codes below class Thread1 { public static void main(String args[]){ byte i=10; byte j=9; i+=j; System.out.println(i); } } Output 19 The reason here is that += is overloaded to return appropriate type. Similarly other assignment operators like -=,*=,/=,%=,^=,&=,|= is over loaded. Remember that in assignment operator the left hand side value is assigned to right hand side only if the right hand side is a similar or bigger data-type with respect to left hand side. class Demo { public static void main(String[]args) { int x; byte y=5; x=y; System.out.print(x); }

39 } Output=5. Right hand side is an integer variable where as left hand side is a byte variable. Hence there is no problem in assignment. But, if the situation is reversed then compilation error will be generated. See the codes below.

class Demo { public static void main(String[]args) { byte x; int y=5; x=y; System.out.print(x); } } Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte at demo.Demo.main(Demo.java:9)

Conditional Operators == equals to operator != Not equal to >Greater than < Smaller than

>=greater than equals to <= smaller than equals to These operators are particularly useful in conditional statements & loops.

class demo1 {

40 public static void main(String ar[]) { int i = 5; int j= 10;

if(i==j) System.out.println("equall"); else System.out.println("not equall");

if(i!=j) System.out.println("equall"); else System.out.println("not equall");

if(i>j) System.out.println("equall"); else System.out.println("not equall");

if(i<j) System.out.println("equall"); else

41 System.out.println("not equall");

i=20; if(i>=j) System.out.println("equall"); else System.out.println("not equall");

if(i<=j) System.out.println("equall"); else System.out.println("not equall");

} }

Output : not equall equall not equall equall equall not equall

Codes & the out clearly explain the behavior of all the conditional operators.

42 Bitwise Operators ~ & | ^ >> << Bitwise inversion operator Logical AND Logical OR Logical XOR(exclusive OR) Bitwise Right Shift Bitwise Left Shift

>>> Bitwise Unsigned Right Shift Lets have logic table of first four bit wise operators to have a primary idea, then we will go for codes. x 0 0 1 1 y 0 1 0 1 ~x 1 1 0 0 ~y 1 0 1 0 x&y x|y 0 0 0 1 0 1 1 1 x^y 0 1 1 0

Bitwise inversion operator is explained earlier in unary operator. Bitwise and operator ( & ) :

class Demo{ public static void main(String args[]) { int x=12; int y= 13; x=x&y; System.out.println(x); }}

43 Output : 12

Lets see what actually happens. See the truth table above, in case of AND (&) operation only 1 & 1 gives 1 else in all other cases results 0. In the above example x =12 will be stored in the memory as 00000000 00000000 00000000 00001100 y = 13 will be stored in the memory as 00000000 00000000 00000000 00001101 x =x&ywill be stored in the memory as 00000000 00000000 00000000 00001100 from above we can see that only in the 3rd bit and 4th bit of both 12 and 13 is 1 so by the & operation the value of 3rd and 4th bit will remain 1 else will remain 0. The result is the binary form of 12 & so is the output. Lets see what happens when the AND (&) operation is performed between a negative and a positive number class demo { public static void main(String ar[]) { int x = -12; int y = 13;

x= x & y;

System.out.println(x);

} } Output :

44 4 Here x is a negative number hence it will be stored in the memory in the form of twos complement. x =-12 will be stored in the memory as 11111111 11111111 11111111 11110100 y = 13will be stored in the memory as 00000000 00000000 00000000 00001101 x=x&y will be stored in the memory as 00000000 00000000 00000000 00000100 The sign bit of the resultant is 0, hence it is a positive number which is 4.

Bitwise OR(|)operator class Demo { public static void main(String[]args) { int x=12; int y=13; x=x|y; System.out.print(x); } } Output:13 The bit wise OR (|) operator checks individual bits of two different operand, if any bit of any of the operand is 1 then output is 1. X=12 its binary form is 00000000 00000000 00000000 00001100 Y=13 its binary form is 00000000 00000000 00000000 00001101 X=x|y out put is 00000000 00000000 00000000 00001101

The right most bit of 12 is 0 whwre as that of 13 is 1, hence the right most bit of result is 1 as shown above. The resultant is the binary form of 13 which is the desired output.

45 Lets have another example class Demo { public static void main(String[]args) { int x=-12; int y=13; x=x|y; System.out.print(x); } } Output: -3 Here x is a negative number hence it will be stored in the memory in the form of twos complement. X=-12 will be stored in the memory as 11111111 11111111 11111111 11110100 Y=13 will be stored in the memory as 00000000 00000000 00000000 00001101 X=x|y will be stored in the memory as 11111111 11111111 11111111 11111101 Clearly the resultant is a negative number since its sign bit is on. To get the final out put 1st determine the ones complement of 11111111 11111111 11111111 11111101which is (by converting 0 to 1 & 1 to 0) 10000000 00000000 00000000 00000010 here sign bit never change its polarity. Finally add 1 & the output is 10000000 00000000 00000000 00000011. So it is -3.

BITWISE XOR OPERATOR( ^ ): class demo1 { public static void main(String ar[]) {

46 int x = 12; int y = 13;

x= x ^ y;

System.out.println(x);

} } Output : 1 In XOR ( ^) operation when ever the value of a operand is equall to the value of the same bit of another operand then the the result will contain 0 in that bit else it will contain 0. In the above program x = 12 is stored in the memory as x = 13 is stored in the memory as x = x ^ y the output is 00000000 00000000 00000000 00001100 00000000 00000000 00000000 00001101 00000000 00000000 00000000 00000001

now we can see that all the bits in 12 and 13 contains same values except the right most bit which contains 0 incase of 12 and 1 incaze of 13. So the output will only have 1 in its rightmost place all other bits will have the value 0.

Lets see what happens when one of the operands I positive and the other is negative class demo1 { public static void main(String ar[]) {

47 int x = -12; int y = 13;

x= x ^ y;

System.out.println(x);

} } Output : -7 In the above example x = -12 is stored in the memory as y = 13 is stored in the memory as 11111111 11111111 11111111 11110100 00000000 00000000 00000000 00001101 11111111 11111111 11111111 11111001

x = x ^ y the output is

so we can see that -12 is stored in memory in its twos complement form and 13 in its usuall form. All the bits of the operands except the 2nd and the 3rd bit contain same value so the output will have all the values 1 except 2nd and 3rd bit ,which will contain 0. Because we have 1 in the highest bit so it is a negative number so to get the result we have to convert it into twos complement form which will be -7.

Below program shows how to swap two variables without using third variable through XOR ( ^ ) operator

class demo1 { public static void main(String ar[]) {

48 int x = 12 ; int y = 13 ;

System.out.println("value of x = "+x); System.out.println("value of y = "+y);

x=x^y; y=x^y; x=x^y;

System.out.println(" AFTER SWAPPING ");

System.out.println("value of x = "+x); System.out.println("value of y = "+y); } } Output :

value of x = 12 value of y = 13 AFTER SWAPPING value of x = 13 value of y = 12

Bitwise Shift Operator The bitwise Right Shift operator

49 The syntax for bitwise right shift opearator is given below. Variable >> no.of shifts

Here variable represents the variable on which we want to carry out the shift operation., and no.of shifts represents the number of bits the value of the variable should be shifted. e.g x >> 2 ;

Bitwise right shift operator shifts the bits of a number to a specified number of bits towars right preserving the signed bit. We can say that the empty bits are filled with the value of the highest order bit i.e for a positive number it is filled by 0 and for a negative number it is filled by 1.

class demo1 { public static void main(String ar[]) { int i = 5; i = i >> 2; System.out.println(i);

i = -5; i = i >> 2; System.out.println(i);

} }

50

Output : 1 -2

Lets see what happens in the above example. What actually happens in memory. i = 5 is stored in the memory as 00000000 00000000 00000101 i >> 2 value after the shift of two bits towards right 00000000 00000001 So after shifting we get the value of I as 1. But in case of negative numbers there is some difference. We all know that negative numbers are stored in memory in twos complement form and when we want to see the value it is again converted to twos complement and the original value is shown to us. Now lets see i = -5 is stored in the memory as 11111011 11111111 11111111 11111111 00000000

00000000 00000000

I >> 2 value after the shift of two bits towards right 11111111 11111110 so after shifting we get the value of i as -2.

11111111

11111111

*note : when we use the shift operators on byte and short variables then the values are shifted to int and the result after evaluation is also int so we should properly typecast it to get the correct result.

Bitwise Left Shift Operator ( << )

The syntax for bitwise left shift opearator is given below. Variable << no.of shifts

51 Here variable represents the variable on which we want to carry out the shift operation., and no.of shifts represents the number of bits the value of the variable should be shifted. e.g x << 2 ;

Bitwise left shift operator shifts the bits of a number to a specified number of bits towards left preserving the signed bit. We can say that the empty bits are filled with 0 .

class demo1 { public static void main(String ar[]) { int i = 5; i = i << 2; System.out.println(i);

i = -5; i = i << 2; System.out.println(i);

} }

Output : 20 -20

52

Lets see what happens in the above example. What actually happens in memory. i = 5 is stored in the memory as 00000000 00000101 i >> 2 value after the shift of two bits towards left 00000000 00010100 So after shifting we get the value of i as 20 . But in case of negative numbers there is some difference. We all know that negative numbers are stored in memory in twos complement form and when we want to see the value it is again converted to twos complement and the original value is shown to us. Now lets see i = -5 is stored in the memory as 11111011 i >>2 value after the shift of two bits towards left 11111111 11101100 so after shifting we get the value of i as -20 . 11111111 11111111 11111111 00000000 00000000

00000000

00000000

11111111

11111111

*note : when we use the shift operators on byte and short variables then the values are shifted to int and the result after evaluation is also int so we should properly typecast it to get the correct result.

Bitwise Unsigned Right Sift Operator ( >>> )

The syntax for bitwise right shift opearator is given below. Variable >>> no.of shifts

Here variable represents the variable on which we want to carry out the shift operation., and no.of shifts represents the number of bits the value of the variable should be shifted. e.g x >>> 2 ;

53 Bitwise unsigned right shift operator shifts the bits of a number to a specified number of bits towars right without preserving the signed bit. We can say that the empty bits are filled with 0 .

class demo1 { public static void main(String ar[]) { int i = 64; i = i >>> 4 ; System.out.println(i);

i = - 64; i = i >>> 4 ; System.out.println(i);

} }

Output : 4 268435452

Lets see what happens in the above example. What actually happens in memory. i =64 is stored in the memory as 01000000 00000000 00000000 00000000

54 i >>> 4 value after the shift of two bits towards right 00000000 00000100 So after shifting we get the value of i as 4 . here in case of negative numbers also the empty bits are filled with o. We all know that negative numbers are stored in memory in twos complement form and when we want to see the value it is again converted to twos complement and the original value is shown to us. Now lets see i = -64 is stored in the memory as 11111011 11111111 11111111 11111111 00000000 00000000

i>>> 4 value after the shift of two bits towards right 11111111 11111111 so after shifting we get the value of i as 268435452.

00001111 11111111

*note : when we use the shift operators on byte and short variables then the values are shifted to int and the result after evaluation is also int so we should properly typecast it to get the correct result.

Short circuit operators && ,|| These operators are used particularly in control statement & loops. The && operator

If(condition_1 && condition_2) { Codes } In && operator both condition_1 & condition_2 is checked, if both the parts are true then codes with in block followed by is executed. If condition_1 is checked as false then condition_2 is never evaluated. class Demo {

55 public static void main(String[]args) { int x=9; int y=0; if((++x)==10 && (++y)==1) {

} System.out.println(x); System.out.println(y);

} } Output:
10 1

In the above piece of code, see the if statement both sides are evaluated because of && operator. But if first statement is evaluated as false then control never goes to the second one. class Demo { public static void main(String[]args) { int x=9; int y=0; if(++x==1&& ++y==1) {

56 System.out.println(x); System.out.println(y);

} } Output:
10 0

See the output first condition is evaluated as false there fore control does not go to the second condition.

The || operator If(condition_1 || condition_2) { Codes } In this case first condition_1 is evaluated & control goes to the second condition only if condition_1 is false. class Demo { public static void main(String[]args) { int x=9; int y=0; if(++x==10||++y==1) {

57 } System.out.println(x); System.out.println(y);

} } Output: 10 0 See the output. It clearly shows that since 1st condition is evaluated as true control does not go to the second condition. class Demo { public static void main(String[]args) { int x=9; int y=0; if(++x==1||++y==1) {

} System.out.println(x); System.out.println(y);

} } Output:

58 10 1 Here 1st condition is evaluated as false, there control goes to the second condition.

Ternary if-then-else operator ( ?: )

We can say that we can execute a if else statement using ternary if-then-else operator ( ?: ). Syntax is given below Evaluation_Part ? codes_of_section_1 :codes_section_2 First Evaluation_Part is evaluated if it is true then codes_of_section_1 is excuted else codes_section_2 is executed. e.g. class demo1 { public static void main(String ar[]) { int i = 64; int k=0;

k =(i>k)? 10 : 5; System.out.println(k);

k= (i<k)? 10: 5; System.out.println(k);

59 } }

Output : 10 5

From the above example you can check that the Ternary if-then-else operator ( ?: ) works like if else.

OPERATOR PRECEDENCE TABLE

Highest

() []

! ~ - + ++ --

*/%

+-

<< >> >>>

< <= > >=

60

== != === !==

&

&&

||

?:

= += -= *= /= %= <<= >>= >>>= &= ^= |=

Lowest

If there are more than one operators in an expression then they are evaluated according to their precedence.

61

CHAPTER 5:

CONDITIONAL STATEMENTS AND LOOPS


Decision making and branching: When a program makes a sequential control code and joins another part of code. Then it is called branching.   Conditional branching: It based on particular condition. Unconditional branching: This takes place decision. without any

Control statement: 1. If statement. 2. Switch case statement. 3. Conditional operator. If statement: It's a two-way decision making statement, which use in construction with an expression. a. b. c. d. Simple if. if ... Else. Nested if. else.... if ladder.

 if statement - of Java will take only the logical value true or false, Java not allow the integer value as condition, (0 as false and any non-zero value as true like C and C++).  If statement of java will allow only the statement which return true or false, rather than the statement which return any integral value.

62

Simple if: if (expression) { statement(s); } statement (x);

if Test ? true Statement of body of if false

Exit

if ...else: Syntax: If (test Expression) { statement(s); } else{ statement(s); }

63

if
Test

False

Block of if

Block of else

True
Exit

Nested if ... else: Syntax: if (test expression) { if(test expression) { statement(s); } else { statement(s); } } else statement(s);

64

If True Test

If False Test Block 3 Expression

True

False

Block 1

Block 2

Statement x

Exit

else ... if ... ladder Syntax:

65

if (test expression) { statement(s); } else if (test expression) { statement(s); } else statement(s); statement(x); //THIS IS A else-if ladder statement for setting-up a multi-way condition checking

If true
Test Expressi on

false

If false true
Test Expressi on

If
B1 B2

false true
Test Expressi on

B3

B4

Exit

66

switch ... case statement:   Java has a build in multi-way design statement called a switch. The switch statement test the value of given variable or expression against the list of case value when a match is found a block of statement associated with that case is executed. The expression inside the switch case may be an integer or character. Value 1, 2, 3, 4, n are constant or constant expression. Each of these values should be unique in a switch block otherwise, it will hang the computer. Each case must end with a colon.

 

If there is no match with any case specified in the switch case than the default statement is executed. Each case must be terminated with a break statement.

 Syntax:

switch (expression/variable) { case Val 1: statement(s); break; case Val 2: statement(s); break; case Val 3: statement(s); break; default: statement(s) break; } Another of the decision making constructs is the switch-case construct which is ideally suited for making multiple choice application, like, for example, user menus. Typically, in situations where we have one value or expression

67

that has to be exactly matched with a list of pre-defined values or options the switch case is the construct of choice. The switch statement is a multiway decision making construct based upon the evaluated expression. It gives you a faster way to make a decision from a multiple number choice, the break statement is require after each case because if the switch expression contain default then this statement will execute by default and as well the after finding the require condition it will go for checking other cases which is a drawback, so it is better to use break after each case.
Switch(exp)

Case Y
Val 1

Break

B-1

N Break Case
Val 2

Y B-2

N Break Case
Val n

Y B-n

Default

Statement x

Exit

68

Conditional operator: Syntax: Exp1? Exp 2:Exp 3; e.g. : ((X!= A)?((X>A)?(4X+100):(X+30)):(3X+50)); A program to show compute the net amount paid by the costumer if he purchased Rs. X from mill clothes and Rs. Y from handloom clothes

Looping:       Entry controlled. Exit controlled. While loop. Do loop. For loop. Jump statement. y Break. y Continue.

Looping:
The process of repeatedly executing a block of statement is called as looping; the statement in the block may be executed any no. Of time from 0 n times.

If loop continues forever then it is called as infinite loop. In looping a sequence of statement executed until some condition for termination of the loop is satisfied. A program will consist of two parts.   Control statement. Body of the loop.

69

The control statement tests certain condition and then directs repeated execution of statement. Contain in the body of the loop. Depending upon the position of the condition or the control statement it may be of two types.  Entry control: Here control condition is test before the start of the loop execution. It will not execute the block of statement for once also if the specified condition is false. e.g., while (test expression)....  Exit control: Here test is performing at the end of the body of the loop and before that, the body is executed unconditionally for the first time. It must run the body of the loop at least once whether the condition is true or false this will not hamper the first execution of the block. E.g. do...while (test expression).

For loop is the easiest to understand of the loop in Java. The for loop is execute the block of loop for the fixed no. Of time. It's generally used when you know, before entering the loop, how many time the loop will execute the code. Here is an example to show the use of for loop in Java. This is the sample program to show the use of for loop and as well as find out the whether a no is odd or even from a given set of no.

Entry if True Test Expr


n

False

Block - 1

Exit

Increment/ Decrement

70

Entry Control Loop These are the control statement or control condition tested before the body start of loop execution. The example of this type of loop is: e.g. While (condition) { statement(S); } This loop is run only when the condition is true other wise the will not be executed. This loop is never execute the statement if the condition is false.

Entry

Block - 1

If True Test n expr

False

Exit

71

Exit control loop These are the control statement or control condition is placed at the end of the body of the loop and before that the body is executed un-conditionally at least for one time, which is not possible in the case of Entry control loop. do { statement(s); } while (condition);

Step in looping process: 1. 2. 3. 4. Setting and initialization of a counter. Execution of statement in the loop. Test for a specified condition for execution of loop. Incrementing or decrementing the counter.

while loop (Entry control loop)

Initialization

If N Test exprn Exit

Y Statement(s)

72

while loop: initialization; while (test condition) { Loop body; }    e.g.: sum = 0; add = 1; while(n<=10) { sum=sum+n; n=n+1; } System.out.println(sum); Do while statement (Exit control loop) Here when the test condition is fails control is transfer out of the loop otherwise loop will be continue or repeated. Here the body of the loop may be executed at all if the condition doesn't satisfy for 1st time. Here also the expression (Test condition) should return only the true and false rather than any integer value as we have in C and C++.

Initialization

do

Body of loop

While Y Test Condition

Exit
N

73

do while loop: initialization do { Body of the loop } while (test condition);    Free from language free from any indentation. Since the test, condition is provided at bottom of the loop it always executed at least one. This loop will executed till the condition is true.

The program to show the use of do while loop. Example-1 /* find out the sum of the first ten natural no. */ class Test1 { public static void main (String args[]) { int s=0,n=1; do{ s=s+n; n++; } while (n<=10); System.out.println ("Summation of the fist ten natural no. : "+s); } } For loop (Entry control loop) Format: for (initialization; test condition; increment or decrement) { Loop body; }

74

Body of loop of this loop may not be executed at all if the specified condition fails at the start.

Example-2 /* Find out the sum of the first ten natural no. */ class Test2 { public static void main(String args[]) { int s=0; for (int n=1;n<=10;n++) { s=s+n; } System.out.println("Summation of the fist ten natural no. : "+s); } }

Additional feature of For loop:       More than one variable can initialize at a time in for loop statement. The increment section also must have more than one part. Test condition may have any compound relation and testing may not be limited only two loop control variable. We can use expression in the assignment statement of initialization of increment section. Both initialization and increment in the for statement. We can setup time delay using null statement using for loop.

Nesting of for loop:

for(initialization; condition; increment or decrement){ for(initialization; condition; increment or decrement){ statement(s);} statement(s);}

75

Example-3 public class Nest1 { public static void main(String args[]) { int i=0,j=9; do{ i++; if(j--<i++) { break; } } while (i<5); System.out.println(i+"\t"+j); } } Output:-

Example-4 public class Nest2 { public static void main(String args[]) { int j=0; do for(int i=0;i++<2;) System.out.println(i); while(j++<2) } }

76

Output:-

Jumping statement in loop: Break and continue:    e.g. Java permits to jump from one statement to the end or beginning as well as jump out of a loop. An early exit from a loop can be accomplished using a break statement. In case of nesting loop break will exit only a single loop.

1. while(condition) { statement(s); if (condition) break; statement(s); }

2.for(int i=0;i<10;i++) { statement(s); if(condition) break; statement(s); }

77

3.do { statement(s); if(condition) break; statement(s) }while(condition);  Continue causes the loop to be continue of to the next iteration of the skipping statements. In while and do loops continue causes the control to go directly to test the condition and then continue the iteration process. In for increment section of for is executed before the test condition is evaluated.

Label loops:   In java we can give, a label is a valid variable name followed by colon. If we want to jump outside nested loop or continue at an outer loop we can use label break or label continue statement.

Example-5 public class Loop { static String o=""; public static void main(String args[]) { z: for(int x=2;x<7;x++) { if(x==3)continue; if(x==5)break z; o=o+x; } System.out.println(o); }

78

} Output:-

Brain Drill

Assignment-1 Enter a number and check it is an Armstrong number or not?

import java.io.*; public class Armstrong { public static void main(String args[])throws Exception { int n,t=0,s=0,r=0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter A Number"); n=Integer.parseInt(br.readLine()); t=n; while(n>0) { r=n%10; s=s+(r*r*r); n=n/10;

79 } if(t==s) System.out.println("Armstrong Number is "+t); else System.out.println("Not an Armstrong Number "+t);

} }

Output:-

Assignment-2 Enter a number from keyboard and check it is Prime number or not?

import java.io.*; public class PrimeCheck

80 { public static void main(String args[])throws Exception { int a=0,b=1,c=0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter A Number"); a=Integer.parseInt(br.readLine()); while(b<=a) { if(a%b==0) { c=c+1; } b++; }

if(c==2) { System.out.println("Prime Number Is "+a); }else{ System.out.println("Not A Prime Numer "+a); } }

81 }

Output:-

Assignment-3

Enter a number and count how many prime number are present within it?

import java.io.*; public class PrimeCount { public static void main(String args[])throws Exception { int a=1,r; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a Number");

82 r=Integer.parseInt(br.readLine()); while(a<=r) { int b=1,c=0; while(b<=a) { if(a%b==0) c=c+1; b++; } if(c==2) System.out.println("Prime Number is "+a);

a++; } } }

Output:-

83

Assignment-4

Enter A Character and find out the ASCII value of that number?

import java.io.*; public class Ascii { public static void main(String args[])throws Exception { System.out.println("Enter A Character and findout the Ascii value"); byte b=(byte)System.in.read(); System.out.print(b);

84 } }

Output:-

Assignment-5

Enter A Number and check it is a Binary Number or not?

import java.io.*; public class BinaryCheck { public static void main(String args[])throws Exception { int r,c,n,t; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Binary Number"); n=Integer.parseInt(br.readLine()); t=n; c=r=0;

85 while(n>0) { if(n%10==0 || n%10==1) c++; r++; n=n/10; } if(c==r) { System.out.println("It is a Binary Number"); }else{ System.out.println ("It Is not a binary number"); } } }

Output:-

86

Assignment-6
Enter A Number and Find Out The Factorial? import java.io.*; public class Factorial { public static void main(String args[])throws Exception { int n,f,i; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter any Numer"); n=Integer.parseInt(br.readLine()); i=n; f=1; while(i>0) { f=f*i; i--; } System.out.println ("Factorial of "+n +" Is "+f) ; } }

Output:-

87

Assignment-7

Enter A Number and add each digit of that number? import java.io.*; public class SumDigit { public static void main(String args[])throws Exception { int r=0,s=0,n; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Any Number"); n=Integer.parseInt(br.readLine()); while(n>0) { r=n%10; s=s+r; n=n/10; } System.out.println("Sum Of Digit Is "+s); }

88 } Output:-

Assignment-8

See the Pyramid and Draw It?

import java.io.*; public class Pyramid1 { public static void main(String args[])throws Exception { int i,j,row;

89 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter The Number Of Rows"); row=Integer.parseInt(br.readLine()); for(i=1;i<=row;i++) { for(j=1;j<=i;j++) { System.out.print("* "); } System.out.print("\n") } } } ;

Assignment-9
See The Pyramid and Draw It?

90 import java.io.*; public class Pyramid1 {

public static void main(String args[])throws Exception { int row=0,t=0,i=0,j=0,k=0,s=0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter The Number Of Rows"); row=Integer.parseInt(br.readLine()); t=1; for(i=1;i<=row;i++) { for(j=0;j<(row-i);j++) System.out.print(" s=(2*i)-1; for(k=0;k<s;k++) { if(t<10) System.out.print(" else System.out.print(" t++; } System.out.print("\n\n") ; "+t); "+t); ");

91 } } }

Assignment-10
Draw A Number Triangle?

import java.io.*; public class NumberTriangle { public static void main(String args[])throws Exception { int i,j,t=1,row; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter number of rows"); row=Integer.parseInt(br.readLine());

92 for(i=0;i<row;i++) {

for(j=0;j<=i;j++) { if(t<10) { System.out.print(" "+t); }else{ System.out.print(" "+t); t++; } } System.out.print("\n"); } } }

93

Assignment-11
Draw A Pascal Triangle?

import java.io.*; public class Pascal { public static void main(String args[])throws Exception { int b,p,q,r,x; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); r=Integer.parseInt(br.readLine()); b=1; q=0; System.out.println("Pascal's Triangle"); while(q<r) { for(p=30-3*q;p>0;p--) System.out.print(" "); for(x=0;x<=q;x++)

94 { if(x==0 || q==0) b=1; else b=(b*(q-x+1)/x); System.out.print(" } System.out.print("\n") ; q++; } } } "+b);

95

CHAPTER 6 :

CLASS FUNDAMENTALS
I must say this is the most important chapter, the foundation on which the entire java programming language is developed. Its my sincere advice to the reader to be careful & focused. Class can be defined as a template or an abstract model. It contains variables and methods which are required to modify the values of the variables belonging to the particular class. An object is known as the instance of a class. Class templates takes no memory, when object is created memory is allocated. Local variable

Example-1
class p { public static void main (String args [ ]) { int x; System.out.println(x); } } Above program generates compilation error . The error is given below

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable x may not have been initialized at .p.main(p.java:5)

Above program will result a compilation error. x is a local variable. In java each local variable has to be initialized before they are used other wise it will give compilation error. Local variable scope is the method (including constructor) where it is declared. It is invisible to outside the method. Therefore it cannot be accessed from out side the method. In

96

C/C++ an uninitialized local variable takes garbage value. But, there is no such thing called garbage value in java.

Example-2
class p { public static void main(String args[ ]) { int x=3; {-/ int x=7; System.out.println(x); } System.out.println(x); } } Above program generates compilation error. The error is given below

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Duplicate local variable x at p.main(prj1.java:5) Output: compilation error. In C/C++ block scope is there inside the function but java doesnt define block scope inside method, be careful with this. So inside a method we cannot have more than one variable having same name.

97

Creation of object Object is created by calling the constructor of the corresponding class through new operator. Example-3 class p { public static void main(String a[ ]) { p x=new p(); /*x is known as reference variable of class p. Through new operator constructor is called to create the object of class p.*/ } } If an object having no reference is created then it is called orphan object. Example-4 class p { public static void main(String a[ ]) { new p(); //orphan object is created } }

98

Constructor is used to create the object of the corresponding class. Therefore constructor name must be same as that of the class name. Its a rule OOP. y Constructor does not have any return type. y Constructor cannot use any access modifier. y Constructor is of two types  Parameterize constructor  Non-parameterize or default constructor y Constructor cannot be over ridden but cannot be over loaded. y Note: If there is no constructor defined by the programmer then JVM automatically recognize the default constructor but, if the programmer define the parameterize constructor & call the default constructor then compile time error occurs. Check it out: Example-5 class p { p(int i) { System.out.println(Hello, World!!); } public static void main(String a[ ]) { p x=new p(); } } Above program generates compilation error. The error is given below

99

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor prj1() is undefined at p.main(prj1.java:8) So the solution is either the programmer has to define a default constructor or only can call the parameterized constructor that has been defined by the programmer. static modifier y y y y y y y static is a key word or modifier in java. static variables are declared outside the method & constructor. If the static variable is not initialized then it takes the default value of the data type. There is only one copy of the static variable exist for a particular class. It is directly accessed within a non static method & constructor. static variables can be accessed through class name, object name & directly with in a static method. If a method is static then the programmer can call the method without creating the object of the corresponding class.

Example-6 class p { public static void main(String args[ ]) { fun(); //fun is a static method & main is static therefore main can call fun directly. p.fun(); //fun can be called through class name since fun is static p x=new p();

100

x.fun(); //fun can also be called through object name. } static void fun() { System.out.println("Hello!"); } } Output will be Hello! Hello! Hello!

Example 7: class p{ public static void main(String f[ ]) { p x=new p(); x.fun1(); } static void fun() { System.out.println("Hello!"); }

101

void fun1() { System.out.println("Hie"); fun(); // fun is called directly from a non-static method p.fun(); //fun is called from non static method through class name. p x=new p(); x.fun(); //fun is called from a non static method through object name. } } Output will be Hie Hello! Hello! Hello! Instance variable y y y y y y y It is declared outside the method & constructor. If the instance variable is not initialized then it takes default value of the data type. Same named instance variable cannot be in a single class. It is accessed by its name inside non static method. It is accessed by the object name inside a static method. Instance variables are known as class member variable. Size of an object is equal to the size of instance variables present in the corresponding class.

102

Methods Class consist instance variables and the methods to manipulate those instance variables. Now we are going to discuss the fundamentals about methods. The syntax of declaring a method is return_type method_name ( parameters ); Here return_type indicates the type of data returned by the method. The return type of a method can be of any valid data type, including the user defined classes. If the method does not returns any value its return type must be void. return keyword is used to return a value from a method. e.g. return value ; Here value represents the value that is returned from method. method_name represents the name of the method. It can be any legal identifier. parameters are the variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Adding a simple method to class Now we will see how to a simple method to a class. Example-8 // This program uses a method. class Rectangle { double width; double height;

103

// compute and return volume double area() { return width * height ; } } class RectangleDemo { public static void main(String args[]) { Rectangle rec1 = new Rectangle(); double area; // initialize each rectangle rec1.width =10 ; rec1.height = 20; // get area of first rectangle area = rec1.area(); System.out.println("Area is " + area); } } Output : Area is 200.0 In the above example we used a method called area to calculate the area of a Rectangle object.

104

Adding a Parameterized Method to a Class In addition to defining methods that provide access to data, you can also define methods that are used internally by the class itself. Example-9 // This program uses a parameterized method. class Rectangle { double width; double height; // compute and return volume

double area() { return width * height ; } // sets dimensions of the rectangle void setValue(double w, double h) { width = w; height = h; } } class RectangleDemo { public static void main(String args[])

105

{ Rectangle rec1 = new Rectangle(); Rectangle rec2 = new Rectangle(); double area; // initialize each rectangle rec1.setValue(10, 20); rec2.setValue(3, 6); // get area of first rectangle area = rec1.area(); System.out.println("Area is " + area); // get area of second rectangle area = rec2.area(); System.out.println("Area is " + area); } } Output : Area is 200.0 Area is 18.0 As you can see, the setValue( ) method is used to set the dimensions of each rectangle. For example, when rec1.setValue (10, 20); is called, 10 is copied into parameter w and 20 is copied into h. Inside setValue( ) the values of w and h are then assigned to width and height respectively. The area() method is used to calculate the area of each rectangle and then the calculated value is returned.

106

Constructor A constructor is used to create the object when it is invoked through new operator. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately when the object is created, before the new operator completes. Constructors do not have any return type. It is quite obvious not to have return type of constructors. Lets rework the Rectangle example so that the dimensions of a rectangle are automatically initialized when an object is constructed. To do so, replace setValue( ) with a constructor. Lets begin by defining a simple constructor that simply sets the dimensions of each rectangle to the same values. This version is shown here: Example-10: class Rectangle { double width ; double height ; //This is the constructor for Rectangle. Rectangle() { System.out.println("Constructing Rectangle"); width = 10; height = 10; } // compute and return area double area() { return width * height ; } } class RectangleDemo { public static void main(String args[]) {

107

// declare, allocate, and initialize Rectangle objects Rectangle rec1 = new Rectangle(); Rectangle rec2 = new Rectangle(); double arae; // get area of first rectangle arae = rec1.area(); System.out.println("area is " +arae); // get area of second rectangle arae = rec2.area(); System.out.println("area is " + arae); } } Output : Constructing Rectangle Constructing Rectangle area is 100.0 area is 100.0

As you can see, both rec1 and rec2 were initialized by the Rectangle( ) constructor when they were created. Since the constructor gives all rectangles the same dimensions , 10 by 10 , both rec1 and rec2 will have the same area. Rectangle rec1 = new Rectangle(); new Rectangle( ) is calling the Rectangle( ) constructor. When you do not explicitly define a constructor for a class, then Java creates a default constructor for the class. This is why the preceding line of code worked in earlier examples of Rectangle class where we have not defined a constructor. The default constructor automatically initializes all instance variables to zero. Parameterized Constructors

108

To set different values for different object of Rectangle class we can use parameterized constructor .The following example defines a parameterized constructor which sets the dimensions of a rectangle as specified by those parameters. Example-11 class Rectangle { double width; double height; // This is the constructor for Rectangle. Rectangle(double w, double h) { width = w; height = h;}

// compute and return area double area() { return width * height ; } } public class RectangleDemo { public static void main(String args[]) { // declare, allocate, and initialize Rectangle objects Rectangle rec1 = new Rectangle(10, 20); Rectangle rec2 = new Rectangle(3, 6); double arae; // get area of first rectangle arae = rec1.area(); System.out.println("area is " +arae); // get area of second rectangle arae = rec2.area(); System.out.println("area is " +arae); } } Output : area is 200.0 area is 18.0

109

See, each object is initialized as specified in the parameters to its constructor. For example, in the following line, Rectangle rec1 = new Rectangle(10, 20); the values 10 and 20 are passed to the Rectangle( ) constructor when new creates the object. Now width and height of rec1 will contain the values 10 and 20 respectively. Note : if we define a parameterized constructor for a class we have to also define the constructor taking no arguments otherwise we can only make call to the parameterized constructor, making call to the default constructor will show an error. For example Example-12 class Rectangle { double width; double height; // This is the constructor for Rectangle. Rectangle(double w, double h) { width = w; height = h; } // compute and return area double area() { return width * height ; } } public class RectangleDemo { public static void main(String args[]) { // declare, allocate, and initialize Rectangle objects Rectangle rec1 = new Rectangle(10, 20); Rectangle rec2 = new Rectangle(); // this line will result an error

//

//

double area; get area of first rectangle area = rec1.area(); System.out.println("area is " + area); get area of second rectangle area = rec2.area(); System.out.println("Volume is " + area); } }

110

Output : Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor Rectangle() is undefined at RectangleDemo.main(RectangleDemo.java:18)

The above program will result in an compilation error. Because in the line Rectangle rec2 = new Rectangle(); // this line will result an error we make call to the default constructor , but we have not defined the default constructor. So it is the duty of the programmer to define the default constructor whenever he is defining a parameterized constructor, if he is going to use the default constructor. Overloading Methods When we define two or more methods within the same class that have the same name, but take different types of arguments, then the methods are overloaded. Method overloading is a powerful feature of Java. In OOP terminology method over loading is termed as static binding or static polymorphism. I hope reader can sense that when a method is invoked, only the method name is not sufficient to uniquely determine a method, along with the method name the type of argument method is taking is also necessary. When an overloaded method is invoked, JVM invokes the method according to the type and/or number of arguments the method is taking. In case of method overloading method name must be same where as differ in the type and/or number of their parameters. In case of method overloading methods may have same or different return types. Example-13 // method overloading. class Overload { void show() { System.out.println("No parameters"); }

111

// Overload show for one integer parameter. void show(int a) { System.out.println("a: " + a); } // Overload show for two integer parameters. void show(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload show for a double parameter double show(double a) { System.out.println("double a: " + a); return a*a; } } class Demo{ public static void main(String args[]) { Overload ob = new Overload(); double result; // call all versions of test() ob.show(); ob.show(10); ob.show(10, 20); result = ob.show(20.25); System.out.println("Result of ob.show(20.25): " + result); } } Output: a: 10 a and b: 10 20 double a: 20.25 Result of ob.show(20.25): 410.0625 As we can see, show( ) is overloaded four times. The first method takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth takes one double parameter. Overloading Constructors We can also overload constructors. Example-14

112

Let see the example below /* Here, Rectangle defines three constructors to initialize the dimensions of a rectangle in various ways. */ class Rectangle { double width; double height; // constructor with two arguments Rectangle(double w, double h) { width = w; height = h; } // constructor with no arguments Rectangle() { width = 25; height = 25; } // constructor with one argument Rectangle(double var) { width = height = var; } // compute and return volume double area() { return width * height ; } } public class Demo { public static void main(String args[]) { // create rectangles using the three constructors Rectangle rec1 = new Rectangle(10.0, 20.0); Rectangle rec2 = new Rectangle(); Rectangle rec3 = new Rectangle(15.0); double arae; // get area of rec1 arae = rec1.area(); System.out.println("area of rec1 is " + arae); // get area of rec2 arae = rec2.area(); System.out.println("area of rec2 is " + arae); // get area of rec3 arae = rec3.area(); System.out.println("area of rec3 is " + arae);

113

} } Output : area of rec1 is 200.0 area of rec2 is 625.0 area of rec3 is 225.0 Here the required constructors are called according to the type and/or number of arguments. finalize( ) Usually during the training of new comers in java a question always asked by loyal C++ programmer is what the corresponding tool of C++ destructor in java. The answer is finalize() method. finalize() method is called just before the object is garbage collected. Before an object is garbage collected garbage collector implicitly calls finalize() method of object class. The syntax of finalize( ) method is : public void finalize( ) { // finalization code here } this Keyword To allow a method to refer to the object that invoked it , Java defines the this keyword. this can be used inside any method to refer to the current object. this is always a reference to the object on which the method was invoked. Example-15 To get a clear view what this refers to, consider the following example

/* Here, Rectangle defines three constructors to initialize

114

the dimensions of a rectangle in various ways. */ class Rectangle { double width; double height; // constructor with two arguments Rectangle(double w, double h) { this.width = w; this.height = h; } // constructor with no arguments Rectangle() { this.width = 25; this.height = 25; } // constructor with one argument Rectangle(double var) { this.width = this.height = var; } // compute and return volume double area() { return this.width * this.height ; } }

115

public class RectangleDemo { public static void main(String args[]) { // create rectangles using the three constructors Rectangle rec1 = new Rectangle(10.0, 20.0); Rectangle rec2 = new Rectangle(); Rectangle rec3 = new Rectangle(15.0); double arae; // get area of rec1 arae = rec1.area(); System.out.println("area of rec1 is " + arae); // get area of rec2 arae = rec2.area(); System.out.println("area of rec2 is " + arae); // get area of rec3 arae = rec3.area(); System.out.println("area of rec3 is " + arae); } } Output : area of rec1 is 200.0 area of rec2 is 625.0 area of rec3 is 225.0 This example operates exactly like the previous example.here instead of using only the variable name inside the methods and constructors we have used this.variable name to assign values

116

to the variables of the invoking objectof Rectangle class . Inside Rectangle( ), this will always refer to the invoking object. this is useful in various contexts.

Static and Non Static block in java Block starts with a { and ends with }. Syntax is { //Java codes; } In java there are two types of blocks one is Static block and the other one is the non static block. Static block Whenever a block is declared with the static keyword, then it is known as static block. Its syntax is static { //Java codes; } The nature of static block is that the codes inside it gets executed before the main method is execute i.e. when you run the class file first the codes within the static block is executed and after that the main method starts execution. Lets have an example to know how it exactly behaves Example-16 class Demo { static { System.out.println("Samita is in Static block"); }

117

public static void main ( String ag[]) { System.out.println("Samita is in main method"); } } Output : Samita is in Static block Samita is in main method From the above example we can see that first the code inside the static block is executed and afer that the code inside the main method is executed. By the use of static block we can execute any code before main is called. Example is given below Example-16 class Demo { static { System.out.println("Lory is inside static block"); int a=5; int b=6; int x= a+b; System.out.println("Value of x= "+x); } public static void main(String ag[]) {

118

} } Output : Lory is inside static block Value of x= 11

In the above example you can see that we have printed a statement, calculated the value x and displayed it without writing it inside main method. Example-17 public class Demo { static { System.out.println("Lory is in the first Static block"); } public static void main ( String ag[]) { System.out.println("Lala is in the main method"); } static{ System.out.println("Samita is in the second static block"); } } Output : Lory is in the first Static block Samita is in the second static block

119

Lala is in the main method

In the above program there are two static blocks so they will be executed sequentially one after another before main method is executed , it doesnot matter whether we put the static block above or below main method . An interesting fact can we execute a java program without main method? Answer is yes!! Foxed folks Example-18 Test.java Class Demo{ static { System.out.println(hello world); System.exit(0); } } Compile it javac Test.java Run it by java Demo Out put is hello world Actually when we call System.exit(0) in side static block, it forces the termination of the program. Note : Static block cannot be declared inside any method. Static block is executed only once. Non Static block A block without static key word is known as Non Static block. The statements inside the Non Static block gets executed whenever a object of that class is created.

120

Example-19 Lets see a example. public class Demo { { System.out.println("Lory is in the first Non Static block"); }

Demo() { System.out.println("Asim is inside the constructor"); } public static void main ( String ag[]) { System.out.println("Lala is in the main method"); Demo a= new Demo(); Demo a1= new Demo();

{ System.out.println("Samita is in the second Non static block"); } }

121

Output : Lala is in the main method Lory is in the first Non Static block Samita is in the second Non static block Asim is inside the constructor Lory is in the first Non Static block Samita is in the second Non static block Asim is inside the constructor In the above example we can see that whenever a object of the class containing the non Static blocks is created the non Static blocks are executed first sequentially before the codes inside the constructors of the class is executed. And also we can see that every time when a object of that class is created the Non static blocks are again executed.

122

Chapter-7

Object Reference Does JAVA have memory pointer?? Billion Dollar Question!! My experience with JAVA says JAVA has memory pointer but not as prominent as in case of C/C++. Reference variables behave like pointers. In computer terminology reference variable means such a variable which can hold the address.

p.java class p { int x; public static void main(String args[ ]) { p z=new p( ); z.x=3; System.out.println(z.x); } }

This is a simple java program. Here p is a class having an instance variable x. To create an object of class p we have to call the default constructor of class p through new operator. The job of new operator is to allocate memory dynamically during runtime. z is known as reference variable of class p. As I have said reference variable holds the address of a memory location. In java memory management is completely done by JVM. After compiling above java code p.class file is created. During

123

the execution of p.class file first it is loaded in the memory by the boot strap class loader which is a component of JVM. z is a reference variable which is created inside stack area. When the constructor of class p is called through new operator memory chunk is allocated from heap area and its starting address is stored in z & we say that object of class p is created. Then, how much memory will be allocated? The amount of memory that is to be allocated depends up on the sum of size of instance variables belonging to that class. If the class contains a reference variable as an instance variable then 4 byte memory will be allocated for that. Static variables & methods are not the part of an object, so they are stored in different part of memory known as method area. In its entire life z will hold the starting address of the memory chunk that has been allocated to it from heap area unless until a new memory chunk is allocated to it by calling the constructor through new operator. When z will die the memory chunk allocated to it is freed by garbage collector.

Diagram1:

124

STACK

HEAP

566656

566656 int x

z is the reference variable created inside STACK When the constructor of class p is called through new operator memory chunk is allocated from heap area and its starting address (566656)is stored in z.

The swapping problem If you have understood the concept of reference then this problem is going to test your depth. Example-1 p.java class p { int x;

125

public static void main(String args[ ]) { p a=new p(); a.x=1; p b=new p(); b.x=2; valueSwap(a,b); System.out.println(a.x); System.out.println(b.x); } static void valueSwap(p k,p l) { int i=k.x; k.x=l.x; l.x=i; } }

Out put is 2 1

126

Example-2 class q { int x; public static void main(String args[ ]) { q a=new q(); a.x=1; q b=new q(); b.x=2; valueSwap(a,b); System.out.println(a.x); System.out.println(b.x); } static void valueSwap(q k,q l) { q temp; temp=k; k=l; l=temp; } } Out put is

127

1 2

Output of p.java & q.java is different. Why? Consider p.java program. a & b are reference variables created inside stack area. When we call the constructor through new operator, memory is allocated from heap. Assume that 1000 is the starting address of the memory chunk allocated to a & 5000 is starting address of the memory chunk allocated to b as shown in the figure.

STACK

HEAP

1000

1000 x=1

5000

5000

x=2

128

valueSwap() method takes a & b as its argument. In valueSwap() method content of a is copied to k & content of b is copied to l. Now k=1000

& l=5000. k & l are the local reference variables of valueSwap() method created inside stack. In side the function valueSwap() the code int i=k.x; implies is value is 1. Code k.x=l.x; means the content of x present in the memory chunk whose starting address 1000 is changed to 2.Similarly the code l.x=i; means content of x present in the memory chunk whose starting address is 5000 is changed to 1. Now the feature is described below. X=2 K 1000 1000

L 5000 5000 X=1

HEAP STACK When control goes out of the method valueSwap() although the reference variables k & l become dead but the changes they have made in heap area is permanent. When control goes back to main() method the changes reflected there as shown in the figure

129

STACK

HEAP

1000

1000 x=2

5000

5000

x=1

Now consider the 2nd program q.java. up to the function call valueSwap(), everything is similar to that of p.java. Here inside the method valueSwap() of the program q.java things are different. temp is an reference of class q. temp=k; means now temp=1000;, k=l; means k=5000 & l=temp; means l=1000. When control goes out of the method valueSwap(), k&l become dead because they are local reference variables created inside stack. Hence changes are not reflected.

130

One has to understand the concept that local variables always die when control goes out of a method. But, if the local variables are of

reference type then the changes they have made in the memory locations they are pointing are permanent. Hash code When an object is created through new operator by calling the constructor of the corresponding class a unique identifier is assigned to the reference variable, known as hash code. Hash code is allotted by JVM. How to determine the hash code?

Example-3 class p { public static void main(String args[ ]) { p x=new p(); System.out.println(x.hashCode()); } }

The method hashCode() returns the hash code of the corresponding reference when object is created. Hash code is assigned only to reference variables when memory is allocated from heap area. Local variables of primitive data types are created inside stack area & memory is allocated from there also. All the above complexities are not involved here. Local variables of primitive data types do

131

not have any hash code because they do not acquire memory from heap area. To get hash code the variable must be of reference type. Example-4 class p { public static void main(String f[ ]) { int mak=5; System.out.println(mak.hashCode()); } } Above program will result a compilation error because mak is not a reference variable & memory is not allocated to it from heap. The error is int can not be dereferenced. The next question that arises is it possible to allocate memory to variables of primitive data type from heap & the answer is yes. I will explain it in array.  A note from author: Ok, our voyage of OBJECT & REFERENCE is completed. But, there is a mystery still to be unrevealed. Mystery is about static variables. Static variables are created inside method area. Objects are inside heap. References are inside stack. Static variables can be accessed by reference variables, but only after the object is created by invoking the constructor of the class through new operator, other wise compilation error will arise. When an object is created inside heap, along with the instance variables it also contains a
 pointer to the memory location of method area which contains

the static variables of corresponding class. All the objects of a particular class contains pointer which holds the address of same particular memory location inside method area containing the static data member of that class.

132

Chapter-8 Array Array is a linear homogeneous data structure. It is simply a collection of similar type elements. An element present in the array is accessed through its index. You can define an array either as int[ ] arr; Or as int arr[ ]. But the former one is preferred by most java programmer. A specific element of an array is accessed by the index. The syntax of one dimensional array declaration is Data_Type variable_name [ ] =new Data_Type[size]; Or Data_Type [ ] variable_name=new Data_Type[size]; Here Data_Type specifies the type of array that is created, size specifies number of elements in the array, and variable_name is the array variable or in particular a reference variable of the corresponding data type. But, things are quite different in case of an array of objects.. The 1st element of the array is accessed by placing 0 in the [ ]. 0th index represents the 1st element of the array. Example-1 public class Demo { public static void main(String[] args) { int[] arr=new int[2]; System.out.println(arr[0]); System.out.println(arr[1]); } } Output is 0 0

133

In general to create an array you must follow three steps y y y Declaration Construction Initialization

Declaration tells the java compiler what the arrays name is and what the type of its elements will be. For example, int[ ] ints;//ints ia an integer array variable double[ ] dubs;//dubs is a double array variable char[ ] chars//chars is a character array variable. float[ ] floats;//floats is a float array variable. Construction means calling the new operator to allocate memory for the array variable. During initialization process the elements of the array is initialized to their default values. Array Element Initialization Values Element Type Byte Int Float Char Short Long Double Boolean reference Initial Values 0 0 0.0f \u0000 0 0L 0.0d false null

134

In the above program array constructed where it is declared. You can separate the process. Example-2 public class Demo { public static void main(String[] args) { int[] arr;//array declaration arr=new int[2];//array construction System.out.println(arr[0]); System.out.println(arr[1]); } } A closer look at array Example-3 public class Demo { public static void main(String args[]) { int [ ]mak=new int[3]; //Array declaration in java mak[0]=1; mak[1]=2; mak[2]=3; System.out.println(mak[0]); System.out.println(mak[1]); System.out.println(mak[2]); } } Output is 1 2 3 int mak[ ]=new int[3]; is the statement to create the integer array of length 3. Remember that new operator always allocates memory from the heap. If [ ] is associated with variable declaration then, that variable is of reference type. So mak is a reference type variable that

135

means it is going to hold the address of a memory location. The new operator allocates memory from heap according to the size specified & the starting address is stored in mak. The memory is allocated continuously for mak from heap.

mak is the reference variable created inside stack. The new operator allocates memory from heap & the starting address of the memory location i.e. 65556 is stored in mak. Since for array continuous memory allocation is done & integer takes 4 byte of memory therefore the address of the next memory location is 65560 & so on. To access the elements present in the array the statement is System.out.println(mak[0]); System.out.println(mak[1]); System.out.println(mak[2]); Value stored in mak mak[0] mak[1] mak[2] means value stored at (65556+0* size of integer ) means value stored at (65556+1* size of integer) means value stored at (65556+2*size of integer)

136

In general if you have declared Data_Type [ ]var_name=new Data_Type[size]; var_name[i] Data_Type) means value stored at (starting address+ i* size of

here i is an integral index & i<size. If the data type is of object reference then size will be 4 bytes. Array actually are objects, even to an extent you can execute methods on them, mostly of the object class. But, you can not create child class or sub class of an array. Creating a programmer-initialized array Example-4 public class Demo { public static void main(String args[]) { int [ ]mak={1,2,3}; //Array declaration in java mak[0]=1; mak[1]=2; mak[2]=3; System.out.println(mak[2]); } } Output is 3 One may think that how array is created with out new operator. In the above situation java compiler implicitly calls the new operator to allocate memory from heap. Accessing the element beyond the size of an array throws a compile time error as shown in the program below.

137

Example-5 public class Demo { public static void main(String args[]) { int [ ]mak={1,2,3}; //Array declaration in java mak[0]=1; mak[1]=2; mak[2]=3; System.out.println(mak[3]); } } This program generates an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Demo.main(Demo.java:13) Creation of reference to a primitive: This is a useful technique to create a reference of primitive data type. Array in java provides such technique. In this procedure the data is stored in heap instead of stack. Simply you just create an array of one element of primitive data type Example-6 public class Demo { public static void main(String args[]) { int [ ]mak=new int[1]; //Array declaration in java mak[0]=10; changeIt(mak); System.out.println(mak[0]); } static void changeIt(int []p) { p[0]=100; }

138

} Out put are 100 Due to reference change is reflected.

MULTIDIMENTIONAL ARRAY

Two dimension array: To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called twoD. int twoD[ ][ ] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. [0][0] [0][1] [0][2] [0][3] [0][4]

[1][0]

[1][1]

[1][2]

[1][3]

[1][4]

[2][0]

[2][1]

[2][2]

[2][3]

[2][4]

[3][0]

[3][1]

[3][2]

[3][3]

[3][4]

Left index indicates row number & right index indicates column number. A closer look at two dimensional array. The declaration Int [][]town; town=new int[3][3]; Or int [][]town=new int[3][3] creates a two dimensional array. What exactly town is?. town in fact a reference to an array of integer reference. Surprised!!,(If you are good in c,c++ you can feel that it is something like pointer to an array of pointers.) A closer look at two dimensional array.

139

The declaration Int [][]town; town=new int[3][3];

Or int [][] town=new int[3][3] creates a two dimensional array. What exactly town is?. town in fact a reference to an array of integer reference. Surprised!!,(If you are good in c,c++ you can feel that it is something like pointer to an array of pointers.) In the statement town=new int [3][3]; it is the number of rows.Actually no of rows represents the number of integer references to which town is pointing.The no.ofcolumn represents the length of the integer array towhich each element of the array of references pointing. Confused!!! Ok lets have the snap short of memory representation of two dimensional array .

Really is it happens! Yes 100%.Fine lets check it out programmatically.

140

Exampe-7 class demo { Public static void main(String args[]) { Int [][]town=new int[4][]; System.out.println(town[0]); System.out.println(town[1]); System.out.println(town[2]); } } OUTPUT: null null null Why null null null ? As I have said earlier in java when you create an array all the elements are initialized to their default value according to the variable. If you check that table reference type variables default value is null. This is the reason why the output is null null null

lets have a snap short of memory for the above program.

141

STACK Town 1000 1000

HEAP

null null 1004 null 1008 null 1012

Example-8 Unequal second dimension class demo { Public static void main(String args[]) { Int [][] town=new int[3][]; town[0]=new int [1]; town[2]=new int [2]; town[2]=new int [3]; Int I,j,k=0;

for(i=0;i<3;i++) for(j=0;j<=I;j++)

142

{ town[i][j]=k; K++; } for(i=0;i<3;i++) { for(j=0;j<i;j++) { System.out.print(town[j][j]+ ); } System.out.println( ); } } } Output: 0 1 2 3 4 5 Let me explain the program. As I have said town is a reference variable pointing to an array of reference of length 3 as shown in the snap shot of memory .

143

town[o] is a reference to integer type. So through a new operator we allocate memory to it. town[0]=new int [1]; implies that integer array of length one is created in the heap and its starting address 6000 here is allocated to town[0]. An interesting thing is that reference is created inside heap and memory is allocated to it from the heap also.

Array of objects Example-9 Lets begin this section with an example class Demo { int x; public static void main(String args[])

144

{ Demo []arr=new Demo[3]; arr[0]=new Demo(); arr[0].x=0; arr[1]=new Demo(); arr[1].x=1; arr[2]=new Demo(); arr[2].x=2; for(int i=0;i<3;i++) System.out.println(arr[i].x); } } Output: 0 1 2 In the above example I have created an array of objects. The above codes are not simple & straight as it looks. Let me explain the program: Demo [] arr=new Demo[3]; Demo is the class name. What is arr? As I have mentioned in the previous sections, in Java a variable of class type is not a normal variable, rather it is a reference variable. So arr is a reference to an array of references & each element of the array is a reference of class Demo created inside heap. Lets have a snap shot of memory. Diagram: arr is created inside stack. When the statement Demo []arr=new Demo[3];is executed array of references is created inside stack, & the staring address is stored in arr. Remember that size of a reference variable is 4 bytes, if 1000 is the address of the 1st element of the array then next one is 1004 & so on. Each element of the array is a reference variable of Demo class, so you cannot access instance variable x. if you try to do that then null pointer exception will arise. This is because whenever a reference variable is created in side heap, its default value is null. Finally I have to allocate memory to each element present in the array to access the instance variable. This is

145

done by calling the constructor of Demo class through new operator. (arr[0]=new Demo();) Now I can store a value in the instance variable x.

Method returning reference to an array See the example below. Just check the signature of the method returning the reference else everything is straight forward. Example-10 class Demo { public static void main(String args[ ]) { Demo x=new p1(); int[ ] arr_Ref=x.funRef(); System.out.println(arr_Ref[2]); } int[] funRef() { int [ ]arr1=new int[3]; arr1[0]=1; arr1[1]=2; arr1[2]=3; return arr1; } }

146

Brain Drill

Assignment-1:Draw this By the help of Array in java?

Program:import java.io.*; public class ArrayTask1 { public static void main(String args[]) {

147

try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter The Number Of Rows"); int r=Integer.parseInt(br.readLine()); char c[][]=new char[r][]; for(int k=0;k<r;k++) { c[k]=new char[k+1]; } for(int k=0;k<r;k++) { for(int j=0;j<=k;j++) { if(j==0) c[k][j]='*'; else if(j==k) c[k][j]='*'; else if(k==(r-1)) c[k][j]='*';

else c[k][j]=' '; }

148

} for(int k=0;k<r;k++) { for(int j=0;j<=k;j++) System.out.print(c[k][j]); System.out.println(); } }catch(IOException ie) { } } } Assignment-2:Draw This Triangle By Array?

149

Program:import java.io.*; public class ArrayTask2 { public static void main(String args[]) { try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)) ; System.out.println("Enter Number Of Rows"); int r=Integer.parseInt(br.readLine());

150

char c[][]=new char[r][r]; for(int k=0;k<r;k++) { for(int j=0;j<r;j++) { if(j<k) c[k][j]=' '; else c[k][j]='*'; } } System.out.println("See The Structure"); for(int k=0;k<r;k++) { for(int j=0;j<r;j++) { System.out.print(c[k][j]); } System.out.println(); } }catch(IOException ie) { } }

151

} Assignment-3:Enter four integer value from keyboard and Sort the elements of array in Ascending order? import java.io.*; public class ArrSortA { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i=0,j,temp; int ar[]=new int[4]; System.out.println("Enter The Array Elements"); for(i=0;i<ar.length;i++) { ar[i]=Integer.parseInt(br.readLine()); for(j=0;j<ar.length;j++) { if(ar[i]<ar[j]) { temp=ar[j]; ar[j]=ar[i]; ar[i]=temp; }

152

} } for(i=0;i<ar.length;i++) { System.out.println(ar[i]+"\n"); } } } Output:

Assignment-4:Enter 5 integer through an array and find out Smallest Number?

153

import java.io.*; public class ArrSmall { public static void main(String args[])throws Exception { int i,j,temp=0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int ar[]=new int[5]; System.out.println("Enter The Array Elements"); for(i=0;i<5;i++) { ar[i]=Integer.parseInt(br.readLine()); for(j=0;j<5;j++) { if(ar[i]<ar[j]) { temp=ar[j]; ar[j]=ar[i]; temp=ar[i]; } } } System.out.println("Smallest No is "+temp) } ;

154

} Output:

Assignment-5:Enter A Number and find out the Binary Value?

import java.io.*; public class Binary { public static void main(String args[])throws Exception { int num,i=0,j,k; int a[]=new int[20]; int b[]=new int[20]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter any number");

155

num=Integer.parseInt(br.readLine()); while(num>0) { a[i]=num%2; i++; num=num/2; } k=i-1; System.out.print("\n\n"); for(j=0;j<i;j++) { b[j]=a[k]; System.out.print(b[j]); k--; } } } Output:

156

Assignment-6:Enter a decimal and find out the octal value? import java.io.*; public class DecimalOctal { public static void main(String args[])throws Exception { int r,q,o,num; int a[]=new int[10]; int b[]=new int[10]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Any Number"); num=Integer.parseInt(br.readLine()); o=0; while(num>0) {

157

if(num<8) { a[o]=num; o++; break; }else{ a[o]=num%8; o++; num=num/8; } } r=0; for(q=o-1;q>=0;q--) { b[r]=a[q]; r++; }

System.out.println("Octal Number Is ") ; for(q=0;q<r;q++)

158

{ System.out.print(b[q]); } } } Output:

159

CHAPTER 9 :

Inheritance
Inheritance is one of the fundamental concepts of object oriented programming. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a super class & the class that inherits the properties of super-class is known as derived class or child class. Java uses extends keyword to support inheritance. The general syntax is

class X { //Codes } class Y extends X { //Codes } Class baseClass extends superClass{ //Codes } should be the syntax. Here X is the super class Y is the child class or derived class Benefits of inheritance y Code reusability because derived class (child class) copies the member of super class (parent class).

Restriction: if the super class members are private, then child class cannot copy them & another thing JAVA does not support multiple inheritances. To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. To see how, lets begin with a short example.

160

class X{ void show() { System.out.println("Hello, Java I am inherited"); } } class Y extends X { } class Demo { public static void main(String argts[]) { Y a=new Y(); a.show(); } } Output: Hello, Java I am inherited In the above example X is known as the super class & Y is the derived class or you may say the child class. In side main() method object of child class is created but the show() method of parent class is invoked. show() method is not a member of Y. In case of inheritance child class copies members of the parent class those are not private, to it self. show() method belongs to class X. It has default access specifier. Therefore it can be inherited with in a package. By using extend keyword show() method is copied to class Y. Hence any object of class Y can invoke show() method.

Multi-level inheritance. class X { void show() { System.out.println("Hello, Java"); } }

161

class Y extends X { } class Z extends Y { Z() { super.show(); } } Output: Hello, Java Hello, Java Here show() method of X is copied to class Y & from class Y to class Z. Hence the object of class Z can invoke show() method which is written in class X. In this way inheritance facilitates code reusability.

super Keyword super is a keyword. Through the use of super keyword programmer can access the members of super class. Java does not allow the use of super keyword inside static method & static block. super keyword is used for two purposes y If the super class instance variable name is same as that of child class or sub class instance variable name, then to access the super class instance variable super keyword is used only the inside sub class. class X{ int i=9; } class Y extends X { int i=90; void showSuper() { System.out.println(i); System.out.println(super.i); } }

162

class Demo { public static void main(String args[]) { Y a=new Y(); a.showSuper(); } } Output: 90 9 X is the base class which has the instance variable i. Y is derived from X & also has the instance variable i. Inside the child class Y showSuper() is a method. The first statement inside the showSuper() method prints the value of i that belongs to child class Y. To access the parent class i, super keyword is used. Through the use of super.i programmer can access the super class instance variables.

Java uses super keyword for explicitly calling the super class constructor within child class constructor.

Restriction: y super must be the first statement in side the child class constructor, other wise it will give compile time error. Example: class X { X() { System.out.println("Parent class"); } } class Y extends X { Y() { super();

163

System.out.println("Child class"); } } class Demo extends Y { public static void main(String argts[]) { Y d=new Y(); } }

Output: Parent class Child class

Just like super, this is also used to call the constructor of the current class with in a constructor & it must be the first statement otherwise compile time error will arise. class Demo { Demo() { System.out.println("Inside Default constructor"); } Demo(int i) { this(); System.out.println("Inside parameterized constructor"); } public static void main(String argts[]) { Demo d=new Demo(3); } }

164

Output: Inside Default constructor Inside parameterized constructor

Calling of constructor In case of inheritance when the programmer creates the child class object by calling the child class constructor through new operator, at that time the super class default constructor is implicitly invoked. class X { X() { System.out.println("Inside super class default constructor"); } X(int i) { System.out.println("Inside super class parameterized constructor"); } } class Y extends X { } class Demo { public static void main(String argts[]) { Y d=new Y(); } } Output Inside super class default constructor

When you define the super class parameterized constructor & do not define the super class default constructor then compile time error will arise.

165

class X { X(int i) { System.out.println("Inside super class parameterized constructor"); } } class Y extends X { } class Demo { public static void main(String argts[]) { Y d=new Y(); } } Output It will give compile time error as Exception in thread "main" java.lang.Error: Unresolved compilation problem: Implicit super constructor X() is undefined for default constructor. Must define an explicit constructor at demo.Y.<init>(Demo.java:12) at demo.Demo.main(Demo.java:20)

If you call the child class parameterized constructor at that time also parent class default constructor is called. class X {

166

X() { System.out.println("Inside super class default constructor"); } X(int i) { System.out.println("Inside super class parameterized constructor"); } } class Y extends X { Y(int i) { System.out.println("Inside child class parameterized constructor"); } } class Demo { public static void main(String argts[]) { Y d=new Y(6); } } Output: Inside super class default constructor Inside child class parameterized constructor If you are not defining the super class default constructor then inside child class constructor just calls the parent class parameterized constructor as shown in the example below. class X { X(int i) {

167

System.out.println("Inside super class parameterized constructor"); } } class Y extends X { Y(int i) { super(8); System.out.println("Inside child class parameterized constructor"); } } class Demo { public static void main(String argts[]) { Y d=new Y(6); } } Output: Inside super class parameterized constructor Inside child class parameterized constructor See here parent class parameterized constructor is called through super key word & it is the first statement in side child class constructor. Method over ridding & Dynamic method dispatch Method over ridding is only possible in case of inheritance where super class method is over ridden in its child class. In case of method over ridding method name, its argument type, no. of arguments & return type is exactly same. Access specifires may be same or least restrictive in the child class where the parent class method is over ridden. Private methods can not be over ridden. Static & final methods also can not be over ridden. class X { X() {

168

System.out.println("Inside super class parameterized constructor"); } void fun() { System.out.println("Parent"); } } class Y extends X { Y() { System.out.println("Inside child class parameterized constructor"); } void fun() { System.out.println("Child"); } } class Demo { public static void main(String argts[]) { Y d=new Y(); d.fun(); } } Output: Inside super class parameterized constructor Inside child class parameterized constructor Child Here the fun method is over ridden in Y. inside Demo class I have created the object of Y i.e. d is the object of Y, so d.fun() invokes the fun method that is overridden in Y. class X { X() {

169

System.out.println("Inside super class parameterized constructor"); } protected void fun() { System.out.println("Parent"); } } class Y extends X { Y() { System.out.println("Inside child class parameterized constructor"); } public void fun() { System.out.println("Child"); } } class Demo { public static void main(String argts[]) { Y d=new Y(); d.fun(); } } Output: Inside super class parameterized constructor Inside child class parameterized constructor Child See here in the parent class X access specifier of fun is protected & when it is over ridden in its child class Y acess specifier of fun is public which is less restrictive than protected. There fore the program is successfully compiled & child class fun method is invoked. class X { X() {

170

System.out.println("Inside super class parameterized constructor"); } void fun() { System.out.println("Parent"); } } class Y extends X { Y() { System.out.println("Inside child class parameterized constructor"); } proteted void fun() { System.out.println("Child"); } } class Demo { public static void main(String argts[]) { Y d=new Y(); } } This program will result compilation error because in parent class the access specifier of fun is default where in child access specifier of fun is protected which is more restrictive than default access. So you have to be careful in this issue while performing the method over ridding. Dynamic method dispatch in case of method over ridding : Method over ridding implements dynamic polymorphism i.e. it is executed in run time. So when over ridden method is invoked, it completely depends which class object invokes the method. class X { X() {

171

System.out.println("Inside super class parameterized constructor"); fun(); } void fun() { System.out.println("Parent"); } } class Y extends X { Y() { System.out.println("Inside child class parameterized constructor"); } void fun() { System.out.println("Child"); } } class Demo extends Y { public static void main(String argts[]) { Y d=new Y(); d.fun(); } } Inside super class parameterized constructor Child Inside child class parameterized constructor Child Output clearly shows that fun method of child class is invoked. Inside main method since child class object is created therefore fun method of child class is called although it is called inside the body of the super class constructor. If you write this.fun() inside the super class constructor due to the mentioned reason the fun() method of child class is called. class X { {

172

fun(); } X() { System.out.println("Inside super class parameterized constructor"); fun(); } void fun() { System.out.println("Parent"); } } class Y extends X { Y() { System.out.println("Inside child class parameterized constructor"); } void fun() { System.out.println("Child"); } } class Demo extends Y { public static void main(String argts[]) { Y d=new Y(); d.fun(); } } Output: Child Inside super class parameterized constructor Child Inside child class parameterized constructor Child Here also fun() method of child class is invoked. This is because when any overridden method is called it completely depends through which object the

173

overridden method is called & according to that appropriate function call takes place. Parent class reference variable can hold the child class object. In this case also since the object of child class is created, therefore child class method will be invoked. See the example below class X { X() { System.out.println("Inside super class parameterized constructor"); fun(); } void fun() { System.out.println("Parent"); } } class Y extends X { Y() { System.out.println("Inside child class parameterized constructor"); } void fun() { System.out.println("Child"); } } class Demo extends Y { public static void main(String argts[]) { X d=new Y(); d.fun(); } } Output: Inside super class parameterized constructor Child

174

Inside child class parameterized constructor Child Inside main() method X d=new Y() implied that parent class reference variable holds the address of child class created. Since child class object is created there fore child class fun method is called. Behavior of instance variables in case of inheritance.: Instance variables are initialized at the compile time. If super class instance variable name is same as that of child class instance variable name, when you access such a variable then the reference type matters. class X { int i=40; } class Y extends X { int i=90; } class Demo extends Y { public static void main(String argts[]) { X d=new Y(); System.out.println(d.i); } } Output: 40 In main() method I have created reference variable of parent class. Variables are initialized at compile time; hence parent class instance variable is accessed. Behavior of overloaded method in inheritance: Method overloading is done at compile time. So when you call a overloaded method according to the reference type appropriate method is called.

175

class X { void fun() { System.out.println("Parent class"); } } class Y extends X { void fun(int x) { System.out.println("Child class"); } } class Demo extends Y { public static void main(String argts[]) { X d=new Y(); d.fun(); Y a=new Y(); a.fun(); a.fun(6); } } Output: Parent class Parent class Child class Here d is a reference of parent class. So when you write d.fun(); parent class fun() is invoked. Rest of the lines are straight foreward. Now another important thing. See the program below. class X { void fun() { System.out.println("Parent class"); }

176

} class Y extends X { void fun(int x) { System.out.println("Child class"); } } class Demo extends Y { public static void main(String argts[]) { X d=new Y(); d.fun(); d.fun(6); }

} Above program will result compilation error. Because parent class X does not have a fun method which takes an integer argument. So what we conclude is that when ever programmer deals with aspects those are performed at compile time, the type reference variable matters. When programmer deals with the aspect which are performed at run time the type of object created matters. Difference between super & this super is a keyword in java but this is a reference variable. super is only used to access the parent class members & the parent class constructor. class X { X() { System.out.println("Parent class"); } } class Y extends X { Y()

177

{ super(); System.out.println("Child class"); } Y fun() { return this; } void show() { System.out.println("Hello R u foxed!!"); } } class Demo extends Y { public static void main(String argts[]) { Y d=new Y(); Y x=d.fun(); if(d==x) { x.show(); } } } Out put Parent class Child class Hello R u foxed!! Here in child class fun method return this, the address of the currents object memory location which is assigned to x. That is address of d is assigned to x. package demo; class X { X() { System.out.println("Parent class"); } } class Y extends X

178

{ Y() { super(); System.out.println("Child class"); } X fun() { return super; } } class Demo extends Y { public static void main(String argts[]) { Y d=new Y(); X x=d.fun(); } } Above program will result a compilation error because super is not a reference variable. it is simply keyword in java. Hence to fix the bug rewrite the program as below class X { X() { System.out.println("Parent class"); } } class Y extends X { Y() { super(); System.out.println("Child class"); } X fun() { X x=new X(); return x; } void show() {

179

System.out.println("Hello R u foxed!!"); } } class Demo extends Y { public static void main(String argts[]) { Y d=new Y(); X a=d.fun(); } } Output: Parent class Child class Parent class Here out put is straight foreword.

Thats all about inheritance in java folks.

abstract
abstract is a keyword or modifier used in case of class & method. If the class is declared as abstract, programmer cannot instantiated that class means cannot create the object of that class. Abstract method means method having declaration only. Abstract method body is not defined where it is declared rather it is declared somewhere else. Syntax to declare an abstract class: abstract class X{ } You can create the reference of an abstract class but you cannot create the object of the abstract class by calling the constructor of the corresponding class through new operator. If you try to create the object of the abstract class compilation error will arise. X ab;// possible ab=new X();//Compilation error

180

If a class is declared as abstract the methods those are the member of that class may abstract or may not be. But on the other hand if any of the method of a class is abstract then the class has to be abstract. Abstract methods are declared inside the abstract class but defined in their child class. If any of the child class does not define the abstract method of its super class then that child class has to be declared as abstract class otherwise compilation error will be generated. abstract class X { int i=10; public abstract void display(); { System.out.println("Hello"); } } class Y extends X { int i; public void display() { System.out.println("Finally I got Life!!"); } } class Demo { public static void main(String argts[]) { X a=new Y(); a.display(); System.out.println(a.i); } }

181

Output: Hello Finally I got Life!! 10 final & abstract behave complement to each other. When a class is declared with final keyword, that class can not be inherited. But abstract class has to be inherited in order to define its abstract methods. There fore abstract class can not use final keyword. Constructors can not be abstract. Although you can not call the constructor of abstract class, still you can declare the constructor of the abstract class. Using super keyword inside the constructor of child class you can invoke the constructor of abstract parent class. abstract class X { public abstract void fun(); X() { System.out.println("X constructor"); } } class Y extends X { public void fun() { System.out.print("Hello"); } Y() { super(); } } class Demo { public static void main(String argts[]) { X a=new Y(); a.fun(); }

182

} Output: X constructor Hello Interface First of all interface is a keyword. Interface declaration is same as class declaration. e.g. public interface X { } Interface X { } Interfaces are implicitly abstract in nature. Interface cannot be instantiated. In interface all the methods are public & abstract by default. As the methods are public & abstract by default therefore those methods has to be overridden in their corresponding child class. The methods belonging to an interface are looked up at runtime. In interface variables are implicitly public, static & final. The advantage of declaring variables within an interface is that they become globally available to all classes and need not be declared explicitly in classes implementing them. interface supports multiple inheritance. Example:-1 interface in { String toString(); }

183

public class Test implements in { public static void main(String a[]) { System.out.println(new in() { public String toString() { return "test"; } }); } } Output:test Example-2 interface Declare { public static final int i=3; void doStuff(int i1); } public class A implements Declare {

184

public static void main(String args[]) { int x=5; new A().doStuff(++x); } public void doStuff(int s) { s+=i + ++s; System.out.println("Output Is "+s); } } Output:Output is 16

Final keyword:
Final keyword is used in class, method and variable. If the class is declared as final the then the class cannot be inherited. String, Math, Wrapper classes are treated as final so these classes have no child class. Ex. class X extends String //error as String is a final class If the method is declared as final then method cannot be override. In technical term final method cannot be override. Ex. class X { Final void show() { //code here } }

185

class Y extend X { void show() { //code here } } //error final method cannot be override. If the variable is declared as final then the value of final variable cannot be changed or modified. In technical term we cannot assign the value to final variable.
Ex. final int i=10; void show() { i++; //Error } final variable must be initialized. Ex. public class X { final int i; void show() { System.out.println(i); } public static void main(String args[]) { X ab=new X(); ab.show(); } } Error: This program generates a compile time error that i is not initialized. As i is a final variable , i must be initialized.

186

Chapter-10

Inner Class / Nested Class


Java supports Inner class or nested class. Define one class within another class is treated as Inner class or nested class. In java four types of inner classes are used. y y y y Static Inner Class Non-static Inner Class Local Inner Class Anonymous Inner Class

A nested or inner class is the member of its enclosing class. Nested class can be declared by using any access modifier. In java outer class or enclosing class is declared by using public or no access modifier. Nested class is able to access private, protected, no access or public member of enclosing class.

Advantage of Using Inner / Nested class:1. Logical grouping of classes 2. Increased encapsulation 3. More readable, maintainable code

Static Inner Class


If the Inner class uses the static modifier then the Inner class is treated as static inner class. For Example:class X { static class Y { }

187

} Here Y class is treated as static inner class.

Key Points of Static Inner Class:y y y y y y y y Programmer declares the static inner class by using any access modifier. Static Inner class access the static member of outer or enclosing class through the outer class name or directly. Static Inner class access the non-static member of the outer or enclosing class through the instance or object of the outer class. Static Inner class static member access the non-static member of the Inner class through the instance of static Inner Class. Static Inner class static member access the static member of the Inner Class through the name of the static inner class or directly. Static Inner Classs Non-static member access the static member of the inner class through the Inner class name or directly. Static Inner classs non-static member access the non-static member of the inner class directly. Static Inner Class supports inheritance.

Example-1:public class Inner1 { String name; static int roll; private String getName(String n) { name=n; return name; } static int getRoll(int r)

188

{ roll=r; return roll; } static class Test { int age=10; static String add="Cuttack"; void display() { Inner1 i1=new Inner1(); System.out.println("Name Is "+i1.getName("Sai")); System.out.println("Roll Number Is "+Inner1.getRoll(1)); System.out.println("Age Is "+age+"\t"+"Address Is "+add); } } public static void main(String args[]) { Test t1=new Test(); t1.display(); } } Output:

189

Example-2 public class Inner2 { String name; static int roll; private String getName(String n) { name=n; return name; } static int getRoll(int r) { roll=r; return roll; } static class Test { int age=10; static String add="Cuttack";

190

static void display() { Inner2 i1=new Inner2(); Test t=new Test(); System.out.println("Name Is "+i1.getName("Sai")); System.out.println("Roll Number Is "+Inner1.getRoll(1)); System.out.println("Age Is "+t.age+"\t"+"Address Is "+Test.add); } } public static void main(String args[]) { Test.display(); } } Output:

Example-3 public class Inner3 { String name;

191

static String add; static int age; private static class Test1 { int roll; String getName(String n) { Inner3 i3=new Inner3(); i3.name=n; return i3.name; } int getAge(int a) { Inner3.age=a; return Inner3.age; } } protected static class Test2 extends Test1 { int getRoll(int r) { roll=r; return roll; }

192

String getAddress(String a) { Inner3.add=a; return Inner3.add; } } public static void main(String args[]) { Test2 t=new Test2(); System.out.println("Name Is "+t.getName("Sai")); System.out.println("Age Is "+t.getAge(10)); System.out.println("Roll Number Is "+t.getRoll(1)); System.out.println("Address Is "+t.getAddress("Cuttack")); } } Output:

193

Non-static Inner Class:Class declared within another class without using static modifier is treated as non-static Inner class. Non-static inner class is popularly known as Inner class. We declare non-static inner class by using any access modifier. Class X { Class Y {

} } Here class Y is treated as non-static inner class

Key Points of Non-Static Inner Class:y y Non-static inner class non-static member access the static member of the outer class through the outer class name or directly. Non-static inner class non-static member access the non-static member of the outer class directly without creating any instance of the outer class. Within non-static inner class we cannot declare any static member This inner class is very popularly used.

y y

Example-4 public class Inner4 { String name; static int age; private String getName(String n)

194

{ name=n; return name; } static int getAge(int a) { age=a; return age; } private class Test1 { int roll; String add; int getRoll(int r) { roll=r; return roll; } String getAddress(String s) { add=s; return add; } void display()

195

{ System.out.println("Name Is "+getName("Sai")); System.out.println("Age Is "+Inner4.getAge(10)); System.out.println("Roll Number Is "+getRoll(1)); System.out.println("Address Is "+getAddress("Cuttack")); } } public static void main(String args[]) { Inner4 t1=new Inner4(); t1.show(); } void show() { Test1 t1=new Test1(); t1.display(); } } Output:

196

Example-5 public class Outer1 { String name; int roll; public class Inner1 { String getName(String n) { name=n; return name; } int getRoll(int r) { roll=r; return roll; } } public static void main(String args[]) { Outer1 o1=new Outer1(); Inner1 i1=o1.new Inner1(); System.out.println("Name Is "+i1.getName("Asit")); System.out.println("Roll Number Is "+i1.getRoll(4));

197

} }

Local Inner Class:Class declared within the method is treated as local inner class. class X { void show() { class Y {

} } } Here class Y is treated as Local inner class as it is declared within the method show.

Key Points of Non-Static Inner Class:y y Local inner class is declared through no-access modifier but not declared through public, private and protected access modifier. Local Inner class access the private member of the outer class

198

y y y y

Local Inner class non-static member directly access the static member of the outer class. Local inner class non-static member directly access the nonstatic member of the outer class. Local inner class only accesses the final member of the method where the class is declared. Programmer creates the object of local inner class within the method where the class is declared.

Example-6 public class Local1 { String name; private static int roll; protected static int age; String add; void go(final int a,int b) { final int x=a+b; int y=a-b; class Inner { String getName(String n) { name=n;

199

return name; } int getAge(int a) { age=a; return age; } int getRoll(int r) { roll=r; return roll; } String getAddress(String s) { add=s; return add; } void show() { System.out.println("Name Is "+getName("Sai"));

200

System.out.println("Age Is "+getAge(10)); System.out.println("Roll Number Is "+getRoll(1)); System.out.println("Address Is "+getAddress("Cuttack")); } void display() { System.out.println("Value Of A Is "+a); //System.out.println("Value Of B Is "+b); System.out.println("Value Of X Is "+x); } } Inner i1=new Inner(); i1.show(); i1.display(); } public static void main(String args[]) { Local1 l1=new Local1(); l1.go(10,2); } }

201

Output:

Anonymous Inner Class:You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes. In other words the declaration and initialization of the class is done on the same line. addFocusListener(new FocusAdapter() { Public void focusGained(FocusEvent fe) { } }); Here FocusAdapter is treated as Anonymous Inner Class.

202

CHAPTER 11:

Exception Handling
Introduction
Exceptions are abnormal behavior of program during its execution state. You can say that exceptions are runtime error. Compile time errors never come under exception. They are simply errors. Exception occurs only at the execution state of the program. Exceptions that can be generated in a java programs are

   

If the array index cross the range. If the number divide by zero. The file you try to open may not exist. The class file programmer want to load may be missing etc.

Some of the exceptions are detected at compile time & some of the exceptions are detected during run time. In java the exceptions those are detected during compile time is known as checked exception & exceptions those detected during the execution of java program by JVM is called unchecked exception. Since unchecked exceptions are generated during the execution of the program, java programmer can create programs having unchecked exceptions. But, things are completely different in case of checked exception. If the programmer does not handle the checked exception then java compiler detects them & program terminate at the compilation stage. Programmer can not ignore the checked exception. In java exception handling is done by 5 keywords: try,catch,throw,throws & finally. Briefly here is how they work. Programming codes that you want to monitor for exceptions are embedded inside this block. If an exception is generated inside try block then it has to be thrown. When the programmer manually handles the exception, he has to use throw keyword. In this case catch follows the try block in order to handle the exception. When an exception is thrown out of a method throws keyword has to be used. If some piece of code that is necessary to be executed after try block then those has to be written in side finally block. The general syntax of exception handling block is try{ //Block of code to monitor for errors }

203 catch(Exception_Type_1 excp1){ //Codes to handle the exception } catch(Exception_Type_2 excp2) { //Codes to handle the exception } catch(Exception_Type_3 excp3) { //Codes to handle the exception } //. finally{ //Codes that has to be executed must }

In java Exception is handled by five keywords try, catch, finally, throw, throws.

204

In java Exception is of two types Checked and Unchecked Exception.


Checked exceptions: ClassNotFoundException, IOException are checked exceptions. & its child classes all

Unchecked Exception: Error,RuntimeException & its child classes all are treated as unchecked exception.

Types of Exception:         ArithmeticException. ArrayIndexOutOfBoundsException. ArrayStoreException. ClassCastException. IllegalArgumentException. IllegalMonitorStateException. IllegalStateException. IllegalThreadStateException. IndexOutOfBoundsException.

205

           

NegativeArraySizeException. NullPointerException. NumberFormatException. SecurityException. StringIndexOutOfBounds. UnsupportedOperationException. ClassNotFoundException. CloneNotSupportedException. IllegalAccessException. InstantiationException. NoSuchFieldException. NoSuchMethodException.

Types of Error:     AWTError VirtualMachineError OutOfMemoryError StackOverFlowError AssertionError

Throwable Class Throwable is a class present in java.lang package. Throwable is the super class of Exception and Error. Constructors of Throwable class public Throwable() this constructor creates a Throawble object with a null information embedded within the object. public Throwable(String mess) this constructor creates a Throawble object with a the message mess supplied by the programmer embedded within the object. public Throwable(String message, Throwable reason)

206

this constructor creates a Throawble object with a the message mess supplied & the reason behind the exception through the Throwable object reason . public Throwable(Throwable reason) this constructor creates a Throawble object with a the reason behind the exception by Throwable object rason.

Use of try, catch & finally block: try block: All the exception generating codes are embedded within try block. Java supports nested try block. catch block: catch block is treated as exception handler. The catch block caught the exception that will arise within the try block. Every try block must be followed by a catch block. In java one try block can have multiple catch block. If the catch parameter matched with the exception, then the programmer is able to handle the exception. On the other hand if the catch if the catch parameter is not matched, then the program is terminated. The matching is done by JVM using instanceof operator. Finally block: In java the try block is executed means the finally block must be executed. Without try block finally block cannot be executed. Either the programmer caught the exception or not finally block must be executed. If the programmer is able to caught the exception, first catch block is executed & then finally block is executed. But in the other hand if the programmer is not able to caught the exception, finally block is executed & program terminates. Finally block is executed in java to give control to the programmer. As the finally block must be executed, with in the finally block you can use another try catch block. Throws: throws keyword is used in java to throw the exception from the called method to the calling method. The calling method should have the tool to handle the exception thrown from called method. It is used in method definition. Exception handling provides two benefits 1: Allows to fix the bug. 2: Prevents the automatic termination of the program.

207

How JVM handles an exception Now it is important for the beginners to understand what will happen if you dont handle the exception. Let me explain it through an example Example-1 public class Demo { public static void main(String argts[]) { int x=12,y=0,z; z=x/y; System.out.println(I am not executed); } }

Output:-

This program is compiled successfully. During its execution, JVM detects the attempt to divide by zero. At that instant of time JVM generates unchecked exception object & throws it. This terminates the execution at the runtime. When the exception is thrown, there must have some technique to handle or mange it by the use of catch block. In the given program there is no exception handler provided by the programmer so the default exception handler of JVM caught the exception. If programmer manually does not handle the exception then JVM handle them by default handler. The default handler throws a message to the screen as

208

Exception in thread "main" java.lang.ArithmeticException: / by zero at Demo.main(Demo.java:7). Actually when exception occurs & it is handled by JVM, JVM shows the stack trace message from the point where exception has been occurred. If you see the message carefully it clearly shows exception occurs in demo packages Demo classs main method at line no: 7. When such run time exception occurs, it leads to abnormal termination of the program. The codes below the point where such exceptions occur are never executed. That is the reason why the last statement of the program is not executed. Use of try & catch block Let me use the try, catch tool for the previous program. Example-2 public class Demo { public static void main(String argts[]) {

int x,y,z; x=9; y=0; try{ z=x/y; }catch(ArithmeticException e) { System.out.println("You can not devide an intrger by zero"); System.out.println("so using y++");

209

y++; z=x/y; } System.out.println("I am executed"); } } Output:-

In the first case there no exception handler provided by the programmer, therefore the program terminates abnormally. To prevent the abnormal termination of the program, simply put the codes to be monitored inside the try block. A catch block immediately follows the try block to catch the thrown exception. When an integer is divided by zero java generates ArithmeticException. The catch block catches the exception by the ArithmeticException object e. So the program does not terminate abnormally. But, one thing the programmer has take care of is that the codes below the point where the exception is generated is not going to be executed. The program below illustrates the above fact. Example-3 class Demo { public static void main(String argts[]) { int x,y,z; x=9; y=0; try{ z=x/y; System.out.println("I am not Executed");

210

}catch(ArithmeticException e) { System.out.println("Exception is handled"); } } } Output: Exception is handled A try block holds a piece of Exception arising codes and its catch block treats as an Exception handler. If the Generated Exception is handled by the catch block through that Exception or its super class then the programmer is able to handle the Exception. How to know why the exception is generated As Throwable is the child class of Object class it overrides the public String toString() method. Through this method returns a string where it describes about the type of Exception. Example-4 public class Demo { public static void main(String argts[]) { int x=9; try{ x=x/0; }catch(ArithmeticException e) { System.out.println("inside catch block"+e); } } Output: inside catch block java.lang.ArithmeticException: / by zero

Multiple catch blocks

211

In some special case one try block can have multiple catch block. In other words more than one Exception can be generated within a single line of code, so the programmer required multiple catch statement for one try block. To handle such situations multiple catch blocks are required. When multiple Exception is generated, each catch statement inspected in order. Example-5 public class Demo { public static void main(String argts[]) { try{ int len=argts.length; System.out.println(Length=+len); int con=5/len; int mak[]={222}; mak[42]=1000; }catch(ArithmeticException e) { System.out.println("inside catch block"+e); } catch(ArrayIndexOutOfBoundsException aoe) { System.out.println(Inside Catch Block+aoe); } } } Output:-

This program will generate an ArithmeticException if in the command line the programmer not passes any arguments, so the length is equal to zero. But if the programmer passes any command line arguments then the length is not equal to zero and the program not generates any ArithmeticException. But program must generate an ArrayIndexOutOfBoundsException, since the int array mak has a length of 1, yet the program attempts to assign a value to mak[42].

212

Parent class reference variable can hold the object of child class. So the exception thrown by a try block can be caught by its parent class reference. When one try block having multiple catch statement then Exception of sub class must placed before Exception of super class. It is a restriction otherwise it generates compile time error. Example-6 import java.io.*; class New extends Exception { } public class Multi { public static void main(String args[])throws IOException { int a=10; int b=args.length; try{ System.out.println(a/b) ; BufferedReader br=new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter A Number"); int i=Integer.parseInt(br.readLine()); throw new New(); }catch(ArithmeticException ae) { ae.printStackTrace(); } catch(NumberFormatException ne) { System.out.println(ne.getMessage()); } catch(Exception n) { System.out.println("Caught"); } } } Use of throw statement So far we have caught the exceptions generated by JVM. Java provides

213

support to generate exception manually by the programmer just by instantiating the appropriate exception class. You have to use the throw statement to thyrow the exception. The general form will be throw instance_of_Throwable_or_its_child_class; You can throw the object of Throwable or the object of the child class of Throwable. The execution stops when JVM encounters the throw statement & controls jumps to the catch block. The codes below the throw statement are never going to be executed. Example-7 public class Demo { public static void main(String argts[]) { ArithmeticException a=new ArithmeticException(); try{ throw a; System.out.println("inside try block"); }catch(ArithmeticException e) { System.out.println("inside catch block"); } } } Output: inside catch block Example-8 class X extends RuntimeException { void show() { throw new X(); } } public class Demo { public static void main(String argts[])

214

{ X a=new X(); try{ a.show(); }catch(RuntimeException e) { System.out.println("inside catch block"); } } } Output: inside catch block Explanation: this program represents another way to generate exception inside a method. class X extends the RuntimeException. This class has show method which has a statement throw new X();. When you want to call the method, it should be inside try block. Rests of the things are straight forward. Nested try block: Java supports nested try block. Nested try block means one try block defined within another try block. The context of the Exception is stored in stack, when the try statement executed each and every time. If the inner try block has no catch block or has a catch block that is not able to handle the Exception, then stack is unwound and the next try statements catch block are inspected to handle the Exception of the Inner try block. This process will continue unless until one of the catch statements matched, or until all of the nested try blocks are exhausted. If no catch statement matches, then at the runtime the Java run-time system will handle the Exception. The throws keyword If a method generate an Exception and not handle the exception by catch block, then the programmer must specify throws keyword so that the caller of the method can guard its code against that exception. If method generate a Checked Exception and the programmer does not want to handle the checked exception then the programmer should throw them out by using throws keyword otherwise an error flagged by java compiler. But in case of unchecked exception if the programmer does not want to handle the

215

unchecked exception then the programmer should not throw them out by using throws keyword. Example-9 public class Excep1 { public static void main(String args[]) { try{ amethod(); }catch(Exception e) { System.out.println("Exception"); } System.out.println("Finished"); } public static void amethod()throws Exception { try{ throw new Exception(); }finally{ System.out.println("Finally") ; } } } Output:-

Example-10 public class Excep2 { public static void main(String afg[]) { try{ show();

216

System.out.println("A"); }catch(RuntimeException re) { System.out.println("B"); } catch(Exception e) { System.out.println("C"); } finally{ System.out.println("D"); } System.out.println("E"); } public static void show() { throw new RuntimeException(); } } Output:-

If any statement generates exception, the remaining statement in the try block is skipped and exception is jumped to catch block. Every try block must be followed by at least one catch block. Both try and catch block have more than one statement. Catch statement work like a method statement. Catch statement is passed a single parameter, which is reference to the exception object thrown by try block. If catch parameter is matches with the type of exception object then exception is caught and statement of catch block will be executed otherwise default exception handle will be executed otherwise default exception to terminate.

   

217

User-defined Exception Customized exceptions are necessary to handle abnormal conditions of applications created by the user. The advantage of creating such an exception class is that, according to situations user generate user defined exception. It also possible to set any condition or value to a variable and generate user defined exception. Example-11 import java.io.*; class Excep1 extends Exception { private int a; Excep1(int b) { a=b; } public String toString() { return "Excep1[" +a+ "]" ; } } public class User { public int x; final int k=5; void getInt() { try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)) ; System.out.println("Enter A Number in between 1-10"); String line; while((line=br.readLine())!=null) { x=Integer.parseInt(line); if(x==5) {

218

System.out.println("Congrats You Will Generate an Exception"); throw new Excep1(x); }else System.out.println("Try Again") ; continue; } }catch(Excep1 e1) { System.out.println("Generated Exception : "+e1); } catch(NumberFormatException ne) { System.out.println("Please Enter A Number"); } catch(IOException ie) { } } public static void main(String args[]) { User u=new User(); u.getInt(); } } Output:-

Exception Restriction:-

219

When we override a method, we can throw only the exceptions that have been specified in the base-class method. This is very useful restriction since it means that the code which works with the base class will automatically work with any object derived from the base class, including exceptions. It is useful to realize that, although exception specifications are enforced by the compiler during inheritance, the exception specifications are not part of the type of a method.

220

Chapter-12 Package It consists of classes and interfaces grouped together according to functionality. Package contains a set of classes in order to ensure that class names are unique. Package is the container for classes or interfaces. Packages contain classes and interfaces in a hierarchical order and are imported when the programmer wants to access classes or interface within it. Advantage:     Classes contained in the packages of other program can be easily reused. Two classes in two different packages can have the same name. Packages provide a way to hide classes. Packages provide a way for separating design from coding.

Classpath variable: When a class is defined without package declaration, then it is defined that the class is included in javas default package. If the programmer not declared the package name then the class files are stored in the current working directory so by default the current working directory included in the classpath variable. At the runtime the java interpreter search the .class files in the path specified in the classpath environmental variable. In case of creating a user defined package ensure that the root directory of the package is included in the classpath variable. When programmer develops a package program, program follow three steps: y y y Package Declaration Import statement Class Definition

The format of package declaration is quite simple. Keyword package followed by package name. Package name must be same as the directory name. When class files are created, they must be placed in a directory hierarchy that reflects the package name.

221

package p1; import is a keyword in java that is used to access the class files of the user defined package and pre defined package. import p1.*; import java.util.*;
Naming convention:    Package begins with lower case letter. Every package name must be unique, to best use of package. To ensure uniqueness in naming packages, domain name as used as prefix to package name.

Access protection: Java having four different types of access specifiers namely private, no access, protected and public. In java if the method and variable declared without any access specifier then by default members are no access and the methods and variables are accessed to all classes within the same package.

Members Same class Within the same package class is inherited Within the same package class is not inherited Outside the package class is inherited Outside the package class is not inherited

private Yes No

no access Yes Yes

protected Yes Yes

public Yes Yes

No

Yes

Yes

Yes

No

No

Yes

Yes

No

No

No

Yes

222

If the members are private then the data is only accessed within the class but it is not accessed outside the class. If the members are no access then the data is accessed within the class and accessed within the same package either the class is inherited or not. If the members are protected then the data is accessed within the class and accessed within the package the package either the class is inherited or not but outside the package only when the class is inherited. If the members are public then the data is freely access within the package and outside the package either through inheritance or not.

Program:y y Create a directory named as pack Open a file Name.java

223

package pack; class Name { String n; String setName(String name) { n=name; return n; } } In Name class the class, method and variable are declared without using any access specifier that means the members are only accessed within the same package pack. y In the same package open Roll.java

package pack; public class Roll { protected int roll; protected int getRoll(int r) { roll=r; Name n1=new Name(); System.out.println("Name Is "+n1.setName("Amit")); return roll; } } As the Roll class members are protected then it accessed outside the package through inheritance. y y Inside the pack directory creates a subdirectory named as subpack Inside the subpack directory creates a file named as Address.java

package pack.subpack; import pack.Roll; public class Address extends Roll { public String address; public String getAddress(String a) {

224

address=a; Address a1=new Address(); System.out.println("Roll Number Is "+a1.getRoll(7)); return address; } } In this class the members are public so it is freely access within the package and outside the package either through inheritance or not. Here c:\java is the root directory. In the root directory write the main application PackDemo.java. y In c:\java open PackDemo.java

import pack.subpack.Address; public class PackDemo { public static void main(String args[]) { Address a1=new Address(); System.out.println("Address Is "+a1.getAddress("Nayabazar, Cuttack")); } } Output:

225

Chapter-13 JAR File

Java Archive(JAR) files provides a standard mechanism to compress and package a set of files for distribution to users. JAR is a platform independent file format that aggregates many files into single unit. Programmer creates java archive file format for compress number of class files and improve the download performance of applet and application. In JAR programmer can store not only .class files but store different types of file. JAR stands for the Java Archive. This file format helps the programmer to reduce the size of the file and collect many file in one by compressing these files. The following files may be packed into one JAR file: y y y y y y The Beans Any Supporting class files. Text and HTML class files that provides help to the user. Static Images. Audio and video clips. Configuration data.

In java some commands are used to perform main operations for the jar file. These commands are performed in java by using jar tool.

Option C f m

Description Create an Archive The first element in files is the name of the archive to be created. The second element in the file is the name of the manifest file. Tabulate the content of the archive. Provide verbose output Extract files from the archive. Dont use Compression Dont create a manifest file

T V X O M

226

The jar utility provided with jdk is to create and manage the JAR files. Step-1 Write the source code import java.io.*; public class Sort { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter First String"); String first=br.readLine(); System.out.println("Enter Second String"); String second=br.readLine(); int l1=first.length(); int l2=second.length(); int count1=0,count2=0,i; for(int c=0;c<128;c++) { for(i=0;i<l1-1;i++) { if((byte)c==(byte)first.charAt(i)) {

227

count1++; } } for(i=0;i<l2-1;i++) { if((byte)c==(byte)second.charAt(i)) { count2++; } } if(count1>count2) { for(i=1;i<=count1;i++) { System.out.print((char)c); } }else{ for(i=1;i<=count2;i++) { System.out.print((char)c); } } } }

228

Step-2 Create the manifest file named as Sort.mft Name: Sort.class Java-Bean: True Step-3

Create the jar file.

Tabulating the contents of the jar file

Extracting Files from a jar file

229

Manifest File This is an ordinary text file that can be viewed with an editor. This file consists Manifest-Version: 1.0 Name: Sort.class Java-Bean: True The first line of the manifest file provides version information. The other lines provide information about each of the element in the JAR file. One of the most important items to note in this file is Java-Bean: True.

230

Chapter-14

String
In java strings are sequence of Unicode characters. String is a predefined class present in java.lang package. String is a final class that means String class cannot be inherited. String is the child class of Object class and implements the CharSequence, Comparable, Serializable interfaces. Each quoted string is an object of the String class. So it is created inside heap. Therefore s1 must have a hash code value. Lets check it out class Demo { public static void main(String args[]) { String s1="Java"; System.out.println(s1.hashCode()); } } Output: 71355168 Yes, s1 is a reference of string class. But, how object is created inside without new operator!! When JVM encounters String s1=Java; such statement it implicitly invoke new operator to allocate memory from heap. Java has maintained most of the C/C++ syntax & that is the reason why java provides this facility to declare a string. String objects are created in side heap in string pool. Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. If you change the content of the original String object then an entirely new String object is created. A java.lang.String class is final which implies no class can extend it.

231

Most frequently used Constructors of String class: y No argument constructor String s=new String() this constructor is used to create an empty string. String(char chars[ ]) This constructor can be used to create a string from array of characters

class Demo { public static void main(String args[]) { char mak[]={'a','b','c'}; String s1=new String(mak); System.out.println(s1); } } Output: abc y String(char[] c, int start, int length);

The parameter start specifies the index from which the charcters are used to create the String object, and length specifies the number of characters to be used from the character indicated by start. class Demo { public static void main(String args[]) { char mak[]={'a','b','c','d','e','f','g'}; String s1=new String(mak,3,3); System.out.println(s1); } }

232

Output is def y String(String stringObj); class Demo { public static void main(String args[]) { String s1=new String("Hello,Java!"); System.out.println(s1); } } Output is Hello,Java! class Demo { public static void main(String args[]) { String s2="Hello World!"; String s1=new String(s2); System.out.println(s1); } } Output is Hello World! In java Strings are set unicode character sequence. Unicode characters take 2 byte from memory. If the programmer is assured that the user characters in a string are only from keyboard i.e. only ASCII character set then it is advisable to use byte data type rather than char. The constructors are String(byte b[ ]) String(byte b[],int start, int length) The parameter b represents the array of bytes. The parameter start specifies the index from which the characters are used to create the String object, and length specifies the number of characters to be used from the character indicated by start i.e. the range. class SubStringConstructiom {

233

public static void main(String args[]) { byte ascii[] = {65, 66, 67, 68, 69, 70 }; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); System.out.println(s2); } } This program generates the following output: ABCDEF CDE Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters. However, most of the time, you will want to use the default encoding. Behavior of == operator in case of string The == operator is used to determine whether the content of two variables are same or different. But when == used in case of string references some abnormal behavior is shown. See the program below. class Demo { public static void main(String args[]) { String s1="java"; String s2="java"; if(s1==s2) System.out.println("Surprised!!!"); } } Output Surprised!!! S1 is reference of string class. S1=java; statement instructs the JVM to call the constructor of string class through new operator implicitly. S1 created inside stack & memory is allocated to it from heap. Similarly s2 is

234

created in side stack & JVM implicitly calls the constructor to allocate memory to it from heap. Since s1 & s2 are two different reference variables therefore it is quite oblivious that two separate chunk of memory is allocated & their starting address has to be stored in s1 & s2 respectively. So, s1 cannot be equal to s2. Concept is absolutely correct. But, in case of string object when the constructor is called implicitly, JVM behaves in different way. Strings are immutable i.e. content of a string object can not be altered in a given reference. So when JVM implicitly calls the string class constructor, first JVM searches the heap area whether any memory chunk of string object that has the same character set in same sequence available or not. If such a memory chunk is available then, instead of allocating new memory chunk it uses the existing one. In the above program, s1 & s2 has the same character set in the same sequence. JVM first allocates memory to s1 from heap say 1000 as shown in the figure. When s2 is encountered, JVM searches the heap to find whether same character set in same sequence present or not, & it gets. So instead of allocating new memory chunk, JVM assigns the starting address of the memory chunk that has been allocated to s1, allocates to s2. So s2 also contains 1000. when programmer explicitly calls the constructor through new operator a new separate memory chunk is allocated. So s1 is now not equal to s2 class Demo { public static void main(String args[]) { String s1="java"; String s2=new String("java"); if(s1==s2) System.out.println("hello"); } } Output: no output

235

A closer look at equals() & hashCode() method In case of String class, the equals() method & the hashCode() has been over ridden. The hashCode() method returns the same unique integral value for any two objects that compared as equal and a different integral value for any two objects that is not compared equal & equality is inspected by the equals() method. Except String class in all cases equal method checks the content of reference variable, if the content is same then it returns true. class X { int x; } class Demo { public static void main(String argts[]) { X d1=new X(); d1.x=9; X d2=new X(); d2.x=9; if(d1.equals(d2)) System.out.println("Hello! We are same."); else System.out.println("No, We are different."); if(d1==d2) System.out.println("Same same dear."); else System.out.println("Believe dear we are different."); } }

Output: No, We are different.

236

Believe dear we are different.

In the above program, JVM has allocated two different chunk of memory to d1 & d2. Since d1 & d2 both are reference variables, they are going to contain the starting address of the memory chunk allocated to them. So the content of d1 & d2 is entirely different. == operator & equals method checks the content of reference variables & since the content is different output is quite obvious. But, the story is different in case of String objects. Check this program class Demo { public static void main(String argts[]) { String d1=new String("Java"); String d2=new String("Java"); if(d1.equals(d2)) System.out.println("Hello! We are same."); else System.out.println("No, We are different."); if(d1==d2) System.out.println("Same same dear."); else System.out.println("Believe dear we are different."); } } Output: Hello! We are same. Believe dear we are different. Foxed dear!!! Why different output? Let me explain the program from the very beginning. d1 & d2 are the reference variables of String class. I have explicitly invoked the constructor of string class through new operator. JVM allocates memory from heap to d1 & d2. Definitely d1 & d2 have different address. So d1 is not equal to d2. ==

237

operator checks the content of d1 & d2, since the are different out put is as usual. But, in case of equals method, as I have said behave in a different way in case of String class. equls() method checks whether the character sequence & character case (upper or lower) is same or not while invoked by string objects. If the character sequence & character case is same then equals method returns boolean true else false. The hashCode() method returns the same integral value if the equals() method returns boolean true value for two objects. See the program below class Demo { public static void main(String argts[]) { String d1=new String("Java"); String d2=new String("Java"); if(d1.equals(d2)) System.out.println("Hello! We are same."); else System.out.println("No, We are different."); if(d1==d2) System.out.println("Same same dear."); else System.out.println("Believe dear we are different."); System.out.println(d1.hashCode()); System.out.println(d2.hashCode()); } } Out put: Hello! We are same. Believe dear we are different. 2301506 2301506 See since the character set & character sequence is same in both String objects, equals() method returns the same Boolean true value. There fore hashCode() method returns same value for two objects. All these stuffs are only because Strings are immutable.

238

Some Important Methods of String class with example:y public int length() this method is used to determine the length of the string. class Demo{ public static void main(String args[]) { String s1="Hello world"; int i=s1.length(); System.out.println(i); }} Output: 11 public char charAt(int index) this method is used to extract a specified character from the string by the particular index supplied by the programmer. The index supplied must be within the length of the string. class Demo{ public static void main(String args[]) { String s1="Hello world"; char ch=s1.charAt(2); System.out.println(ch); }} Output: l Suppose the programmer supplies the index which is greater than the length of the string then string out of bound exception will be generated. For example class Demo{ public static void main(String args[]) { String s1="Hello world"; char ch=s1.charAt(12); System.out.println(ch); }} Upon execution this program throws string out of bound index exception. public void getChars(int start,int end,char c[], int index_1) this method is used to copy the set of Unicode characters from the string from the index supplied through the start variable up to the index represented by end variable in to a character array c. the last variable index_1 represents the index number of the array from which the characters copied from the string has to be stored.

239

class Demo{ public static void main(String args[]) { String s1="Hello world"; char ch[]=new char[5]; s1.getChars(1,3,ch,2); for(int i=0;i<5;i++) System.out.println(ch[i]); }} Output:

e l

public byte[] getBytes() this method is used to to convert a unicode string in to to an array of bytes class Demo{ public static void main(String args[]) { String s1="Hello"; int i=s1.length(); byte b[]=new byte[i]; b=s1.getBytes(); for(int j=0;j<i;j++) System.out.println(b[j]); }} Output: 72 101 108 108 111 public boolean equalsIgnoreCase(String s) this method is used to compare two strings ignoring the upper or lower case. class Demo{ public static void main(String args[]) { String s1="Hello world"; String s2="hello world"; boolean b=s1.equalsIgnoreCase(s2); y

240

System.out.println(b); }} Output:true y public int compareTo(String sobj); this method is used to compare two strings. Lets have an example how this method behaves. class Demo { public static void main(String[]args) { String s1="Java"; String s2="C++"; int i=s2.compareTo(s1); System.out.println(i); } } Output: -7 Ok fine now check these two programs class Demo { public static void main(String[]args) { String s1="Java"; String s2="C++"; int i=s2.compareTo(s2); System.out.println(i); } } Output: 0 class Demo { public static void main(String[]args) { String s1="Java"; String s2="C++"; int i=s1.compareTo(s2); System.out.println(i); } } Output:7 Conclusion is that i<0 means invoking string is less than the string taken as argument. i=0 both the string object are same. i>0 means string is greater than the string taken as argument.

241

Actually how the comparison is made only through the length. No absolutely not. Comparision is done through dictionary order & upper case letter comes first. See the example below class Demo { public static void main(String[]args) { String s1="Java"; String s2="java"; int i=s1.compareTo(s2); System.out.println(i); } } Output: -32

public boolean startsWith(String prefixValue,int index) checks whether the string begins with the specified prefixValue from specified index class Demo { public static void main(String[]args) { String s1="Java is cool"; boolean i=s1.startsWith("cool",8); System.out.println(i); } } Output: true public boolean startsWith(String prefixValue) checks if the string starts with the specified prefixVlaue. So you can feel that startsWith method of string class is overloaded. class Demo { public static void main(String[]args) { String s1="Java is cool"; boolean i=s1.startsWith("Java"); System.out.println(i); } } Output true public boolean endsWith(String suffixValue)

242

checks whether the string ends with the specified suffixVlaue or y not. public int indexOf(int ch) this method is used to return the place value of the specified character in the string. class Demo{ public static void main(String args[]) { String s1="Hello world"; int b=s1.indexOf('w'); System.out.println(b); }} Output:6 public int indexOf(int ch,int fromIndex) this method returns the place value of the specified character with in the string. If the string does not have the character with in the string then -1 is returned. This checking is done with respect to the integer value fromIndex. class Demo{ public static void main(String args[]) { String s1="Hello world"; int b=s1.indexOf('l',4); System.out.println(b); }} Output 9 class Demo{ public static void main(String args[]) { String s1="Hello world"; int b=s1.indexOf('l',4); System.out.println(b); }} Output:2 class Demo{ public static void main(String args[]) { String s1="Hello world";

243

int b=s1.indexOf('H',4); System.out.println(b); }} Output: -1 public int lastIndexOf(int ch) public String concat(String str) adds the string send in the argument to at the end of the string through which it is invoked. class Demo{ public static void main(String args[]) { String s1=" Hello"; String s2=s1.concat(" World"); System.out.println(s2); }} Output: Hello World

public String toLowerCase() this method is used to convert all the characters present in the string to lower case & assigns it to a new string object. class Demo{ public static void main(String args[]) { String s1="Hello World"; String s2=s1.toLowerCase(); System.out.println(s2); }} Output: hello world public String toUpperCase() this method is used to convert all the characters present in the string to upper case & assigns it to a new string object.

public String trim() this method is used to eliminate the white space from the beginning of the string. class Demo{ public static void main(String args[]) { String s1=" Hello World";

244

String s2=s1.trim(); System.out.println(s1); System.out.println(s2); }} Output: Hello World Hello World y public char[] toCharArray() this method is used to convert the string to character array. class Demo{ public static void main(String args[]) { String s1=" HELLO WORLD"; int i=s1.length(); char ch[]=new char[i]; ch=s1.toCharArray(); for(int j=0;j<i;j++) System.out.println(ch[j]); }} Output: H E L L O W O R L D

245

Chapter-15

StringBuffer
StringBuffer is a class present in java.lang package. StringBuffer is a final class. StringBuffer class cannot be inherited as it is a final class. StringBuffer class in java is a sub class of java.lang.Object class & implements the interfaces CharSequence, Serializable. An instance of StringBuffer class represents a String that can be dynamically modified. String class objects are immutable where as a StringBuffer class objects are mutable. StringBuffer object is like a String, but can be changed or modified. StringBuffer object is auto flushed. Constructor of StringBuffer y y y StringBuffer() This constructs an empty StringBuffer StringBuffer(int capacity) This constructs an empty StringBuffer with the specified initial capacity. StringBuffer(String s) This constructs a StringBuffer that initially contains the special String.

Methods of StringBuffer y y public synchronized int length() : returns the length of the StringBuffer. public synchronized int capacity() : returns the capacity of the StringBuffer. A StringBuffer has a capacity, which is the longest String it can represent without needing to allocate more memory. public synchronized void setLength(int length) :This method is used to set the length of the StringBuffer. public synchronized void ensureCapacity(int capacity) :This method is used to set the capacity of the StringBuffer. public synchronized char charAt(int index) :This method returns a character from the StringBuffer. public synchronized void getChars(int stat,int end,char c[],int index) :This method extract more than one character from the StringBuffer.

y y y y

246

y y

y y y y

y y y y y

public synchronized void setCharAt(int index, char ch) :This method set a character in the StringBuffer. public synchronized StringBuffer append(Object o) :This method calls toString() on Object o and append the result to the current StringBuffer. public synchronized StringBuffer append(String s) :This method append a String in the StringBuffer. public synchronized StringBuffer append(StringBuffer sb) : public synchronized StringBuffer append(char c) : public synchronized StringBuffer delete(int index, int length) : This method is used to delete more than one character from the StringBuffer. public synchronized StringBuffer deleteCharAt(int index) : This method is used to extract a character from the StringBuffer. public synchronized StringBuffer replace(int index, int length, String s) :This method is used to replace a String in the StringBuffer. public synchronized StringBuffer insert(int index, String s) :This method is used to insert a String in the StringBuffer. public synchronized StringBuffer reverse() :This method is used to reverse the StringBuffer. public String toString() :This method is used to convert the String to StringBuffer.

247

Chapter-16

Wrapper class:
Each java primitive data types has a corresponding wrapper class. When we create an object of the wrapper class, it contains a field and in this field primitive data types are stored. Primitive data types boolean byte short char int float long double Wrapper class Boolean Byte Short Character Integer Float Long Double

Why We Require Wrapper Class?  Vector, ArrayList, LinkedList classes present in java.util package cannot handle primitive data type like int, char, float etc. hence primitive may be converted into object type using Wrapper classes present in java.lang package.  Wrapper class converts primitive data types into objects. Character Character class object is a wraps around a char. The Constructor is Character (char ch) To obtain the char value contained in the Character object is Methods: public static Character valueOf(char c): this method converts a single character into Character class object. public char charValue( ): This method is useful to convert character class object into primitive char value. public int hashCode(): returns the hash value of Character class Object.

248

public static String toString(char c): This method coverts char data types into String. Boolean Boolean is wrapper around boolean value. The constructor of the Boolean class is overloaded. Boolean(boolean b) Boolean(String s) If the s contains the String true (in uppercase and in lowercase) then the Boolean object hold true values. Otherwise the Boolean object will hold false vales. To obtain a boolean value contained by the Boolean object is boolean booleanValue() Methods: public static boolean parseBoolean(String s): converts String to boolean public boolean booleanValue() :Extract boolean value from the Boolean Object. public static String toString(boolean b) : This method coverts boolean data types into String. public int hashCode() : returns the hash value of Character class Object. public static Boolean valueOf(String s) :This method convert a String that contains a boolean value into Boolean object. public static Boolean valueOf(boolean b): This method converts a boolean value into Boolean object.

Number Number is an abstract class whose subclass is Byte, Short, Integer, Float, Long and Double. The method of the Number class is override in the child classes. Methods of the Number class are:

249

byte byteValue() short shortValue() int intValue() float floatValue() long longValue() double doubleValue()

Byte class: Byte class wraps a value of the primitive type byte in an object. The Byte class object contains byte value.

Constructor:Constructor of Byte class is Overloaded y Byte(byte b)

Syntax:Byte b1=new Byte ((byte) 12); y Byte(String s)

Syntax:Byte b2=new Byte (45); Byte b3=new Byte(Java);//when we extract the value from the b3 object then the program is terminated at runtime by throwing an Exception NumberFormatException. Methods: public static byte parseByte(String s): Converts String to byte datatype. public static Byte valueOf(String s): Converts String to Bye class object. public static Byte valueOf(byte b): Converts byte value to Byte class object. public int hashCode(): returns the hash value of Byte class Object public static String toString(byte b): Converts byte value to String

250

Short class:Short class wraps a value of the primitive type short in an object. The Short class object contains short value. Constructor:Constructor of Short class is Overloaded y Short(short s)

Syntax:Short s1=new Short ((short) 12); y Short(String s)

Syntax:Short s2=new Short (45); Short s3=new Short (Java);//when we extract the value from the s3 object then the program is terminated at runtime by throwing an Exception NumberFormatException. Methods: public static short parseShort(String s): converts String to short data types. public static String toString(short s): Converts short data types to String. public static Short valueOf(String s): Converts String to Short class object. public static Short valueOf(short s): converts short data types to Short class Object. public int hashCode(): Returns the hash value of Short class Object. Integer class:Integer class wraps a value of the primitive type int in an object. The Integer class object contains int value. Constructor:Constructor of Integer class is Overloaded y Integer(int b)

251

Syntax:Integer i1=new Integer(12); y Integer(String s)

Syntax:Integer i2=new Integer (45); Integer i3=new Integer (Java);//when we extract the value from the i3 object then the program is terminated at runtime by throwing an Exception NumberFormatException. Methods: public static int parseInt(String s): converts String to int data type. public static String toString(int s): converts int dada type into String. public static Integer valueOf(String s): Converts String class object into Integer class Object. public static Integer valueOf(int s): converts int data type into Integer class object. public int hashCode(): Returns the hash value of Integer class Object.

Long class:Long class wraps a value of the primitive type long in an object. The Long class object contains long value. Constructor:Constructor of Long class is Overloaded y Long(long l) Syntax:Long l1=new Long (12); y Long(String s)

Syntax:Long l2=new Long(45);

252

Long l3=new Long (Java);//when we extract the value from the l3 object then the program is terminated at runtime by throwing an Exception NumberFormatException. Methods: public static long parseLong(String s): Convert String class object into long data types. public static String toString(long s): Converts long data types into String. public static Long valueOf(String s): Converts String class Object into Long class Object. public static Long valueOf(short s): Converts long data types into Long class object. public int hashCode(): Returns the hash value of Long class Object.

Float class:Float class wraps a value of the primitive type float in an object. The Float class object contains float value. Constructor:Constructor of Float class is Overloaded y Float(float b)

Syntax: Float f1=new Float ((float) 12.5); y Float(String s)

Syntax:Float f2=new Float (45); Float f3=new Float(Java);//when we extract the value from the f3 object then the program is terminated at runtime by throwing an Exception NumberFormatException.

253

Method: public static Float parseFloat(String s): Converts String class object to float data type. public static String toString(float s): Converts float data types into String. public static Float valueOf(String s): Converts String class object into Float class Object. public static Float valueOf(float s): Converts float data types into Float class Object. public int hashCode(): Returns the hash value of Float class Object.

Double class:-

Double class wraps a value of the primitive type double in an object. The Double class object contains double value. Constructor:-

Constructor of Double class is Overloaded y Double(double b)

Syntax:-

Double s1=new Double (23.09); y Double(String s)

Syntax:-

Double d2=new Double (5.9); Double d3=new Double (Java);//when we extract the value from the d3 object then the program is terminated at runtime by throwing an Exception NumberFormatException.

254

Method:

public static double parseDouble(String s): Converts String class object to double data type. public static String toString(double s): Converts double data types into String. public static Double valueOf(String s): Converts String class object into Double class Object. public static Double valueOf(double s): Converts double data types into Double class object. public int hashCode(): Returns the hash value of Double class object.

Example-1 public class Wrap1 { public static void main(String rs[]) { String s="22"; int i=Integer.parseInt(s); i++; System.out.println(i); double d=Double.parseDouble(s); d+=5; System.out.println(d); short s1=Short.parseShort(s); s1+=10; System.out.println(s1);

255

s=Integer.toString(i); s+=1; System.out.println(s); s=Double.toString(d); s+=12; System.out.println(s); s=Short.toString(s1); s+=2; System.out.println(s); } }

Auto boxing and Auto unboxing: J2SE 5 supports auto boxing process by which a primitive type is automatically encapsulated into its equivalent type wrapper class object. There is no need to explicitly construct a wrapper class object. This technique is popularly known as autoboxing in java. Whereas unboxing is required to convert Wrapper class Object into subsequent primitive data types. In general, autoboxing and unboxing take place whenever a conversion into an object or from an object is required.

256

Example-2 public class Auto { Boolean b1=new Boolean("yes"); boolean b=b1; void show() { if(b){ System.out.println("You Need Money");; }else{ System.out.println("You Need Knowledge"); } } public static void main(String args[]) { Auto a=new Auto(); a.show(); } } Output:

257

Chapter-17

Taking Input from keyboard

In java you can take the input from keyboard in three ways.

1st: Through command line In any java program the signature of main method is as follows public static void main(String args[]) Here args is an array of strings. This string array is capable of storing various string elements that is passed to the program from command line during the execution of java program. Lets have an example Demo1.java class Demo1{ public static void main(String args[]) { System.out.println(args[0]); } } Compile this program by javac Demo1.java During the execution phase you are going to provide the command line argument which is of string type. This can be done by java Demo1 Hello & the out put will be Hello. In java the zeroth argument is the string supplied by the user as in this case Hello is the zeroth argument. But, always remember that the arguments or the input supplied to the java program

258

from the command prompt are always in the form of string. So you have to use different method & techniques to get it converted to desired type. And one thing strings are objects in java. In command line 1st argument 0th argument is separated by space. To access the 1st argument you to use args[1] & so on. e.g. Demo2.java class Demo2 { public static void main (String args[]) { String s=args[0]+args[1]; System.out.println(s); } }

Input java Demo hello world Output helloworld Whatever the argument we pass from the command line are in String format as every arguments are stored in array of String argument. When we extract the element then we extract the element through the array indexes. If the array index cross the range then the program is terminated at the runtime by generating ArrayIndexOutOfBoundsException. e.g. public class Demo3 { public static void main(String args[])

259

{ int i=0; while(i++<args.length) { System.out.println(args[i]); } } } Compile the application by javac Demo3.java Execute it by java Demo3 A B C Output B C Program is terminated by throwing java.lang.ArrayIndexOutOfBoundsException.

2nd: by the use of readLine() method The readLine () method is available in the java.io package. So you have to import that package. The syntax of the method is public String readLine()throws IOException { } This method present in BufferedReader and DataInputStream class. Both the class present in java.io package. As the method return type is String then the given input is in the string format. But the programmer is bound to

260

handle IOException as the method throws IOException. Lets have an example: import java.io.*; class Demo{ public static void main(String args[]) throws IOException { InputStreamReader is=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(is); System.out.println(Enter The Data From Keyboard); Stsring s=br.readLine(); System.out.println(Output Is +s); } }

Compile the application by javac Demo.java Execute it by java Demo Output is: Enter The Data From Keyboard Hello World Output Is Hello World

Here notice the additional phrase attached to main method. throws IOException this phrase is added to main method because signature of readLine () method has throws IOException. Till now remember that when ever you are going use a method which has signature of throwing any

261

Exception then, with in which such a method is called, that method must have throws Exception_Object.

Another way is that invoke the method readLine () inside a try catch block. import java.io.*; class Demo{ public static void main(String args[]) {

InputStreamReader is=new InputStreamReader (System.in); BufferedReader br=new BufferedReader(is); String s; try{ s=br.readLine(); }catch(IOException e) { } System.out.println(s); } Input: Hello World Output: Hello World System.in is the keyboard. InputStreamReader behaves like a channel connected to it. readLine() method reads the data & store it in the string s.

3rd(By using Scanner class) Scanner is a class present in java.util package. Scanner reads formatted input and converts it into binary form. Scanner class is used to read all types of numeric values, String and other types of data from any input sources.

262

Scanner can be used to read input from the console, from a file, from a String or any source that implements Readable interface.

Constructor: FileReader fr=new FileReader (a.txt); Scanner s1=new Scanner (fr);

Scanner s2=new Scanner (System.in);

String s=Interface Software; Scanner s3=new Scanner(s);

Method boolean hasNext()

Description Returns true if another token of any type is available to be read. Returns true if a boolean value is available to be read. Returns true if a byte available to be read. value is

boolean hasNextBoolean()

boolean hasNextByte()

boolean hasNextShort()

Returns true if a short value is available to be read. Returns true if a int value is available to be read. Returns true if a float available to be read. Returns true if a available to be read. long value is

boolean hasNextInt()

boolean hasNextFloat()

boolean hasNextLong()

value

is

263

boolean hasNextDouble()

Returns true if a double value is available to be read. Returns true if a line of input is available. Returns the next token of any type from the input source. Returns the next token as a boolean value. Returns the next token as a byte value. Returns the next token as a short value. Returns the value. next token as a int

boolean hasNextLine()

String next()

boolean nextBoolean()

byte nextByte()

short nextShort()

int nextInt()

long nextLong()

Returns the next token as a long value. Returns the next token as a float value. Returns the next token as a double value. Returns the next line of input as a String.

float netFloat()

double nextDouble()

String nextLine()

Procedure of using Scanner y y y Determines if a specific type of input is available by calling one of Scanners hasNextXXX method. If input is available, read it by calling one of Scanners next() method. Repeat the process until the input is exhausted.

How to take an integer from key board

264

import java.util.*; class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println(Enter A Number); int i=sc.nextInt(); System.out.println(Output Is :+i); sc.close(); } } Enter A Number 5 Output Is :5 How to take a float variable import java.util.*; class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println(Enter A Floating point value); float i=sc.nextFloat(); System.out.println(Output Is: +i); sc.close(); } } Enter A Floating point value 10.123 Output Is: 10.123 To use the Scanner class & the methods those belongs to scanner class you have to import the java.util package. System.in represents keyboard. After

265

taking the input you have to close the scanner by the invocation of close method. To take boolean value as input import java.util.*; class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println(Enter a boolean value); boolean i=sc.nextBoolean(); System.out.println(Output Is :+i); sc.close(); } } Enter a boolean value true Output Is :true

To take byte from key board import java.util.*;

class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println(Enter A Byte); byte i=sc.nextByte(); System.out.println(Output Is :+i); sc.close(); } } Enter A Byte 23 Output Is :23

266

To read a string from keyboard import java.util.*; class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println(Enter The Text); String i=sc.nextLine(); System.out.println(Output Is +i); sc.close(); } } Enter The Text hello world Output:hello world

267

Chapter-18

JAVA NATIVE INTRFACE Overview: In JAVA native is a modifier. The native modifier can refer only to methods. Like the abstract keyword, native indicates that the body of a method is to be found elsewhere. In the case of the abstract methods, the body is in a subclass but in case of native methods, the body lies entirely outside the java virtual machine, in a library. People who port java to new platform implement extensive native code to support GUI components, network communication and a broad range of platform specific functionalities .However it is rare for applet and application programmers to use the native codes. JNI never imposes any restriction to the JVM. This is one of the vital importance of JNI. Therefore, Java VM vendors can add support for the JNI without affecting other parts of the VM. Now lets discuss what are the situations when java programmer needs the native method. 1: If client requires platform dependent features in java but the standard java class library supports the platform independent feature. In this situation programmer required JNI for supporting platform dependent feature in java. 2: When the programmer already develops the code in C and C++ and wish to make it accessible to Java code then the programmer must required JNI. 3: When the programmer wants to develop small portion of time-critical code by using a lower-level language such as assembly then the programmer use JNI. By programming through the JNI, Programmer use native methods to:
y y y y y

Create, inspect, and update Java objects. Call Java methods. catch and throw Exception. Load classes and collects class information. Perform runtime type checking.

268

JNI can be used with Invocation API to embed any native application in JVM. Drawback of native code is that it violates javas platform independent features and since binary files are generated during native implementation therefore this procedure has less security. Java native interface allows java byte-codes to communicate with foreign methods like C/C++. Advantage of such a technique is that byte-codes can able to communicate with executable files which execute faster, hence increases the performance. In java native code or native method accesses JVM features by calling JNI functions. In java JNI functions are available by using an interface pointer. An interface pointer is a pointer to a pointer to a structure. This structure pointer points to a set of pointers to function which is inside the structure Java Native Interface

The best way to grasp the concept is through an example. JAVA - C COMMUNICATION //Java - C Communication public class p { int i; public static void main(String args[]) { p x=new p(); x.i=10; System.out.println(x.i); x.fun(); //Native method calling. System.out.println(x.i); } public native void fun();

269

//Native method declaration. static{ System.loadLibrary("p"); } } Step 1: Compile it with javac p.java This will generate the class file as p.class Step 2: Create the header file by the command javah p This will generate the header file p.h .

p.h /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class p */ #ifndef _Included_p #define _Included_p #ifdef __cplusplus extern "C" { #endif /* * Class: p * Method: fun * Signature: ()V */ JNIEXPORT void JNICALL Java_p_fun (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif

The above two steps are same for WINDOWS and LINUX

270

For LINUX: Step 3: create the .C file p.c Note that: For LINUX the .C file name should be same as that of the java file name otherwise run time error will arise.

p.c #include"p.h" #includejni.h #include"stdio.h" JNIEXPORT void JNICALL Java_p_fun (JNIEnv *env, jobject obj) { jclass cls; jfieldID fid; jint i; printf("Hello"); cls=(*env)->GetObjectClass(env,obj); fid=(*env)->GetFieldID(env,cls,"i","I"); i=(*env)-> GetIntField(env,obj,fid); printf("%d",i); }

271

Step 4: create the object file by gcc O fpic -c p.c Note that: In case you are using multithreading in your programs you have to use the D_REENTRANT attribute along with the command to create the object file. gcc -O -D_REENTRANT -fpic -c p.c

Step 5: create the libp.so(shared library) file by gcc -shared -o libp.so p.o

Step 6: get the output by java Djava.library.path=. p

On windows platform: Step 3: CL/LD p.c To create dynamic linking library java p to execute java program p.java file is a usual java file. Header file p.h is generated by JVM, it contains the prototype declaration of the native method. Native methods are loaded when the programmer call a static method of System class, public static void loadLibrary()

272

JNIEXPORT void JNICALL Java_p_fun (JNIEnv *, jobject) Signature: V() inside the comment line indicates that the return type of native method is void. The signature of other return types are listed below

Java Type Type Signature Z B C S I J F D boolean byte char short int long float double

L fully-qualified-class ; fully-qualified-class [ type ( arg-types ) ret-type type[ ] method type

Consider the p.c file. It takes the argument JNIEnv *env & jobject obj. typedef const struct JNINativeInterface *JNIEnv; JNIEnv is a pointer to the structure JNINativeInterface which contains function pointers. Lets understand the concept through an example. Consider the C program below void fun() {

273

printf(Hello World); }

struct xxx { void(* p)(); }; typedef struct xxx *struct_ptr ; int main() { struct_ptr *pointer ; struct xxx a,*ptr1; a.p=&fun; ptr1=&a; pointer=&ptr1; (*pointer)->p(); } The out put will be Hello World. You can see that JNIEnv *env is similar to that of struct_ptr *pointer & struct xxx is similar to that of JNINativeInterface . Now consider the second argument jobject obj, obj holds the value of the this pointer that points to the current object that is x here. GetObjectClass(JNIEnv *,jobject); is a function pointer inside the structure JNINativeInterface. While java is communicating with C jobject & jclass both are same. jclass is typedef as jobject(typedef jobject jclass). GetOBjectClass returns the reference of the current object which is stored in

274

cls. GetFieldID reurns the reference held by cls to access the various class member present in the class. Prototype of GetFieldID is

jfieldID GetFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

Here name parameter holds the name of the class element to be accessed by the native method & sig parameter holds signature of the class element. Both these parameter are pointer to character constant. In the program, name holds the name of the class element that is i & sig holds I, signature of i to indicate that i is of integer type. GetIntField(env,obj,fid); rturns the value of i. Similarly if the class contains a float variable then to access that variable the function will be GetIFloatField(env,obj,fid); Example 2: p1.java //Get Your Native Interface Version. class p1{ public native void fun(); public static void main(String args[]) { new p1().fun(); } static{ System.loadLibrary("p1"); } } p1.h /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class p1 */ #ifndef _Included_p1 #define _Included_p1 #ifdef __cplusplus extern "C" { #endif /*

275

* Class: p1 * Method: fun

* Signature: ()V */ JNIEXPORT void JNICALL Java_p1_fun (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif p1.c #include"p1.h" #include"stdio.h" JNIEXPORT void JNICALL Java_p1_fun (JNIEnv *a, jobject b) { jint i=(*a)->GetVersion(a); printf("%x",i); } Both these examples have is data type as jint. In JNI int is typedef as jint. Similarly the typedef version of other java data types are listed below. Java Type Native Type Description boolean byte char short int long jboolean jbyte jchar jshort jint jlong unsigned 8 bits signed 8 bits unsigned 16 bits signed 16 bits signed 32 bits signed 64 bits

276

Java Type Native Type Description

float double void

jfloat jdouble void

32 bits 64 bits N/A

Example 3:

//Static native method p2.java class p2{ public native static void fun(); static{ System.loadLibrary("p2"); } public static void main(String aegs[]) { p2.fun(); }}

p2.h /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class p2 */ #ifndef _Included_p2 #define _Included_p2 #ifdef __cplusplus

277

extern "C" { #endif /* * Class: p2 * Method: fun * Signature: ()V */ JNIEXPORT void JNICALL Java_p2_fun (JNIEnv *, jclass); #ifdef __cplusplus } #endif #endif p2.c #include"stdio.h" #include"p2.h" JNIEXPORT void JNICALL Java_p2_fun (JNIEnv * a, jclass b) { printf("Hello C, From JAVA"); } Since the native method is static therefore second argument to the function JNIEXPORT void JNICALL Java_p2_fun (JNIEnv * a, jclass b) is of jclass type. I have already told that when java communicate with C, jclass & jobject are exactly the same thing so you can replace jclass with jobject.

278

Chapter 19 Multithreading Introduction


Thread!!!! What is a thread? Threads, processes, context-switch, scheduler these are the closely associated terms belongs to the Operating System fundamentals. Multi threaded programming approach is one of the powerful feature of Java. To grab the concept of multithreading you have to understand the fundamental aspects of operating system mentioned above. So lets start our voyage. What happens when you click on the icon (Or shortcut) of Project IGI (a computer game)? Its executable file is loaded in to the RAM of your PC from secondary storage device & the game starts. You can say that Project IGI is in execution phase. Any computer program in its execution phase is known as process. A program will be termed as a process till it is located inside RAM. You people have definitely come across the names of Unix, Linux, Windows Xp, Windows Vista as multi tasking operating system. So what is multi tasking operating system? Operating systems those can perform multiple tasks at a particular instant of time is known as multi tasking OS. Multiple tasks at a single instant of time is it really possible? Whatever PCs you are using, those have only one processor. At any instant of time only one task or one process can be executed by the processor. The definition of multitasking OS does not provide the clear picture. Actually in case of multi tasking OS, multiple tasks are submitted to the processor for execution & processor keeps switching between different tasks. Got it!!! If not just think about yourself. If multiple tasks are given to you what do you do? Say in a Sunday morning you have planed to do these following tasks 1: Complete the novel White Tiger (a 1000 page book) 2: watch the TV show Office-Office at 9.30 a.m. 3: Meet to a friend at 11 a.m. So what should be your way to complete these things? Definitely if you try to complete the novel 1st then do the tasks in a sequence then you cannot complete all of your planed tasks. In the early versions of OS, they do the tasks in the order of their arrival. Next task is performed only when one task

279

is completed. These types of OS are known as single tasking operating system. So what I mean to say is you can not behave as single tasking OS to complete all of your scheduled jobs. What you will do start the novel say at 8.30 a.m. At 9.30 a.m. put a mark on the book & watch the T.V show. After your show is completed you will start the book from where you have left. Again at 11 a.m. you will put a mark on the book & go to meet to your friend & when you will back again start the book from where you have left. Multitasking OS simply follow your procedure to complete their assigned tasks. They just keep switching between different tasks (from OS prospective tasks are known as processes). The process of switching between different processes are known as context switch. This technique improves the efficiency. The switching of process is so fast that it pretends the user as multiple tasks are done at a single instant of time. The normal question that comes in mind is that how this concept improves the efficiency. Let me give an example You all know that IO devices of your system are quite slow as compared to the speed of the processor. If process needs a data from IO device, it has to wait until the data is available. In single tasking OS, processor will remain ideal until the data is available in IO device. The processor time is wasted. But, in case of multitasking OS processor switch to another process & when the data is available in the IO device it will again switch back to the previous process. Just like you multitasking OS keeps the mark to track the correct path of execution when context switch is performed. These marks are maintained in a component of OS known as Task Control Block. Another component of OS known as scheduler is responsible in determining which task has to be performed. But, what is thread? Definition of thread is: Thread is a light weight process. If you have multiple related tasks then it is always better to create threads then to create a new process. Creating a new process involves 30% more over head instead of creating new process. Benefits of Multithreading : in a multi threaded application different parts of the application is executed by different threads. If any of the thread is blocked during the execution of the application then the entire application never halts. e.g. A multithread

280

web browser could still allow user interaction in one thread while an image was being loaded in other thread. Incase of multiprocessor architecture, different threads are allocated to different processors. Each thread is executed in different processors in parallel. Three main thread libraries are use in today. a) POSIX Pthreads. b) Win32. c) Java.

Creation of thread in java Thread is created in java by implementing the Runnable interface available in java.lang package. The Runnable interface contains only the run method which has to be over ridden. Now lets write a program to create the thread class MyThread implements Runnable { public void run() { System.out.println("hello"); } } class Thread1{ public static void main(String args[]) { MyThread x=new MyThread(); Thread t=new Thread(x); t.start(); } } Output: hello Steps to create thread:

281

You have to implement the Runnable interface & override the run method. Just by implementing runnable interface thread is not created. I would rather say that by implementing the runnable interface you have created the task object & the code for the task is embedded inside the over ridden run method. Inside the main method thread class reference points to the task object by calling the thread class constructor which takes the task object as its argument. Here you can say that job is attached to the thread. Then the start method is invoked through the thread class reference variable. It is the entry point of the thread for execution. Start method tells to the JVM that thread is ready for execution. Then thread will wait until it is called by scheduler. I have seen in many java books that threads are created by extending thread class. There is absolutely no problem at all syntactically, but from OOP prospective the programmer can extend a class only when he has to increase its functionality. So I will suggest that be a nice Object Oriented Programmer & implement the Runnable interface to create the thread. Determination of name of currently running thread class Demo { public static void main(String[] args){ System.out.println(Thread.currentThread()); } } Output: Thread[main,5,main] Here the method currentThread() is used to determine the name of the currently running thread. It is a static method. It returns the name of the thread where it is invoked. Check the out put Thread indicates the currenly executing thread is a Thread class object, main is its name, 5 is its priority, main is its group. When ever you create a thread in java a priority is always associated with it. Priority value is varied from 1 to 10. 1 is the minimum priority & 10 is the maximum priority. Thread having maximum priority is preferred over thread having minimum priority by the scheduler of JVM. Each thread in java has a default priority level 5. The next main indicates the name of the group to which thread belongs. Thread Priorities

282

Every thread has a priority, which is an integer from 1 to 10; threads with higher priority should get preference over threads with lower priority. The priority is taken in to account by the thread scheduler when it decides which ready thread should execute. The thread having highest priority is choosen by the scheduler to be executed first . The default priority is 5. To set a threads priority, call the setPriority() method, passing in the desired new priority. The getPriority() method returns a threads priority. The Thread class also has constants to define the priority of the thread. MIN_PRIORITY (which is= 1), and NORM_PRIORITY (which is= 5) the MAX_PRIORITY (which is=10) Program to determine the priority of current thread class X implements Runnable{ public void run() { System.out.println(Thread.currentThread()+"Hello X"); } }

class Demo { public static void main(String[] args){ X o=new X(); Thread t1=new Thread(o,"1st"); System.out.println(t1.getPriority()); t1.start(); } } Output: 5 Thread[1st,5,main]Hello X Setting the priority of a thread class X implements Runnable{ public void run() { System.out.println(Thread.currentThread()+"Hello X");

283

} } class Demo { public static void main(String[] args){ X o=new X(); Thread t1=new Thread(o,"1st"); t1.setPriority(8); t1.start(); } } Output: Thread[1st,8,main]Hello X

I have already told that thread priority plays vital role when comes to be selected by scheduler for execution. See the program below

class X implements Runnable{ public void run() { System.out.println(Thread.currentThread()); } } class Demo { public static void main(String[] args){ X o=new X(); X p=new X(); Thread t1=new Thread(o,"1st"); Thread t2=new Thread(p,"2nd"); t1.setPriority(3); t2.setPriority(9); t1.start(); t2.start(); } } Output: Thread[2nd,9,main] Thread[1st,3,main]

284

Process of yielding Yielding is the process through which currently executed thread goes to ready state from running. If any other thread is waiting for execution then that thread might get chance for execution. class X implements Runnable{ public void run() { System.out.println(Thread.currentThread()); Thread.yield(); System.out.println(Thread.currentThread()); } } class Demo { public static void main(String[] args){ X o=new X(); X p=new X(); Thread t1=new Thread(o,"1st"); Thread t2=new Thread(p,"2nd"); t1.start(); t2.start(); } } Output: Thread[1st,5,main] Thread[2nd,5,main] Thread[1st,5,main] Thread[2nd,5,main] See the output 1st t1 starts running when yield method is called t1 goes to wait state & t2 starts running. Then t2 goes to wait state because yield() method is invoked within it & t1 again starts executing. But story is different if you set the priorities. class X implements Runnable{ public void run()

285

{ System.out.println(Thread.currentThread()); Thread.yield(); System.out.println(Thread.currentThread()); } } class Demo { public static void main(String[] args){ X o=new X(); X p=new X(); Thread t1=new Thread(o,"1st"); Thread t2=new Thread(p,"2nd"); t1.setPriority(3); t2.setPriority(9); t1.start(); t2.start(); } } Output: Thread[2nd,9,main] Thread[2nd,9,main] Thread[1st,3,main] Thread[1st,3,main]

The sleeping process of thread sleep() method is a starting method belongs to Thread class so it is invoked by its class name. it causes the thread to sleep for a particular time period as given by the programmer in its parameter in which it is called. Its signature is public static void sleep(long milliseconds) throws InterruptedException public static void sleep(long milliseconds, int nanoseconds) throws InterruptedException When a thread completes its sleeping it directly does not enter to execution state or running state rather it goes to ready state till it is called by thread scheduler of JVM. The Thread class also contains a method called interrupt(). A sleeping thread upon receiving an interrupt call immediately moves to ready state when it gets to run, it will execute its InterruptedException handler.

286

class X implements Runnable{ public void run() { try{ Thread.sleep(2000); }catch(InterruptedException e) { System.out.println("I am mhandling it"); } System.out.println(Thread.currentThread()); } } class Demo { public static void main(String[] args){ X o=new X(); Thread t1=new Thread(o,"1st"); t1.start(); t1.interrupt(); } } Output: I am mhandling it Thread[1st,5,main] Context switch between no. of threads by the use of sleep() method Multiple numbers of threads can be created by creating multiple no of thread objects and allocating different task object to it. But, the issue is how to use them such that they will keep switching among them self. The solution is the invocation of sleep() method. Let me give an example

class X implements Runnable{ public void run()

287

{ for(int i=1;i<5;i++) { try{ Thread.sleep(500); }catch(InterruptedException e) { } System.out.println(Thread.currentThread()+"Value="+i); } } } class ThreadDemo { public static void main(String[] args){ X o=new X(); Thread t1=new Thread(o,"1st"); X p=new X(); Thread t2=new Thread(p,"2nd"); t1.start(); t2.start(); } } Output: Thread[1st,5,main]Value=1 Thread[2nd,5,main]Value=1 Thread[2nd,5,main]Value=2 Thread[1st,5,main]Value=2 Thread[2nd,5,main]Value=3 Thread[1st,5,main]Value=3 Thread[2nd,5,main]Value=4 Thread[1st,5,main]Value=4 Inside main method we have created two task objects o &p. Two threads t1 & t2 is created & two tasks are allocated to them. Inside the for loop of run method sleep(500) method is invoked. Since it is a static method it is invoked by its class name. The argument inside the sleep method makes the thread sleep for that much millisecond in which it is invoked. 1st main thread starts execution, when t1.start() method is invoked, t1 is ready for execution. When t1 gets it turn for execution inside

288

it sleep is called & JVM t pauses the thread t1 & control jumps back to main thread. Now t2 is ready for execution. During the execution of t2 when sleep method is encountered t2 again goes to sleep & control jumps back to main. When t1 completed its sleep control jumps to t1. In this way control jumps or switches between main thread , t1 & t2. Use of join method The signature of join method is final void join() throws InterruptedException. This method waits until the thread upon which is called is terminated that means calling thread waits until the specified thread joins it. Different forms of join() method is available in the Thread class which can be used in specifying the time period up to which you want a thread to wait for specific thread. I must say that this method is useful in developing multi threading programming approach. Let me give an clear picture through an example class X implements Runnable { public void run() { System.out.println("Inside X"); } } class Thread1 { public static void main(String []args) { X job=new X(); Thread t=new Thread(job,"job"); t.start(); System.out.println("Inside main"); } } Output: Inside main Inside X In multi threading programming it may so happen that main thread exits but the

289

created thread is still alive. You can invoke the sleep method in main thread & forced the main thread to sleep for a particular time period you expect that in that time period the thread you have created completes its task. These things are just your expectations may happen may not happen. So what we need a concrete method that will ensure that main thread is going to wait till the create thread expires. join() method solves your problem. I have illustrated the thing below through an example. package demo; class X implements Runnable { public void run() { System.out.println("Inside X"); } } class Thread1 { public static void main(String []args) { X job=new X(); Thread t=new Thread(job,"job"); t.start(); try{ t.join(); }catch(InterruptedException e) { } System.out.println("Inside main"); } } Output: Inside X Inside main Thread Synchronization When multiple numbers of threads need to access a common resource, then care must be taken by the programmer that only one thread can access the shared resource at a particular instant of time. The technique through which

290

we achieve the mentioned goal is known as synchronization. Let me explain some terms associated with synchronization technique. Monitor(or you can say semaphore) I will use the term semaphore instead of monitor as semaphore is quite a friendly term in OS. Semaphore is an object having mutual exclusive lock. One thing often mutual exclusive lock is known as mutex. At a particular instant of time one thread can be the owner of semaphore. When on thread owns the semaphore it is said that the thread has acquired the lock & entered in to the monitor. All other thread out side the monitor or you can all threads except the owner of the semaphore wait until the owner of semaphore releases its owner ship or you can say exit from monitor. If you have done a bit system level programming in C then synchronization is quite familiar for you. But, one thing implementation synchronization in C involves system calls. It is not directly supported by C language. But java directly support synchronization technique by the use of synchronize key word. Synchronized key word is used as block or method. In java all the objects have implicit monitor or you can say semaphore associated with them. To own the semaphore, you just have to invoke a method using synchronize key word. While a thread is inside a synchronized method or block, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To release the control of shared object the thread has to return from synchronize method or block. Without use of synchronized block package demo; class Y { int bal=100; } class X implements Runnable { Y p; int r; int sleepValue; X(int a,int b, Y g) { r=a; sleepValue=b; p=g; }

291

public void run() { if(p.bal>r) System.out.println("Fund is available"); try{ Thread.sleep(sleepValue); }catch(InterruptedException e){} if(p.bal>r) { p.bal=p.bal-r; System.out.println("Got it!!"+Thread.currentThread()); }

else{ System.out.println("Insufficient "+Thread.currentThread()); } } } class Thread1 { public static void main(String []args) { Y n=new Y(); X job1=new X(50,1000,n); X job2=new X(80,0,n); Thread t1=new Thread(job1,"job1"); Thread t2=new Thread(job2,"job2"); t1.start(); t2.start(); } } Output: Fund is available Fund is available Got it!!Thread[job2,5,main] Insufficient Thread[job1,5,main] Use of synchronized block

292

package demo; class Y { int bal=100; } class X implements Runnable { Y p; int r; int sleepValue; X(int a,int b, Y g) { r=a; sleepValue=b; p=g; } public void run() { if(p.bal>r) System.out.println("Fund is available"); synchronized(p){ try{ Thread.sleep(sleepValue); }catch(InterruptedException e){} if(p.bal>r) { p.bal=p.bal-r; System.out.println("Got it!!"+Thread.currentThread()); } else{ System.out.println("Insufficient "+Thread.currentThread()); } } } } class Thread1 { public static void main(String []args) { Y n=new Y();

293

X job1=new X(50,1000,n); X job2=new X(80,0,n); Thread t1=new Thread(job1,"job1"); Thread t2=new Thread(job2,"job2"); t1.start(); t2.start(); } } Output: Fund is available Fund is available Got it!!Thread[job1,5,main] Insufficient Thread[job2,5,main] In the first case I have not used the synchronized block therefore job1 suffers although request to access the bal variable of Y is 1st made by it. But by the use of synchronized key word in the second program job1 is not suffered. I have always given priority to use synchronized block rather than synchronized method because the prior one improves performance due to atomic level synchronization. Lifecycle of a thread Life cycle of a thread includes 1:Ready 2:Running 3:Blocked state 4:Dead When the start() method is called, the thread does not start running immediately. It goes into a ready state and stays there until the task scheduler or you may say thread scheduler select it for execution. When a thread starts execution, it to the running state. Then the run() method is called. During its execution state, the thread may temporarily give up the CPU. This is because of various reasons it may goes to a sleep or it is waiting for some event to be happened. This is known as blocked state. Finally when the thread completes its execution it goes to dead state. From the blocked state thread goes to ready state when it wakes up or by the invocation of resume method.

294

Stop() method sleep() or suspend() method is Or called


Dead

Running (Run method is in execution)

is

called

task

of

the

thread

is

completed
Blocked

Start() method Is resume() is called or


Ready

called

The thread wakes up after

Sleep.

When thread is dead When the execution of codes in side run() method is completed, the thread has finished its task and is considered as dead. Once a thread become dead it can not go to any other state. It cannot be started again; if you invoke the start method then time exception is thrown by JVM. class X implements Runnable{ public void run() { System.out.println(Thread.currentThread()+"Hello X"); } }

295

class Demo { public static void main(String[] args){ X o=new X(); Thread t1=new Thread(o,"1st"); t1.start(); t1.start(); } } Output Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.start(Unknown Source) at demo.Demo.main(Demo.java:20) Thread[1st,5,main]Hello X The dead thread is an object of Thread class & therefore it is possible to access its data and call its methods. Always remember that You cant restart a dead thread. You can call the methods of a dead thread. Thats all about threading in java folks

296

Chapter-20
GENERICS

INTRODUCTION Generics is a powerful feature of java. It is introduced by JDK 5. It is said to be powerful because using it we can create classes , interfaces , and methods that will work for various types of data in a type safe manner. Using generics we can define a single algorithm which is independent of data ,then apply the same algorithm for various data types without any changes. Why we need Generics? We generally create classes , interfaces and methods which are type specific but using generics it is possible create classes , interfaces and methods which are type independent. Previously we do this things using Object class, because Object class is the super class of other classes, an Object reference can refer to any type of object . to get the actuall data we have to explicitly type cast it to the required type. Generics overcomes this overhead, in generics all type casts are done implicitly. This makes the use of generics more secure. A simple example // Defination of the generic class Gener class Gener<S> { S obj; Gener(S o) { obj =o;

297

} void showClass() { System.out.println("Type of S is "+ obj.getClass().getName()); } void showData() { System.out.println("Data is "+obj); } }

public class GenericDemo { public static void main(String[] args) { // Create a Gener reference for Integer Gener<Integer> ob1 = new Gener<Integer>(100);

// prints the type of data hold by it ob1.showClass();

298

// prints the data hold by it ob1.showData();

// Create a Gener reference for Sting Gener<String> ob2 = new Gener<String>("SAMITA , LORY");

// prints the type of data hold by it ob2.showClass();

// prints the data hold by it ob2.showData() ; } } Output : Type of S is java.lang.Integer Data is 100 Type of S is java.lang.String Data is SAMITA , LORY

In the above example S is the name of a type parameter. S holds the type parameter of which the Gener class object is created. S is written inside

299

<>. Whenever we specify the type of class object we want to create we specify it inside <>. And everywhere in the class definition S behaves like the type specified for that object. Gener<Integer> ob1 = new Gener<Integer>(100); Here we created the object of Gener class, of Integer type. We also have specify the type inside <> while calling the constructor. Here the S holds Integer , so for ob1 S behaves as Integer. So we have passed the argument according to the type. Gener<String> ob2 = new Gener<String>("SAMITA , LORY"); Here we created the object of Gener class ,of String type. Here S holds String , so for ob2 S behaves as String. So we have passed the argument according to the type.

Generics works only on objects. That means the type argument passed to type parameter must be a class type but it cannot be any primitive type. e.g Gener<int> ob1 = new Gener<int>(100); // Error

The above example will result in an error because primitive type ( int , char,... etc) cannot be used . y One thing we have to understand is that a reference of one specific type of generic type is different from another type of generic type. e.g ob1 = ob2 ; // wrong the above is wrong because although ob1 and ob2 both are of type Gener<T> but they are references of different types because of their type parameters.

300

A Generic class with two type parameters We can use more than one type parameter in a generic type. If we want specify two or more type parameters , we just have to separate them with commas. Lets consider the example below.

// Defination of the generic class Gener class Gener<A , B>{ A ob1; B ob2; Gener(A o1 ,B o2 ) { ob1 =o1; ob2 =o2; } void showClass() { System.out.println("Type of A is "+ ob1.getClass().getName()); System.out.println("Type of B is "+ ob2.getClass().getName()); } void showData() { System.out.println("Data in ob1 "+ ob1); System.out.println("Data in ob2 "+ ob2);

301

} } public class GenericDemo { public static void main(String[] args) { // Create a Gener reference for Integer and String Gener<Integer,String> obj1 = new Gener<Integer,String>(100,"SAMITA , LORY");

// prints the type of data hold by it obj1.showClass();

// prints the data hold by it obj1.showData(); } } Output : Type of A is java.lang.Integer Type of B is java.lang.String Data in ob1 100 Data in ob2 SAMITA , LORY

302

Here two type parameters T and V are separated by comma . so now if we want to create a refrence of Gener we have to pass two type arguments.

Bounded Type Generic class This is a feature of generics in which we can restrict the type argument passed to the type parameter of genericlass to a particular type. Let,see the example below. // Defination of the generic class Gener class Gener<A extends Integer >{ A ob1;

Gener(A o1 ) { ob1 =o1;

} void showClass() { System.out.println("Type of A is "+ ob1.getClass().getName()); } void showData() { System.out.println("Data in ob1 "+ ob1);

303

public class GenericDemo {

public static void main(String[] args) {

// Create a Gener reference for Integer Gener<Integer> obj1 = new Gener<Integer>(100);

// prints the type of data hold by it obj1.showClass();

// prints the data hold by it obj1.showData();

Output : Type of A is java.lang.Integer Data in ob1 100

The above will work well but not the below program. lets see .

304

// Defination of the generic class Gener class Gener<A extends Integer >{ A ob1;

Gener(A o1 ) { ob1 =o1; } void showClass() { System.out.println("Type of A is "+ ob1.getClass().getName()); } void showData() { System.out.println("Data in ob1 "+ ob1); } }

public class GenericDemo {

public static void main(String[] args) {

305

// Create a Gener reference for String Gener<String> obj2 = new Gener<String>("SAMITA , LORY");

// prints the type of data hold by it obj2.showClass();

// prints the data hold by it obj2.showData(); } } Output : Exception in thread "main" java.lang.Error: Unresolved compilation problems: Bound mismatch: The type String is not a valid substitute for the bounded parameter <A extends Integer> of the type Gener<A> Bound mismatch: The type String is not a valid substitute for the bounded parameter <A extends Integer> of the type Gener<A>

at GenericDemo.main(GenericDemo.java:27) The above program will result in an error because we have bounded the type of A to Integer so if we will try to give it any other type except the child classes of Integer then it will result in an error. y y We can also declare interfaces as bound for A . Web can also declare one class and multiple interfaces as bound for A. e.g class Gener<A extends Myclass & Myinterface>

306

here Myclass is a class and Myinterface is a interface and & operator is used to connect them.

Wildcard Arguments

Wildcard arguments are a special feature of generics . suppose we want to define a method inside the generic class which compares the value of different type of generic class object and returns the result irrespective of their types. Previously it was not possible because a method defined inside the generic class can only act upon the data types which is same as that of the object calling it. But using wildcard arguments we can do this. To know about the use of Wildcard arguments lets see the example below.

// Defination of the generic class Gener class Gener<T>{ T ob1;

Gener(T o1 ) { ob1 =o1;

} // wildcard argument is used void Equalls(Gener<?> o2) { if(ob1 == o2.ob1)

307

System.out.println("TRUE"); else System.out.println("False");

} } public class GenericDemo { public static void main(String[] args) { // Create a Gener reference for Integer Gener<Integer> obj2 = new Gener<Integer>(100); // Create a Gener reference for Double Gener<Double> obj1 = new Gener<Double>(100.0); // Create a Gener reference for String Gener<String> obj3 = new Gener<String>("100"); obj2.Equalls(obj1); obj2.Equalls(obj3); obj1.Equalls(obj3); } } Outpurt : False False False

308

In the above program we have used the wild card argument , <?> represents the wildcard argument i.e it will work irrespective of types. we can see that the Equalls method checks the value of different objects irrespective of their types and prints the result . y Wild cards can also be bounded. Suppose we want that in the above example the Equalls method only execute for Numbers otherwise results in an error. So we just have to change a little bit in the method definition i.e void Equalls(Gener<? extends Number> o2) { if(ob1 == o2.ob1) System.out.println("TRUE"); else System.out.println("False"); } Now if we are going to execute the statements obj2.Equalls(obj3); obj1.Equalls(obj3); it will result in an error because we can create a object reference of Genr class for String type but we cannot use the Equalls method for the String type.

Creating Generic Method and Generic Constructor Now we will see how to define a generic method and generic class. A generic method can be created inside a non-generic class which acts on multiple types of data independently. We can also define a generic constructor inside a non-generic class which can act on multiple types independently. Lets see the below example.

309

public class GenericDemo { double db;

// Generic constructor <T extends Number> GenericDemo(T o1) { db= o1.doubleValue(); } // Generic Method static < V > void Display(V o2) { System.out.println(o2); } void show() { System.out.println(db); } public static void main(String[] args) { GenericDemo g1 = new GenericDemo(100); g1.show(); GenericDemo g2 = new GenericDemo(1025.54); g2.show(); GenericDemo g3 = new GenericDemo(103.9F);

310

g3.show(); Display(100); Display(125.56); Display("SAMITA , LORY"); } } Output : 100.0 1025.54 103.9000015258789 100 125.56 SAMITA , LORY From the above example we can observe the output. The Generic constructor is taking the numbers of different type of argument as type parameters and storing its double value in the variable db of each reference.like that the Display method is taking different type of arguments as type parameters and displaying the value. Erasure or Raw Types A raw type is a parameterized type stripped of its parameters. The official term given to the stripping of parameters is type erasure. Raw types are necessary to support legacy code that uses non-generic versions of classes . Because of type erasure, it is possible to assign a generic class reference to a reference of its nongeneric (legacy) version. Therefore, the following code compiles without error: Gener ob1 ; Gener<Integer> ob2 ; ob1=ob2; // valid

311

ob2=ob1 ; // will cause a unchecked warning

Remember during compilation all types parameters are erased only raw types actually exists.

// Defination of the generic class Gener class Gener<T>{ T obj; Gener(T o) { obj =o; }

void showClass() { System.out.println("Type of T is "+ obj.getClass().getName()); } void showData() { System.out.println("Data is "+obj); } } public class GenericDemo {

public static void main(String[] args) {

312

// Create a Gener reference for Integer Gener ob1 = new Gener(100); System.out.println("Type of ob1 is "+ ob1.getClass().getName()); // prints the type of data hold by it ob1.showClass(); // prints the data hold by it ob1.showData(); // Create a Gener reference for Sting Gener<String> ob2 = new Gener<String>("SAMITA , LORY"); System.out.println("Type of ob2 is "+ ob2.getClass().getName()); // prints the type of data hold by it ob2.showClass(); // prints the data hold by it ob2.showData(); } } Output : Type of ob1 is Gener Type of T is java.lang.Integer Data is 100 Type of ob2 is Gener

313

Type of T is java.lang.String Data is SAMITA , LORY

From above example we can see that ob1 and ob2 are both of Gener class, they are not of Integer class or String class. But according to the parameters the variables inside ob1 and ob2 are type casted accordingly. When we write the below code Gener<Integer> ob1 = new Gener<Integer>(100); int i = ob1.obj;

it is compiled as if it is written like this : Gener ob1 = new Gener(100); int i = (Integer)ob1.obj;

Some Restrictions While Using Generics y Type parameters cannot be instanciated : class Gener<T>{ T obj; Gener(T o) { obj =newT(); // error } } The above code will result in an error because T doesn,t exist at runtime so how compiler will know what type of object to create. y Restrictions on Static Members : Below are some facts we should care of while using static keyword.

314

class Gener<T>{ // error , cannot make a static reference to a nonstatic type static T obj ; // error, no static method can use T Static T show() { // error , no static method can acces T type object System.out.println(obj); } }

Java Generics vs. C++ Templates

While generics look like the C++ templates, it is important to note that they are not the same. Generics simply provide compile-time type safety and eliminate the need for casts. The main difference is encapsulation: errors are flagged where they occur and not later at some use site, and source code is not exposed to clients. Generics use a technique known as type erasure as described above, and the compiler keeps track of the generics internally, and all instances use the same class file at compile/run time.

A C++ template on the other hand is just a fancy macro processor; whenever a template class is instantiated with a new class, the entire code for the class is reproduced and recompiled for the new class.

315 Chapter-21 Files and Streams

Files are located in the secondary storage of the system. When it is opened for any purpose first it is loaded in to the primary memory, then the operation is performed. After any write operation the changes are reflected according to the implementation of either write through or write back protocol. Files are normally of two types; binary file & text file. Java provides two ways to handle files. One through various streams provided in java.io package & other through File class which does not required streams to operate. The File class By the use of File class you can directly deal with the files, directory & file system of the platform. Actually java does not provide crystal clear view of how the things are done in background when the programmer uses the File class. Programmer has to create the file object through the constructors provided by File class. Then, using those objects programmer can perform manipulation with the files & directory. File class constructors are used for the creation of the object of the File class. These constructors are overloaded. Various forms of these constructors are given below. File f1 = new File (c: / Minerva / ravenX); Here I have shown how to open the existing file in window platform. File f2 = new File (c: / Minerva , rian ); Here 1st parameter is the absolute path & the second parameter is the file that has to be opened. File f3 = new File (java, temp); Here the first parameter is a directory name in which the existing file temp has to be opened. One question may arise in the minds of novice programmer is that why files are required & the answer is files are required to have a persistent storing of data. Sometimes it is required to read the data from files rather than standard input device like keyboard. Another thing I want to say is that in java, directories are also treated as files. If you are dealing with directory, then you have to use the list () method provided by java to list out all the files residing in the directory.

316 Java is quite smart when it comes to deal with path separator. In windows you can use both /. If you are quite loyal to Microsoft & want to use \ then, you have to use the escape sequence \\. In UNIX & Linux you can use /. Methods of the File Class

By the help of the predefined methods of File class programmer can retrieve the properties of a file. String getName( ) Method This method returns the name of the file through which this method is invoked String getPath( ) / String getAbsolutePath ( ) method These two methods are used to get to get the absolute path of the file through which it is invoked.

String getParent ( ) method This method returns the name of the parent directory of the file through which it is invoked.

boolean exists ( ) method this methods checks whether the file exists or not through which it is invoked. boolean isFile ( ) / boolean isDirectory ( ) method these two methods are used to determine whether the file object through which it is invoked is a directory or file.

import java.io.File; //you need to import this package to have various methods to deal with file object. class Demo { public static void main(String args[]) {

317 File myfile=new File(/dir1/pex); System.out.println(Name: +myfile.getName()); System.out.println(Path: +myfile.getPath()); System.out.println(My absolute path: +myfile.getAbsolutePath()); System.out.println(My parent : +myfile.getParent()); System.out.println(Name: +myfile.getName()); if(myfile.exists()) System.out.println(file do exists!!!); else System.out.println(File does not exists); if(myfile.canRead()) System.out.println(file is readable ); else System.out.println(file is not readable); if(myfile.canWrite()) System.out.println(file is writeable ); else System.out.println(file is not writeable); if(myfile.isFile()) System.out.println(It is a normal file); else System.out.println(It is not a normal file might be system file like device driver.);

System.out.println(File was last modified+myfile.lastModified());

318 System.out.println(size of the file is in bytes+myfile.length()); } } boolean canRead ( ) / boolean canWrite ( ) methods

These methods are used to check if we can read from the specified file or write into the specified file respectively. These methods return a boolean value depending on their readability/ writability.

Use of long lastModified( ), canWrite() & canRead() methods This method returns the modification time the file.

Example 3

import java.io.*; public class File2 { public static void main(String args[]) { File f1 = new File ("c:/java","abc.txt"); if(f1.canRead()) System.out.println ("we can read from this file") ; else System.out.println ("we cannot read from this file" ) ; if(f1.canWrite()) System.out.println("we can write to this file"); else System.out.println("we cannot write to this file");

319 System.out.println("The file was at"+f1.lastModified()+"seconds after January 1 1980"); } } last modified

The file I have used has both read & write option. Therefore that is the output. But, the interesting one is the output of lastModified() method. It shows the time period in millisecond after which the file is modified with respect to 1st January How to rename a file: renameTo() method is used to rename an existing file.

Example 4

class Demo { public static void main(String[] args) { File myFile=new File (/dir1/pex); boolean b1=myFile.renameTo(Minarva); if(b1) System.out.println(Rename operation is success full); else System.out.println(File cannot be renamed); } } renameTo() method returns boolean true value upon if rename is done successfully otherwise false is returned.

320 Deleting an existing file

Example 5

class Demo{ public static void main(String[] args) { File myFile=new File(/dir1/pex); boolean b1=myFile.delete(); if(b1) System.out.println(file is deleted); else System.out.println(File cannot be deleted ); } } delete() method returns true if file is deleted successfully else it will return false. There is another method dleteOnExit() deletes the file when you complete the operation exit from the execution phase of the program. File class also provides some other useful methods like: public long length( ) This method is used to know the file size in bytes.

Lets have another example to fix ideas concretely.

Example 6

import java.io.*; public class File3

321 { public static void main(String args[]) { File f=null; for(int i=0;i<args.length;i++) { f=new File("c:/java",args[i]); } File f1=new File("c:/java/renfile"); if(f.exists()) { System.out.println(f+" exists"); System.out.println("its size is "+f.length()+" bytes"); f.renameTo(f1); System.out.println("Renamed file name :"+f1); System.out.println("deleting the file "+f); System.out.println ("= = = = = = = = = ="); f.delete(); }else{ System.out.println(f+" does not exist"); } } }

322

Space available in a specified partition J2SE 6 provides three methods to get various attributes associated with the particular partition where the file resides. See the example blow

Example 7

class Demo{ public static void main(String[] args) { File myFile=new File(/dir1/pex); if(myFile.exist()==false) { System.out.println(The specified file does not exist); return ; } long x=myFile.getfreeSpace(); x=x/1000; System.out.println(Amount of space available in MB: +x); x=myFile.getTotalSpace(); x=x/1000; System.out.println(total space in MB: +x);

323 } } Output, easily you can guess. Methods like getFreeSpace() & getTotalspace() when invoked on the specific file, then it checks the free space available & total space available respectively in terms of bytes. I have divided the returned value of these two methods by 1000 to get the things in MBs. How to make a file read only

Example 8

class Demo{ public static void main(String[]args) { File myFile=new File(/dir1/pex); if(myFile.exist()==false) { System.out.println(file doe snot exist); return; } boolean b1=myFile.setReadOnly(); if(b1) System.out.println(Operation is success full); else System.out.println(Operation failed); } } setReadOnly() method is used to make a file readonly.

324 Dealing with directories A directory is a collection of files and directories. In java directories are also treated as files. If you wish to deal with the directories then you can use the list() method. When list() method is invoked by the directory object(created through File class constructor) then list of other files and directories extracted from it. This method is over loaded. One of them is String [ ] list( ). Lets have program!

Example 9

import java.io.File; class DirectoryList { public static void main(String args[]) { String directory_name = "/Minerva"; File myFile = new File(directory_name); if (myFile.isDirectory()==true) { System.out.println ("Directory of + directory_name); String s1[] = myFile.list (); for (int i=0; i < s1.length; i++) { File f1 = new File(directory_name + "/" + s1[i]); if (f1.isDirectory()) { System.out.println(s1[i] + " is a directory"); } else

325

{ LIBRARY } } } else { System.out.println(directory_name + " is not a directory"); } } } Output is straight forward. Method names clearly indicate what are their task. boolean mkdir ( ) Method This method is used to create a directory and returns a boolean indicating the success of the creation. The following example the usage of this method. Example 10 import java.io.*; public class File5 { public static void main(String args[]) throws IOException { File myFile=new File("c:/Alice/wondeLand"); if(myFile.mkdir()==true) System.out.println("created a directory"); else System.out.println ("Unable to create a directory"); System.out.println(s1[i] + " is simply a file!!");

326 } }

If the mkdir() method is executed successfully the boolean true value is returned else the method is going to return false. The other over loaded form of public String[ ] list(FienameFilter FilterObj) method In this form of list() method, it is used to filter out the required files from a directory. Actually often we feel that a particular set of files has to be opened or list out instead of all the files present in the directory. Example-11

import java.io.*; public class File4 implements FilenameFilter { String w; public File4(String w) { this.w="."+w; } public boolean accept(File dir,String name) { return name.endsWith(w); } public static void main(String args[])throws IOException

327 { for (int p=0;p<args.length;p++) { File f1 = new File("e:/cobra/applet"); FilenameFilter only=new File4(args[p]); String s[]=f1.list(only) ; System.out.println ("printing files with "+args[p]+" extesion in the "+f1.getPath()+" directory") ; for(int i=0;i<s.length;i++) System.out.println(s[i]); } } }

In this program when I have invoked the overloaded list() method, this method implicitly invoke the accept() method. In side accept() method endsWith() method is invoked. Entire operation performs only one thing i.e. filter out the required files.

Use of Streams

What is a stream? Stream means a channel or pipe. Like water flow in a pipe, data flows from source to destination through the channels in java. Diagram 1

328

329

These channels are the object of various stream classes provided by Java. Java provides two types of streams input stream & output stream. By the use of input streams we receive the data from source & by the use of output streams we write the data at the desired destination. Java provides two ways to perform read & write operations. Reader class objects reads and Writer class writes the data in the form of characters. Stream class objects read & write in the form of bytes. Classes those end with the term reader deals with characters & classes those end with the term stream deals with bytes. Lets have a hierarchy structure of stream class.

330

With the help of the table you see various InputStream and their functions. By the help of these InputStream system directly read the data from file and buffer in byte format.

Class ByteArrayInputStream

Function

Supported methods

Allows a buffer in available( ), mark( ), memory to be used as mark Supported( ), read( an Input Streams ), insert( ), skip( ) For reading information available( ), from a file. close(),finalize(), read( ), skip() Abstract class providing available ( ), close( ), an interface for useful mark( ), markSupported( functionality to the ), read( ), reset( ), skip( ) other Input Stream classes.

FileInputStream

FilterInputStream

331 With the help of this table you see various OutputStream and its methods through which data is written in targeted output sources like file and buffer in byte format.

Class ByteArrayOutputStream

Function Creates memory a buffer

Supported methods in reset( ), size( ), ), ),

toByteArray( All the data we send to toString( ), the streams is placed in writeTo( ) this buffer. FileOutputStream Abstract class providing close( ), an interface for useful write( ) functionality to the other Output Streams classes

write(

flush(

),

Low-Level Stream Low-level input streams have methods that read input and return the input as bytes. Whereas Low-level output streams have methods that are passed bytes and write the bytes as output.

FileInputStream FileInputStream is a class that helps to read the data from a file. When the programmer wants to read the data from the file by using FileInputStream and file is not present then program is terminated at the runtime by throwing FileNotFoundException. There are two types of constructors available with this class.

The first constructer takes the name of the file as a String argument

FileInputStream f = new FileInputStream( c:/java/temp.exe );

332 The second constructor takes the File class object as an argument

File f = new File ( c:/java/temp.exe); FileInputStream f1=new FileInputStream(f);

FileOutputStream

The FileOutputStream class helps to create a new file and write data into in byte format. The two types of constructors are applicable to this class. The first constructer takes the filename as a string argument

FileOutputStream f = new FileOutputStream( c:/java/temp.exe );

The second constructor takes File class object as an argument

File f = new File ( c:/java/temp.exe); FileOutputStream f1=new FileOutputStream(f);

In case of FileOutputStream if the programmer writes the data into a read-only file then the program generates IOException. Example -12

import java.io.*; public class ReadWriteFile { public static byte get( )[] throws Exception {

333 byte in[]=new byte[50]; System.out.println("enter the text."); System.out.println("only 50 bytes of data is stored in the array "); System.out.println ("press enter after each line to get input into the program"); for (int i=0;i<50;i++) { in[i]=(byte)System.in.read( ); } return in; } public static void main(String args[])throws Exception { byte input []=get( ) ; FileOutputStream f=new FileOutputStream("c:/java/write.txt"); for (int i=0;i<50;i++) { f.write(input[i]); } f.close ( ) ; int size; FileInputStream fl=new FileInputStream("c:/java/write.txt"); size=fl.available ( ) ; System.out.println("reading contants of file write. Text"); for(int i=0;i<size;i++) {

334 System.out.print((char)fl.read ( )) ; } f.close( ) ; } }

ByteArrayInputStream

This class uses a byte array as its input source. It has two types of constructors. The first one takes a byte array as its parameter. ByteArrayInputStream b = new ByteArrayInputStream(byte buf[]) through this bytes. constructor programmer takes the input from the specified array of

ByteArrayInputStream b=new ByteArrayInputStream (byte buf [], int off, int len) In this constructor Off is the offset of the first byte to be read and len is the number of bytes to be read into the array.

ByteArrayOutputStream ByteArrayOutputStream class implements a buffer, which can be used as an OutputStream. The size of the buffer increases as data is written into the stream.

335 The data is retrieved using the methods toByteArray() and toString(). Two types of constructors exist. They are given below: ByteArrayOutputStream o = new ByteArrayOutputStream () This creates a buffer of 32 bytes to stroke the data. ByteArrayOutputStream o=new ByteArrayOutputStream (int size) The above constructor creates a buffer of size int. These methods return void and throw an IOException on error conditions. Example-13 import java.io.*; public class ByteArray { public static void main(String args[])throws Exception { ByteArrayOutputStream f=new ByteArrayOutputStream(12); System.out.println("enter 10 characters and press the enter key"); System.out.println("These will be converted to uppercase and displayed"); while(f.size( )!=10) { f.write(System.in.read( )); } System.out.println("Accepted characters in the array"); byte b[]=f.toByteArray( ); System.out.println("displaying characters in the array"); for(int i=0; i<b.length;i++) {

336 System.out.println((char)b[i]); } ByteArrayInputStream inp=new ByteArrayInputStream (b); int c; System.out.println("Converted to upper case characters"); for (int i=0;i<1;i++) { while ((c =inp.read( )) != -1) { System.out.print(Character.toUpperCase ((char)c)); } System.out.println(); inp.reset(); } } }

337 SequenceInputStream

SequenceInputStream is the child class of InputStream. This class is used to sequentially read the data from two input sources. Constructor:SequenceInputStream (new InputStream, new InputStream) Methods available:public int read()throws IOException public int read(byte b[],int buffer, int size)throws IOException public void close()throws IOException public int available()throws IOException final void nextStream()throws IOException ;

Example:-14 import java.io.*; public class Sequence { public static void main(String args[]) { try{ FileInputStream fis1=new FileInputStream("c:/a.txt"); FileInputStream fis2=new FileInputStream("c:/b.txt"); SequenceInputStream int ch; while((ch=s.read())!=-1) { s =newSequenceInputStream(fis1,fis2);

338 System.out.print((char)ch); } fis1.close(); fis2.close(); s.close(); }catch(FileNotFoundException fe) { fe.printStackTrace(); } catch(IOException ie) { ie.printStackTrace(); }

} }

Output:-

339 FilterInputStream class having the child classes named as :-BufferedInputStream, DataInputStream, PushbackInputStream. FilteredOutputStream class having the child classes BufferedOutputStream, DataOutputStream, PrintStream . named as:-

Class DataInputStream

Function

Supported Methods

Used in context with read(), readBoolean(), DataouputStream. Hence readByte( ), readFloat ( we can read ),

Primitives (int, char, long, readFully ( ), readInt( etc.) from a stream in a ), portable fashion. readLine ( ), readLong ( ), readShort( ), skipBytes( ) BufferedInputStream Use this to prevent a available( ), mark( ), physial read every time markSupported( ), read( more data is needed ), reset( ), skip( ),

PushbackInputStream Has a one-byte pushback available( ), mark( ), buffer, so the last reset( ), read( ), unread( character read can be ), markSupported( ) pushed back.

Class DataOutputStream

Function Used in context with DataInputStream. Hence we can write primitives (int, char, long, etc.) to a stream

Supported Methods flush( ), size( ), write( ), writeBoolean(boolean b), writeDouble(double d), writeFloat(float f ), writeInt(int i ), writeLong( long l),

340 in portable fashion. PrintStream writeShort( short s)

For producing formatted checkError( ), close( ), output. While flush( ), print( ), println ( ), setError( ), write( ), DataOutputStram handles the storage of data, PrintStream handles display. This is used to prevent a flush( ), write( ) physical write every time we send a piece of data. flush( ) can be called to flush the buffer

BufferedOutputSteam

High Level Stream Classes High-level input streams takes their input from other input streams where as Highlevel output streams direct their output to other output streams. High-level input streams are BufferedInputStream, DataInputStream and ObjectInputStream etc. High-level output streams are DataOutputStream, ObjectOutputStream, PrintStream etc. BufferedInputStream The BufferedInputStream class accepts input by using a buffered array of bytes that acts as cache and it utilizes the mark ( ) and reset ( ) method. Chunks of bytes from the buffered array can be chosen and read. The BufferedInputStream class maintains an internal array of characters in which it buffers the data it reads from its source. The default size of the buffer is 2048 bytes. A BufferedInputStream is beneficial in certain situation where reading a large number of consecutive bytes from a data source is not significantly more costly than reading a single byte. This class Constructor is overloaded. BufferedOutputStream,

BufferedInputStream bis = new BufferedInputStream (InputStream is); Creates a buffered input stream with a 2048 byte buffer. BufferedInputStream bis=new BufferedInputStream(InputStream is,int bufsize);

341 Creates a buffered input stream with an internal buffer of bufsize bytes. If the bufsize is less than 0 then it throw IllegalArgumentException.

BufferedOutputStream The output is stored in a buffered array of bytes, which acts as a cache for writing. Data written in the buffered output stream will continue until unless the buffer is full. This class Constructor is overloaded. BufferedOutputStream b= new BufferedOutputStream (OutputStream os); Creates a buffered output stream with a default 512 byte buffer. BufferedOutputStream bufsize); b=new BufferedOutputStream(OutputStream os, int

Creates a buffered output stream with a buffer of bufsize bytes. If the bufsize is less than 0 then the program is terminated by throwing IllegalArgumentException. DataInputStream The DataInputStream class reads bytes from another stream and translate them into java primitives, char array and String by the help of some predefined methods. byte readByte()throws IOException boolean readBoolean()throws IOException short readShort()throws IOException char readChar()throws IOException int readInt ( ) throws roException float readFloat()throws IOException long readLong()throws IOException double readDouble()throws IOException String readLine ( ) throws IOException Constructor Is DataInputStream dis=new DataInputStream(InputStream is);

342

DataOutputStream DataOutputStream class supports the writing of javas primitive data types to an output sources. A set of methods exists in this class to write the data to the output source in any primitive data types format. void writeByte(byte b)throws IOException void writeBoolean(boolean b)throws IOException void writeShort(short s)throws IOException void writeChar(char c)throws IOException void writeInt (int i) throws roException void writeFloat(float f)throws IOException void writeLong(long l)throws IOException void writeDouble(double d)throws IOException Constructor is DataOutputStream os) dos=new DataOutputStream(OutputStream

In order to create a simple text file I am going to use FileOutputStream. See the example

Example 15

import java.io.*; class Demo{ public static void main(String[]args)throws IOException { DataInputsteream din=new FileOutputStream fout=new DataInputsteream (System.in); FileOutputStream(myFile.txt);

343 System.out.println(Press # to save & quit the file); char ch; while((ch=(char)din.read())!=#) fout.write(ch); fout.close(); } } System.in represents the standard input device i.e. is key board. din is an object of DataInputStream class. This is what we call a channel or stream. Now din is connected to keyboard. Next fout is an object of FileOutputStream class. It also behaves like a channel. It is connected to the output file myFile.txt. Inside while loop read() method is invoked through the object din. read() method reads the data from keyboard through the channel named din & the returned character value is saved in the character variable ch. Next the write() method is invoked & the stored value in ch is moved to myfile.txt through the out put channel object fout. All these operation continues till # is pressed by the user. Then finally close() method is invoked to close the operation & save the file. How to append a file. If I am again use the file myFile.txt to write something more at the end then the previous data will be lost. So I have to make some change in the above program to append a file.

Example 16

import java.io.*; class Demo{ public static void main(String[]args)throws IOException { DataInputsteream dIn=new FileOutputStream fout=new DataInputsteream(System.in); FileOutputStream(myFile.txt,true);

System.out println(Press # to save & quit the file);

344 char ch; while((ch=(char)din.read())!=#) fout.write(ch); fout.close(); } } See the extra parameter passed in the constructor of FileOutputStream. This boolean true value opens the file in the append mode. Use of BufferedOutputStream: To improve the performance we have to use the buffered output stream. But, the question how the performance is going to be improved? In the above program each time when a character is read from keyboard, is written to the file & each time in the back ground appropriate system call is made to do the operation. This involves a lot of over head. What else we can do? We can create a buffer i.e. a temporary storage area & store the data till the input operation is completed, and then write the entire content of the buffer in to the file at once.

Example 17

import java.io.*; class Demo{ public static void main(String[]args)throws IOException { DataInputsteream dIn=new FileOutputStream fout=new DataInputsteream(System.in); FileOutputStream(myFile.txt);

BufferedOutputStream br= new BufferedOutputStream(fout); System.out println(Press # to save & quit the file); char ch; while((ch=(char)din.read())!=#)

345 bout.write(ch); bout.close(); } } br is an object of BufferedOutputStream. It is buffer or a chunk of memory attached with fout. Now the read method is invoked through the br, so the characters entered from keyboard is store in the temporary buffer br until the buffer is filled or # is pressed. If the buffer is full & user still entering the data, then IOException will be generated. Once input operation is completed then write() method is invoked by bout to write the entire data in to the file at once. Yes, one thing if the programmer does not mention the size of the buffer explicitly then the default size id 512 bytes. Steps to be remembered: 1:Create an input stream object & connect it to keyboard by DataInputsteream dIn=new DataInputsteream(System.in); 2: create an output stream object & connect it to the file where you are going to write some thing by FileOutputStream fout=new FileOutputStream(myFile.txt); 3: create a buffer & attach it to output stream BufferedOutputStream br= new BufferedOutputStream(fout) 4: read from key board by the din.read() method; 5:write to the file by bout.write() method. Reading a file Data stored in a file can be read by the use of FileInputStream object. object by

Example 18

import java.io.*; class Demo{ public static void main(String[]args)throws IOException {

346 FileInputStream fin=new int ch; while((ch=(char)fin.read())!=-1) System.out.print((char)ch); fin.close(); } } Java detects the end of file when it encounters -1. At the end of every file to indicate the end of file OS stores -1. fin is an object of FileInputStream. It is simply an input channel connected to myFile.txt. When read method() is invoked by fin, data is read from the file through the channel fin, stored it in ch & then displayed on the monitor. This process continues till -1 is encountered. Coping the content of one file to another. FileInputStream(myFile.txt);

Example 19

import java.io.*; class Demo{ public static void main(String[]args)throws IOException { FileInputsteream dIn=new FileOutputStream fout=new int ch; while((ch=fin.read())!=-1) fout.write((char)ch); fout.close(); } } FileInputsteream(myFile1.txt); FileOutputStream(myFile2.txt);

347 Codes are straight forward through fin data is read from myFile1.txt 7 through fout data is written in to myFile2.txt. Use of BufferedReader to improve performance Example-20 import java.io.*; class Demo{ public static void main(String[]args)throws IOException { try{ FileInputStream fin=new FileInputStream(myFile.txt);

}catch(FileNotFoundException e){ System.out.println(file does not exists.) return; } BufferedReader br=new BufferedReader(fin); int ch; while((ch=br.read())!=-1) System.out.print((char)ch); fin.close (); } } Here in this program I have used the BufferedReader to improve the performance.

348 Example-21 import java.io.*; public class DataStream { public static void main(String args[])throws IOException { BufferedReader d=new BufferedReader(new InputStreamReader(new FileInputStream("c:/temp.txt"))); DataOutputStream o=new FileOutputStream("C:/temp1.txt")); String line; while ((line = d.readLine())!=null) { String a =(line.toUpperCase ( )); System.out.println(a); o.writeBytes(a+"\r\n"); } d.close(); o.close(); } } Suppose the temp.txt file contains the line Learn java as it is an object oriented language as its content. The output appears as shown below: DataOutputStream (new

349 PushbackInputStream This class is used to read a character from the InputStream and return the same. This is done without disturbing the InputStream. This class allows the most recently read byte to be put back into the stream, as if it had not yet been read.

Constructor:-

PushbackInputStream(InputStream is) PushbackInputStream(InputStream is,int size)

PrintStream

This class is used to write text or primitive data types. Primitives are converted to character representation. This methods of this class are widely used in Java applications. The two methods that are very familiar to us system.out.println( ) and system.out.print ( ). Constructor:PrintStream(String s) PrintStream(OutputStream os) PrintStream(OutputStream os,boolean b)

Serializalization Serialization is the process of writing the state of an object to a byte stream. Serialization is a technique that is required when the programmer want to save the state of the object in a persistent storage area. Later on programmer restore the objects by using the process deserialization. In other wors serialization is a technique of storing object contents into a file.Serializable interface is an empty or marker interface without any members in it. Marking interface is useful to mark the object of a class for special purposes. Static and transient variables are not serialized. Deserialization is the process of reading back the object from the file. By the help of the ObjectInputStram programmer read the object from a stream.

350

Constructor is

ObjectInputStream(InputStream in) throws IOException

Through the object in the serialized objects should be read.

Methods int available()

Description Returns the number of bytes that are available in the input sources. Closes the invoking String. Return the integer representation of the next available byte of input. Returns the Object from the invoking Stream. Skip n number of bytes from the input sources.

void close() int read()

Object readObject()

long skip(long n)

ObjectOutputStream class is used to write objects to a stream.

Constructor is

ObjectOutputStream(OutputStream out)throws IOException

Through the out object the serializable objects are written in the Output sources.

351 Method void close() Description Closes the invoking stream.

void flush() void write(byte b[])

Finalizes the output sources. Writes an array of bytes to the invoking Stream Writes Object obj to the invoking stream.

void writeObject(Object obj)

Example-22 import java.io.*; class Ex1 implements Serializable { int i,j; transient int k; void show(int i,int j,int k) { this.i=i; this.j=j; this.k=k; } } public class Serial { public static void main(String args[])

352 { try{ Ex1 e1=new Ex1(); e1.show(20,30,40); FileOutputStream fos= new FileOutputStream("c:/s1.txt"); ObjectOutputStream oos= new ObjectOutputStream(fos); oos.writeObject(e1); FileInputStream fis=new FileInputStream("c:/s1.txt") ObjectInputStream ois=new ObjectInputStream(fis) ; Ex1 e2=(Ex1)ois.readObject(); System.out.println("Data Is "+e2.i+"\t"+e2.j+"\t"+e2.k); }catch(Exception e) { e.printStackTrace(); } } } ;

Output:-

353 StreamTokenizer Java provides in built method for pattern matching from the data those extracted from input stream. The pattern matching is done by breaking the Inputstream in to tokens which are later delimited by a set of characters. Example-23 import java.io.*; public class wordcounter { public static void main(String args []) throws IOException { FileReader fr=new FileReader("c:/temp.txt"); StreamTokenizer input=new StreamTokenizer(fr); int tok; int count=0; while((tok=input.nextToken())!=input.TT_EOF) { if(tok==input.TT_WORD) System.out.println("word found :" +input.sval); count++; } System.out.println ("found "+count + " words in temp.txt"); } }

354

StringTokenizr define four integer fields named TT_EOF, TT_EOL, TT_NUMBER & TT_WORD. There exists another variable ttype, the token recognizing variable. Ttype is equal to TT_WORD if nextToken() method recognizes the element as word. If the element is a nuber then ttype is equal to TT_NUMBER. If the token is a simple character then ttype contains the value of that character. If the element is end of line then ttype is equal to TT_EOL. Similarly when end of file is reached ttype is equal to TT_EOF. Reader and Writer Classes The difference between readers and input stream is that while readers are able to read characters. Input streams read bytes. This increases the power of the java iosteream classes by being able to read any character and thus enabling internalization. To say it in simple terms, it is possible to write Java programs in languages like German, French, Japanese, etc. The functionality of the writers is writers is similar to the output streams and it is possible to write one block of bytes or characters. Following section deals with a few subclasses of reader and writer classes. Reader Class Some of the subclasses of reader class are:

355

Reader

BufferedReader

CharArrayReader

FilterReader

InputStreamReader

PipedReader LineNumberReader

StringReader

FileReader

PushbackReader

FileReader The FileReaer class enables reading character files. It uses default character encoding. FileReader class usage is similar to FileInputStream class and its constructors are identical to those of FileInputStream class. The constructors are identical to those of FileInputStream class. The constructor is given below; public FileReader(File f) This constructor can throw a FileNotFoundException. CharArrayReader The CharArrayReader Allows the usage of a character array as an InputStream. The usage of CharArrayReader class is similar to ByteArrayInputStream. The constructor is below: CharArrayReader(char c[]) CharArrayReader(char c[], int start, int num) InputStreamReader The InputStreamReader class reads bytes from an input stream and converts them to characters according to a mapping algorithm. The default mapping identifies bytes as common ASCII characters and converts them to Javas Unicode characters. The constructor is given below: public InputStreamReader (InputStream istream) FilterReader

356

The FilterReader class allows the reading of filtered character streams. There is one instance variable in, which is a protected reference to the reader that is being filtered. Protected FilterReader (Reader r) BufferedReader BufferedReader class accepts a Reader object as its parameter and adds a buffer of characters to it. This class is mainly useful because of its readLine ( ) method. public BufferedReader(Reader r) Writer Class A few of the subclasses of the Writer class are:

Writer

BufferedWriter

CharArrayWriter

FilterWriter

OutputS treamWriter

PipedWriter

PrintWriter

StringWriter

FileWriter

Reader work exclusively with 16-bit chars, designed for Unicode:

FileWriter The FileWriter allows wrting character files. It uses the default character encoding and buffer size. The usage of FileWriter class is similar to that of FileOutputStream class. The constructor is given below and it can throw an IOExeception. public FileWriter (File f) Example-24 import java.io.*; public class FileRead { public static void main(String ars[])

357 { try{ BufferedReader br=new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter The Text"); String s=br.readLine(); char c[]=s.toCharArray(); FileWriter fw=new FileWriter("File1.txt"); fw.write(c); fw.close(); System.out.println("Read The Data From The File"); FileReader fr=new FileReader("File1.txt"); int ch; while((ch=fr.read())!=-1) { System.out.print((char)ch); } fr.close(); }catch(Exception e) { e.printStackTrace(); } } } Output:-

CharArrayWriter This class uses character array as the OutputSource. The constructor of the class is overloaded. CharArrayWriter() CharArrayWriter(int num) PrintWriter

358 The PrintWriter class contains methods that makes the generation of formatted output simple. It can be used instead of PrintStream. The constructor is: public PrintWriter ( OutputStream ostream ) The stream is not flushed each time the printIn( ) method is called. FilterWriter The FilterWriter class is used to Write filtered character streams. It has one instance variable out, which is a protected reference to the Writer that is being filtered. protected Filter(Writer w) BufferedWriter The BufferedWriter class buffers data to the character output stream. BufferedWriter class functionality is the same as BufferedOutputStream class The constructor is: public Buffered (Writer w)

Example-25 import java.io.*; public class ReadWrite { public static void main (String arge []) { try { BufferedReader in=new BufferedReader(new FileReader(arge[0])); String s1=""; String s2="Learn Java"; while((s1=in.readLine())!=null) System.out.println(s1); StringReader in2=new StringReader(s2); int c; System.out.println("printing individual1 charcters of the File"+arge[0]); while((c=in2.read())!=-1) System.out.print((char)c); BufferedReader ind=new BufferedReader(new StringReader(s2)); PrintWriter p=new PrintWriter(new BufferedWriter(new FileWriter("demo.txt"))); while((s1=ind.readLine())!=null)

359 p.println("output "+s1); in.close(); in2.close(); ind.close(); p.close(); }catch(Exception e) { e.printStackTrace(); } } }

Use of FileReader & FileWriter class. FileReader & FileWriter class is performs the read & write operation by characters. Program to write something in to a file. Example-26 import java.io.*; class Demo{ public static void main(String[]args)throws IOException { String data=On this planet\n Life is like ships in the harbor!!!

360 FileWriter fw1=new FileWriter(myFile.txt); for(int i=0;i<data.length();i++) fw1.write(data.charAt(i)); fw1.close(); } }

Reading from a file by FileReader Example-27 import java.io.*; class Demo{ public static void main(String[]args)throws IOException { try{ FileReader fr1=new Filereader(myFile.txt); }catch(FileNotFoundexception e) { System.out.println(file does not exist); return; } int ch; while((ch=fr1.read())!=-1) System.out.println((char)ch); fr1.close(); }} -

361 Chapter-22 Exploring The java.lang Package

java.lang is the fundamental package that is available to the programmer by default. You do not import this package to use the classes, interfaces & methods available in this package. In fact this is the package that is widely used all java programmer.

Various classes present in java.lang package Java.lang package has following classes: Boolean,, Byte, Character, Character.Subset, Character.UnicodeBlock, Class, ClassLoader, Compiler, Double, Enum, Float, InheritableThreadLocal, Integer, Long, Math, Number, Object, Package, Process, ProcessBuilder, Runtime, RuntimePermission, SecurityManager, Short, StackTraceElement, StrictMath, String, StringBuffer, StringBuilder, System, Thread, ThreadGroup, ThreadLocal, Throwable, Void. Interfaces present in java.lang Appendable, Comprable, Runnable, CharSequence, Iterable, Cloneable, Readable. It is not possible to explain each class & methods present in java.lang package & it is also beyond the scope of this book. I am going to explain the most frequently used & important classes their methods present in this package. Boolean This is a wrapper class. This class is used to create the object of primitive data-type boolean. This class is explained in the chapter Wrapper class. Byte This is another Wrapper class. This class is used to create the object of primitive data-type byte. This class is explained in the chapter Wrapper class. Character This is another Wrapper class. This class is used to create the object of primitive data-type byte. This class is explained in the chapter Wrapper class. Charcter.Subset This class is static inner class. This class extends the Object class. This class is enclosed by the Wrapper class Character. The signature of this class is public static class Charcter.Subset extends Object. Character.Unicode

362 This class is also a static inner class. Its outer class is Character. This class can not be extended since it is declared with final keyword. This class extends the Character.Subset class.

Class The class Class extends the object class & implements the Serializable interface. This class is a final class, hence can not be extended. It does not contain any public constructor. In java all the arrays including arrays of primitive data types are created by the invocation of the new operator, just like creation of object. Actually java implements these arrays as the reflection of the object of class Class. This class is instantiated only by Java Virtual Machine during the process of class loading by the invocation of the defineClass() method. This class is generic in nature. You can create the object of this class by the invocation of getClass() method. This method getClass() originally belongs to the Object class & is over-ridden in this class Class. The getClass() & getName() methods: the two methods are invoked together to determine the class name of an object. Lets have an example class Demo { public static void main(String[]args) { Class cl="Hello World".getClass(); System.out.println("The string is an object of "+cl.getName()); cl=System.out.getClass(); System.out.println("out is an object of "+cl.getName());

} } Output: The string is an object of java.lang.String out is an object of java.io.PrintStream In this above program cl is a refernce of class Class. As I have said object of the class Class can not be created directly. The getClass() method returns the name the class, whose object has invoked it. First the getClass() method is invoked by he String object. Hence cl holds the String class. now getName() method simply shows the name of the class that is held by cl. There is another method getSuperClass(), which is used to determine the current super class of the class held by the reference variable of class Class. Now lets find out what is the class name to which arrays of primitive data types in java belongs to class Demo {

363 public static void main(String[]args) { float mak[]=new float[8]; Class cl=mak.getClass(); System.out.println(cl.getName()); } } Output: [F Foxed! With the out put. The [ indicates that mak is an array. If mak would be two dimensional array then initial symbol would be [[. Next symbol F indicates mak is an array of float of single dimension. For other primitive data types the symbols are Boolean Z byte B char C class or interface Lclassname double D float F int I long J short S The forName() method & the newInstance() method. package demo; class X{ int i=10; } class Demo { int i=10; public static void main(String[]args) throws InstantiationException,IllegalAccessException,ClassNotFoundException { X b=new X(); Class cl=Class.forName("demo.X"); X a=(X)cl.newInstance(); System.out.println(a.i); } } Output: 10 forName() method is a static method, there fore it has to be invoked by its class name Class. Its signature is

364 public static Class forName(String className) throws ClassNotFoundException Hence it has to be invoked inside try block or throws keyword has to be used. This method returns the Class object that holds the class supplied as a string argument to this method. Previous to this you know that to create an object of a class you need to call the constructor of this class through new operator. But, the method newInstance() can invoked to create the object of the class that is held by cl. The signature of newInstance() method is public Object newInstance() throws InstantiationException, IllegalAccessException Therefore this method has to be invoked inside a try block followed by a catch block or by the use throws keyword. ClassLoader ClassLoader is a abstract class which extends the Object class. in java a class is loaded in to the memory either by boot strap class loader or by user defined class loader. Boot strap class loader is an component of Java Virtual Machine. When a class file is executed by javac command, the boot strap class loader is responsible for loading the class in to the memory. The class ClassLoader is used to create the user defined class loader. Rarely a java programmer requires an user defined class loader. Compiler class When you compile a java source file .class file is created. By the use compiler class native executable files can be generated from java source file. This class can not be extended. This class extends the Object class. This cass is rarely used by the java programmer. Double This is another Wrapper class. This class is used to create the object of primitive data-type byte. This class is explained in the chapter Wrapper class. Enum class This class is used to create the Enum object. Enum members are simple constants. Float This is another Wrapper class. This class is used to create the object of primitive data-type byte. This class is explained in the chapter Wrapper class. Integer This is another Wrapper class. This class is used to create the object of primitive data-type byte. This class is explained in the chapter Wrapper class. Long This is another Wrapper class. This class is used to create the object of primitive data-type byte. This class is explained in the chapter Wrapper class. Process class & Runtime class These two classes are closely entangled with each other. Java programmer use these two classes frequently to develop system level applications.

365 First of all Process is an abstract class. All the methods present in this class is abstract class. The signature of the Process class is : public abstract class Process extends Object. Since it is an abstract class you can not directly create the object of Process class. For this purpose normally the exec() method of Runtime is used. A Process object embeds a process in to it. The object of a Runtime class contains the current system environment. To instantiate Runtime class you have to invoke the getRuntime() method. It is a static method. Hence it is invoked by the class name Runtime. package demo; class X{ int i; } class Demo { public static void main(String[]args) { Runtime rt=Runtime.getRuntime(); long Initial,Final; Initial=rt.freeMemory(); //This method retuns the amount of free memory available. System.out.println("Available memory initially: "+Initial); X mak[]=new X[10000]; Final=rt.freeMemory(); System.out.println("Available memory after the creation of object: "+Final); long s=(Initial-Final)/10000; System.out.println("Available free memory: "+s); rt.gc(); //gc () method is used to invoke the garbage collector. System.out.println("Available free memory:"+rt.freeMemory());

} } Output: Available Available Available Available

memory initially: 1872280 memory after the creation of object: 1832264 free memory: 40016 free memory:1875168

One question may arise in your mind is why such a large array? This is because by creating a large array appreciable change in the free memory is reflected. Normally while training new comers in java a usual question from their side is how to measure the size of an object in java. Since they all are migrated from C/C++, they do miss the sizeof operator quite a lot. Java does not provide the sizeof operator but, you can determine the size of an object through various methods available in Runtime class. Determining the size of primritive data type char

366 class Demo { public static void main(String[]args) { Runtime rt=Runtime.getRuntime(); long Initial,Final; Initial=rt.freeMemory(); char mak[]=new char[10000]; Final=rt.freeMemory(); long s=(Initial-Final)/10000; System.out.println("Size of the object is "+s); } } Output: Size of the object is 2 Similarly to determine the size of int class Demo { public static void main(String[]args) { Runtime rt=Runtime.getRuntime(); long Initial,Final; Initial=rt.freeMemory(); int mak[]=new int[10000]; Final=rt.freeMemory(); long s=(Initial-Final)/10000; System.out.println("Size of the object is "+s); } } Output: Size of the object is 4 To get the size of double class Demo { public static void main(String[]args) { Runtime rt=Runtime.getRuntime(); long Initial,Final; Initial=rt.freeMemory(); double mak[]=new double[10000]; Final=rt.freeMemory(); long s=(Initial-Final)/10000; System.out.println("Size of the object is "+s); } } Output: Size of the object is 8 Use of exec() method to execute system dependent application. Suppose we are in a window system then the bellow codes will open ms paint for you. package demo;

367 class Demo { public static void main(String[]args)throws Exception { Runtime rt=Runtime.getRuntime(); Process p=rt.exec("mspaint"); } } Output:

The System class

368 This class contains a large number static methods & variables. You can not crate the object of System class. You can not create the sub class of System class. The getProperty() method This method takes various types of environment properties defined by the java.lang package. Some of the examples will fix your idea. This method is a static method. Hence can only be invoked through class name Determining the Os in which you are working package demo; class Demo { public static void main(String[]args) { String S=System.getProperty("os.name"); System.out.println(S); } } Output: Windows XP This particular method can be used to create single class file which will operate in different plat form differently. public class Os { public static void main(String args[]) { String s=new String( System.getProperty("os.name")); Runtime r=Runtime.getRuntime(); Process p=null; try { if(s.equals("Linux")) { p=r.exec("gedit"); } if(s.equals(Windows XP)) { p=r.exec("notepad"); } } catch(Exception ie) {} } } If you run this program in windows plat form, it will open the note pad & if in Linux platform it will open the gedit. I have run this program in windows platform see the output:

369

The arrayCopy() method When you copy an array, you do it by loop. This process can be completed by the use of arrayCopy() method in a more efficient way. package demo; class Demo { public static void main(String args[]) { char mak[]={'r','o','o','t',' ','l','e','s','s',' ','a','g','g','r','e','s','s','i','o','n'}; char arr[]=new char[mak.length]; System.arraycopy(mak, 0,arr, 0, mak.length); for(int i=0;i<arr.length;i++) System.out.print(arr[i]);

370 }} Output: root less aggression this method takes the source array as its 1st argument, next argument is the position from which the source has to be copied, 3rd one is the name of the destination array, 4th one is the position of the destination array from which the copy process begins & final one is the length of the source array up to which the data has to be copied. The ThreadLocal class The ThreadLocal variables are typically declared as private and static. Whenever programmer feels that some data should be unique for the thread and the data should not be shared, then ThreadLocal variables are used. Every individual thread has a separate copy of the variable that means any change done to the ThreadLocal variable by a thread is totally private to it . It is not going to reflect in any other thread. Below given is the structure of ThreadLocal<T> class defined in java.lang public class ThreadLocal<T> { protected T initialValue( ); public T get( ); public void set(T value); public void remove( ); } protected T initialValue() it returns the intial value for the ThreadLocal variable of the current thread . whenever we access the variable with the get() method for the first time the initialValue() method is called implicitly. If the set() method is invoked prior to the get() method then the initial value method will not invoked. public T get() it returns the value of the copy of the thread-local variable present in the current thread. Creates and initializes the copy if it is called for the first time by the thread then it creates and initializes the copy of the variable. public void set(T value)

371 it sets the copy of the thread-local variable of the current thread to the specified value. public void remove() it removes the value of the ThreadLocal variable.after removing the value if we will again invoke the get method then it will again call the initialValue method and will intialise the value of the ThreadLocal variable.

class ThreadLocalDemo1 extends Thread {

private static int number = 0; private static ThreadLocal threadnumber = new ThreadLocal() { protected synchronized Object initialValue() { return number++; } };

public void run(){ System.out.println("Thread " + Thread.currentThread().getName() + " has thread number " + threadnumber.get()); number++; System.out.println("Thread " + Thread.currentThread().getName() + " has thread number " + threadnumber.get()); threadnumber.set(5); System.out.println("Thread " + Thread.currentThread().getName() + " has thread number " + threadnumber.get()); threadnumber.remove(); System.out.println("Thread " + Thread.currentThread().getName() + " has thread number " + threadnumber.get()); threadnumber.remove(); System.out.println("Thread " + Thread.currentThread().getName() + " has thread number " + threadnumber.get());

public static void main(String[] args) {

372 Thread t1 = new ThreadLocalDemo1(); Thread t2 = new ThreadLocalDemo1(); t1.start(); t2.start(); }

Output : Thread Thread Thread Thread Thread Thread Thread Thread Thread Thread Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 has has has has has has has has has has thread thread thread thread thread thread thread thread thread thread number number number number number number number number number number 0 0 5 2 3 4 4 5 6 7

Cloneable interface:The Cloneable interface is present inside the java.lang package, is used to create the clone of an object. The signature of Cloneable interface is: public interface Cloneable { }

The Cloneable interface does not contain any method of its own.To clone an object, a class must implement the interface Cloneable and then invoke the clone () method of object class. The signature of the clone () method is: protected native Object clone() throws CloneNotSupportedException According to the specification, the clone () method returns the reference of the Object class.

373 Example:-

public class LetsClone implements Cloneable {

int roll; String name=new String();

F(int i, String c) { roll=i; name=c; }

public static void main(String ar[]) throws CloneNotSupportedException { F obj=new F(10,"pinku"); F ob=(F)obj.clone();

System.out.println(ob.roll); System.out.println(ob.name); } } Output: 10 pinku

374

The Cloneable interface is a marker interface. A marker interface is an interface, which does not have its own method. But for certain operations, their implementation is a must. Actually implementing the marker interface programmer implicitly let the JVM to know that a specific operationnis going to be performed. The marker interfaces present inside java are:  Java.lang.Cloneable  Java.io.Serializable  Java.util.EventListener To clone one object, the clone() method of the Object class is needed. But, we need to implement the Cloneable interface (i.e. a marker interface) to facilitate the class with the ability for cloning it objects. Object class:In java Object class is the super class of all the classes. Many of its methods are over ridden in different java in built classes according to their purpose. Methods present in Object class:Object clone() I have used this method in creating clone of an object. This method belongs to Object class. boolean equals(Object eq) this method is explained in detail in String chapter. void finalize() This method is called before an object is garbage collected from heap. This is explained in detail in class fundamental. Class getClass() Already explained earlier in this chapter. int hashCode() Explained in detail in object reference & string chapter. Most of the methods of this class is explained in detail in various chapters of this book. Reader can go through them.

Math class The Math class contains various methods that are usefull scientific & engineering applications. It contains two double constansts: E(the exponential c constant) (~2.72) and PI (~3.14).

375 Methods in Math class:public static double sin(double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the measurement of an angle in radian. It returns the sine value of the supplied angle public static double cos(double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the measurement of an angle in radian. It returns the cosine value of the supplied angle. public static double tan(double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the measurement of an angle in radian. It returns the tangent value of the supplied angle. See the below exapmple public class Arithm1 { public static void main(String arg[]) { double dbl1= 30; double dbl2 = Math.toRadians (dbl1); System.out.println(" The angle in radians is : " + dbl1); System.out.println(" sine of +dbl1+ is : "+ Math. sin(dbl2) ); System.out.println(" cosine of +dbl1+ is : "+ Math. cos(dbl2) ); System.out.println(" tangent of +dbl1+ is :"+ Math.tan(dbl2)); } } Output: The angle in radians is : 30.0 sine of +dbl1+ is : 0.49999999999999994 cosine of +dbl1+ is : 0.8660254037844387 tangent of +dbl1+ is :0.5773502691896257 public static double asin (double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the sine value of an angle. It returns the angle in radian. Range is in between /2 to /2

public static double acos (double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the cosine value of an angle. It returns the angle in radian. Range is in between 0 to

376

public static double atan (double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the tangent value of an angle. It returns the angle in radian. Range is in between 0 to

public class Arithm2{ public static void main(String arg[]) { double dbl=0.5; System.out.println("Enter Value is :"+dbl); System.out.println("The angle for which the sine value is 0.5 is :"+Math.asin(dbl)); System.out.println("The angle for which the cosine Value is : " + Math. acos(dbl) ); System.out.println("The angle for which the tangent Value is : " + Math.atan(dbl) ); } } Output: Enter Value is :0.5 The angle for which the sine value is 0.5 is :0.5235987755982989 The angle for which the cosine Value is : 1.0471975511965979 The angle for which the tangent Value is : 0.4636476090008061

public static double toRadians(double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the measurement of an angle in degree. It returns the equivalent angle in radian. public static double toDegrees(double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the measurement of an angle in degree. It returns the equivalent angle in degree.

class Demo { public static void main (String arg[]) { System.out.println("the radian value is :"+Math. toRadians(90.0)) ; System.out.println("Degree value is:"+Math.toDegrees(1.571)) ; System.out.println("Tangent value of two parameters is: "+Math. atan2(30.00,30.00));

377 System.out.println(" The log value is :"+Math. log(35.0)); System.out.println("The Exponent value is :"+Math.exp(30.00)); }

}output: the radian value is :1.5707963267948966 Degree value is:90.01166961505233 Tangent value of two parameters is: 0.7853981633974483 The log value is :3.5553480614894135 The Exponent value is :1.0686474581524463E13

public static double exp(double dbl) This method is a static method; hence can only be invoked by class name. It takes a double variable as its argument. This argument is the tangent value of an angle. It returns the angle in radian. Range is in between 0 to  public static double log (double dbl) The log method has only one double value i.e. dbl as the parameter. This method returns the natural logarithm (base e) of a double value.  public static double sqrt (double dbl) Here, the sqrt method has only one double value dbl as the parameter and it returns the square root of the given value dbl. When the argument is NaN or less than zero , the result is NaN.

 public static double IEEEremainder(double dbl1, double dbl2) This method used to calculate the remainder operation on two arguments. This method having two parameters i.e. dbl1(the dividend) and dbl2(the divisor).Here it returns the remainder when dbl1 is divided by dbl2.

 public static double ceil(double dbl) This ceil method has only one double value i.e.dbl which is taken as parameter. According to this method the given double value returns the smallest double value which is not less than the argument and is equal to a mathematical integer.  public static double floor(double dbl)

378 This floor method having only one double value dbl as the parameter. This method returns the largest double value which is not greater than the argument and is equal to a mathematical integer.

 public static double rint(double dbl) This rint method containing only one double value dbl as the parameter. It returns the closest double value to that dbl and is equal to a mathematical integer. If two double values that are equally close to the value of the argument, it returns the integer value that is even.  public static double atan2 (double dbl1, double dbl2) Here there are two double values dbl1 and dbl2.These are the parameters for this method. The given rectangular coordinates (dbl2, dbl1) is converted to polar (r, theta) by this method. This method also computes the phase theta by computing an arc tangent of dbl1/dbl2 in the range of pi to pi.  public static double pow(double dbl1,double dbl2) Here two double values dbl1 and dbl2 which are taken as the parameters for this method. This method returns the value of the first argument which is raised to the power of the second argument. if (dbl1==0.0) ,then dbl2 must be greater than 0.0, Otherwise it throws an exception . An exception can also arise if(dbl1<=0.0) , dbl2 not equals to a whole number. class Arithm4 { public static void main (String arg[] ) { System.out.println("The square root value is :"+Math.sqrt( 25)); System.out.println("\ nThe remainder of 5 divided by 2 is:"+Math.IEEEremainder(5,2)); System.out.println("\ n The ceil value is : "+Math. ceil(5.6)); System.out.println("\ n The floor value is:"+Math. floor(5.6)); System.out.println("\ n The power value is :"+Math. pow (5.0,2.0)); System.out.println("\ n"+"The rint value is :"+Math.rint(30.6)); }}

Most of the methods of math class is static in nature. Their name clearly indicates their task. I hope reader can google through them & can get them quite easily. Conclusion: Java.lang package is the only package that is available to the programmer by default. java.lang provides quite a lot utility tools to the programmer. Recently added interfaces like Instrumentation has increased the scope of this package. This package is going to be the premier package of java programming language forever.

379

Chapter-23 The collection frame work Introduction I must say this is the most important package developer. If you are familiar with C++, as you can feel that Collection Frame work of java Standard Template Library (STL) of C++. But same. Java Collection Frame Work is quite rich. & extensively used by java go through the chapter you shows similarity with the things are entirely not the

The Collection class object is used to store, manipulate & retrieve objects by the implementation of various data structures like normal array, linked list, trees, stack, queue, hash-table etc. Advantages of the Collection framework:  By the help of useful data-structures and algorithms provided by this framework we can effectively reduce the effort of programming.  Increases program speed and quality since the implementation of each interface are interchangeable.  It allows inter operability among unrelated APIs.  Extending or adapting a collection is easy.  It reduces the effort in designing new APIs.  Encourage software reuse since the Interfaces and algorithms are reusable.  It can interface the core Collection Interfaces which will be effective to achieve different operations on Collections and we can also pass them from one method to another effectively.  By the help of the aforesaid interfaces we can manipulate the collections independently irrespective of their underlying representations. Here in most of the programs I have used the generic constructor of the corresponding class since generic provides type safety.

The for-each loop Before starting our voyage in to the util package its the time now to explain another version of looping the for each loop. This loop is particularly use full when you deal with arrays or in general you might say when you deal with collection of object. Lets have a simple program:

380

class Demo { public static void main (String arg[]) { int mak[]=new int[8]; for(int i=0;i<8;i++) { mak[i]=i; } for(int j:mak) { System.out.println(j); } }

} Output: 0 1 2 3 4 5 6 7 The statement that troubles you for(int j:mak) { System.out.println(j); } Let me explain. mak is the array name & the array is the array of integers. Each element stored in mak is of primitive data type int. when 1st time the statement int j:mak is encountered in side for loop, java assigns the 1st element present in mak to j, 2nd time when the same statement is encountered in side for loop 2nd element is assigned to j. this process continues until the last element assigned to j. after that the loop automatically terminates. This loop maintains a higher level of abstraction. You can try this for an array of user defined class. Set interface The Set interface extends the Collection interface. But, the Set interface never gives permit to have duplicate element with in the set object. The set interface does not define any method of its own. It uses only the methods of the Collection interface. It adds restriction on the add ( ) method since it

381

returns false if the user tries to include duplicate elements added to a Set. It also adds restriction on the equals( ) and hashcode( ) methods. SortedSet Interface The SortedSet interface extends to the Set interface. Java defines a natural ascending order principle for this interface.If the current set does not contain any element, then most of the methods present in this interface throws the NoSuchElementException. If any object is not compatible with the elements that are present in Set then an exception known as ClassCastException is thrown. Null object can not be used in this interface other wise NullPointerException will be generated.  Comparator comparator():This method returns the comparator of the current SortedSet. This method returns null if the set using the default ordering principle of Java.

 Object first( ):This method is used to return the first element of the current SortedSet to the caller of the method.  SortedSet headSet(Object ss ):This method returns a SortedSet that contains elements less than the object ss from the current SortedSet.  Object last ( ):The purpose of using this method is to return the last element of the current SortedSet to the caller.  SortedSet subSet(Object ss1, Object ss2 ):The job of this method is to return a SortedSet reference consisting of elements between the object ss1 and the object ss2, which behave like two end points.  SortedSet tailSet(Object element):This method is used to return a SortedSet reference. Which contain elements those are greater than or equal to the current SortedSet object through which it is invoked. List Interface:The List interface extends the Collection Interface. It is an ordered Collection. This Collection has the permission to contain duplicate elements. Elements can be inserted into the list or accessed from it through their integer index in the list. Including the methods of Collection interface, the List interface has some of its own methods. Brief descriptions of the methods are given below:

382

 void add(int index, Object l):This method inserts the Object l into the current list at the position specified by index. The preceding elements(if any) are shifted up in the list.  boolean addAll(int index,Collection cls):This method is used to add the elements of the given Collection cls to the current list at the position specified by index. The preceding elements(if any) are shifted up in he list.  Object get(int index):This method is used to return the object stored at the position specified by the index, within the current collection.  int indexOf(Object li) This method is used to find out the object li in the current list and returns the index of its first instance. If the object li is not found to be an element of the concerned list, then -1 is returned.  int lastIndexOf(Object li):This method is used to search for the object li in the current list and returns the index of its first instance. If the object is not found in the concerned list, then -1 is returned to the caller.  ListIterator listIterator( ):It returns an iterator to the start of the current list.  ListIterator listIterator( int index):By the help of this method an iterator for current list is returned, that begins at the position specified by the given index.  Object remove(int index):This method is used to erase the element found at the position as specified by index, from the current list.  Object set(int index,Object a):It assign a to the position specified by index in the current list.  List subList(int starting, int ending):It returns a list that includes elements from the position specified by starting to the position specified by ending -1 in the current list. The methods of the interface can be categorized into methods used for Positional Access, Search, List Iteration and Range-view. The get(), set(), add(), remove() and addAll() methods are the methods used for Positional Access. The indexOf and lastindexOf methods are used for search. The two listIterator methods are used for iteration. The sublist method is the Range-view method.

Implementations

383

Implementation (or classes) is the actual objects used to store the collections. Some of these classes provide the full implementation and can be used right away, whereas, the others are abstract and are used as starting points for creating concrete collections. The important standard collection classes are as follows:AbstractCollection : AbstractCollection is a class which helps to provide a skeletal implementation of the Collection interface. In order to implement an un-modifiable collection, we have to extend the AbstractCollection class and provide the implementation logic for the methods like Iterator() and size(). On the other hand, if we need to implement a modifiable collection, the add() method has to be overridden. In this case, the remove method is implemented by the Iterator returned by the iterator() method. AbstaractList : The AbstaractList class extends the AbstractCollection class and provides a skeletal implementation of the List interface. The implementation of an un-changeable list requires the extension of this class and then we have to provide implementations for the get and size methods. To implement a modifiable list, the set and remove methods are to be overridden. AbstractSequentialList :AbstractSequentialList is a class which extends to the AbstractList class. It is an implementation of the List interface. By the help of this class a sequential access can be carried over the collection elements. In order to implement a list, we have to extend the AbstractSequentialList class and define the implementations for the listIterator() and size() methods. LinkedList : LinkedList is a class which extends the AbstractSequentialList class and implements the interface List. All the optional list operations are to be implemented by this class. For the implementation of the List interface, similar named methods have been provided for the operations like get, remove and insert an element at the beginning and at the end of the list. ArrayList:

384

ArrayList is a class which extends the AbstractList class and implements the List interface. ArrayList is serializable. In addition to that, there are methods with which we can manipulate the size of the array that is used to store the list internally. AbstractSet : AbstractSet is a class which extends the AbstractCollection class and provides the skeletal implementation of the Set interface.The implementations from the AbstractColllection class are not overridden in this class. It only used to add implementations for equals and hashcode methods. HashSet : HashSet is a class which extends the AbstractSet class and implements the Set interface. HashSet class have a hash table associated with it. The time complexity for various operations to be performed on the HashSet is almost constant.

The ArrayList class ArrayList class is used to create dynamic arrays that means the object of this class grows & shrinks as you add new elements to it or you remove elements from it respectively. This class is a generic class. This class implements the List interface & extends the AbstractList class. package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>(); System.out.println("Initially size of the array:"+arrX.size()); for (int j=0;j<5;j++)

385

{ X a=new X(); a.i=j; arrX.add(a); } System.out.println("now size of the array "+arrX.size()); for (int j=0;j<5;j++) { X a=new X(); a.i=j+5; arrX.add(a); } System.out.println("Finally the array size "+arrX.size()); for(X a:arrX){ System.out.println(a.i); } }

} Output: Initially size of the array:0 now size of the array 5 Finally the array size 10 0 1 2 3 4 5 6 7 8 9 I have already said ArrayList class is a generic class. Its signature is Class ArrayList<Claass_Nmae>. Programmer specifies the name of the class whose ArrayList has to be created. Here arrX is an object which can contain the object of class X. In the above program I have supplied the class name X to create the ArrayList of class X. To get the number of elements that is stored in the ArrayList, the size() method has to be invoked by the corresponding of ArrayList class. Object of ArrayList is some thing like container. Here arrX is an object which can contain the object of class X. So

386

how to add a new element to this container? 1st create an object X. call the add() method through the object of ArrayList & pass the object of X to be added. The signature of add() method is boolean add(A object). If add() method is successfully executed then boolean true value is returned else false will be returned. Actually this add() method belongs to List interface which is implemented in ArrayList class, hence add() method is over-ridden there. To determine the length of arraylist the size() method is used, which returns the size of ArrayList object. Its return type is integer. ArryList constructors are 1:ArrayList()a zero argument constructor to create an empty array & the array grows as you add new element to it. 2:ArraList(int initial_size) this constructor is used to create an array having length of initial_size supplied by the programmer & the size grows as new element is added to it. 3:ArryList(Collection<? Extends T>c) this constructor used to create an array which can hold the object of T or the object of the subclass of T. lets have an example package demo; import java.util.*; class X{ int i; void show() { System.out.println(i); } } class Y extends X{ int j; void show() { System.out.println(j); } } class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>(); System.out.println("Initially size of the array:"+arrX.size()); for (int j=0;j<5;j++) { X a=new X(); a.i=j; arrX.add(a);

387

} System.out.println("now size of the array "+arrX.size()); for (int j=0;j<5;j++) { Y a=new Y(); a.j=j+5; arrX.add(a); } System.out.println("Finally the array size "+arrX.size()); for(X a:arrX){ a.show(); } }

} Output: Initially size of the array:0 now size of the array 5 Finally the array size 10 0 1 2 3 4 5 6 7 8 9 If you have got the concept of inheritance then the output here is straight forward. Deletion an Object from ArrayList In order to remove an object from ArrayList you have to invoke the remove() method. Just pass the index number of the element that you want to remove from the ArrayList. Program below will fix your idea. package demo; import java.util.*; class X{ int i; void show() {

388

System.out.println(i); } } class Y extends X{ int j; void show() { System.out.println(j); } } class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>(); System.out.println("Initially size of the array:"+arrX.size()); for (int j=0;j<5;j++) { X a=new X(); a.i=j; arrX.add(a); } System.out.println("now size of the array "+arrX.size()); arrX.remove(4); for (int j=0;j<5;j++) { Y a=new Y(); a.j=j+5; arrX.add(a); } System.out.println("Finally the array size "+arrX.size()); for(X a:arrX){ a.show(); } }

} Output: Initially size of the array:0 now size of the array 5 Finally the array size 9 0 1

389

2 3 5 6 7 8 9 Another version of remove() method: here you can directly pass the object to be removed from ArrayList as an argument of remove() method. see the example below. package demo; import java.util.*; class Demo { public static void main (String arg[]) { ArrayList<String> arrX=new ArrayList<String>(); arrX.add("Eureca"); arrX.add("Dasvidania"); arrX.add("Minerva"); arrX.add("HitMan"); arrX.add("Vendeta"); for(String s:arrX) { System.out.println(s); } arrX.remove("Dasvidania"); System.out.println("After deletion"); for(String s:arrX) { System.out.println(s); } } Output: Eureca Dasvidania Minerva HitMan Vendeta After deletion Eureca Minerva HitMan Vendeta

390

See that the string object that is to be removed from the ArryList passed as an argument remove() method.

The LinkedList Class First of all LinkedList is a generic class. It provides the linked list data structure to store & manipulate the data. package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { LinkedList<X> linkedL=new LinkedList<X>(); for(int i=0;i<5;i++) { X a=new X(); a.i=i; linkedL.add(a); } X a=new X(); a.i=100; linkedL.addFirst(a); for(X b:linkedL) { System.out.println(b.i); } } }

Output: 100 0 1 2 3

391

4 To add a new element at the beginning of LinkedList object you have to invoke the addFirst() method which takes the argument of the object that is to be added at the beginning of the list. Similar is the job of another method offerFirst(). See the use of for each loop to extract the elements present in the LinkedList object. The remove() method discussed in ArrayList class can be invoked in LinkedList to perform the similar task. See the for-each loop used here to retrieve the element from LinkedList object.

Retrieving particular element from the LinkedList object. get() method is used to get the stored elements. This method takes index number as its argument & returns the object stored at that postion in the LinkedList object. import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { LinkedList<X> linkedL=new LinkedList<X>(); for(int i=0;i<5;i++) { X a=new X(); a.i=i; linkedL.add(a); } for(int i=0;i<5;i++) { X a=linkedL.get(i); System.out.println(a.i); } }} Output: 0 1 2 3 4

392

Here get() method is invoked by the object of LinkedList & returns the object of class X. Some other methods addLast() or offerLast() method is used to add an element at the end of LinkedList object. To add a particular element at a specific location you can use add(int,E) method. The position where to insert an element is supplied as the first argument to this method. set() method is used to change an entity stored in the LinkedList object in the specified location.

Now lets have an example import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { LinkedList<X> linkedL=new LinkedList<X>(); for(int i=0;i<5;i++) { X a=new X(); a.i=i; linkedL.add(a); } X a=new X(); a.i=100; linkedL.set(1,a); for(X b:linkedL) { System.out.println(b.i); } }} Output: 0 100 2 3 4

393

See the out put, the change is reflected there. The HashSet Class The HashSet class of this util package use has table data structure in back ground to store the data. What is a hash table? Hash table is a data structure to store data, which contains key value for each data present in the hash table. This key value is unique for each element present in the hash table. The key field is closely associated with a pointer or a memory address. When a data is to be retrieved from a hash table the user provides the key value. The data is retrieved from the hash table by the memory address associated with the key value. HashSet in java extends the AbstractSet & implements the set interface. Remember one thing that when you store data in an object of HashSet there is no guarantee that the data is going to be stored in the order it has been entered. Just check it out here. The HashSet class does not provide the key value to the programmer to access the objects stored with in it. But, the HashMap class do provide the key. package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { HashSet<X> hashS=new HashSet<X>(); for(int i=0;i<5;i++) { X a=new X(); a.i=i; hashS.add(a); } for(X b:hashS) { System.out.println(b.i); } }}

394

Output: 3 4 2 1 0 Got it!! Fine!! In order to add an element you have to call the add() method along with the object to be added through the object of HashSet class. but you cannot determine where the data is going to be added. package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { HashSet<X> hashS=new HashSet<X>(); for(int i=0;i<5;i++) { X a=new X(); a.i=i; hashS.add(a); } X z=new X(); z.i=100; hashS.add(z); for(X b:hashS) { System.out.println(b.i); } }}

Output: 3 100

395

4 2 1 0 See where 100 is added. The TreeSet class In a TreeSet class in java uses tree data structure to store the data. Data in TreeSet class always stored in ascending order. Since this class maintains tree structure to store data, searching is done quite efficiently. package demo; import java.util.*;

class Demo { public static void main (String arg[]) { TreeSet<Integer> treeS=new TreeSet<Integer>(); int j=5; for(int i=0;i<5;i++) { System.out.println("Added element:"+j); treeS.add(j); j--; } for(Integer b:treeS) { System.out.println("Stored element"+b); } }} Output: Added element:5 Added element:4 Added element:3 Added element:2 Added element:1 Stored element1 Stored element2 Stored element3 Stored element4

396

Stored element5 See the out put although the elements are supplied in descending order, still they are stored in the TreeSet in ascending order. The Iterator The Iterator is an interface which is similar to Enumeration interface, except these two differences. Iterator as the name suggest is used to traverse through the elements stored in the set. Through Iterator programmer can remove the elements stored in the set. But, Enumeration (explained latter in this chapter) does not support the removal of elements present in the set. Method names have been improved in Iterator as compared to Enumeration The methods of the Iterator interface are: boolean hasNext( ):If the iteration has more elements then it returns true, else, it returns false.  Object next( ) :This method is used to iteratively extract the next element from the iteration. If there will be no more elements in the iteration, then it throws the NoSuchElementException  void remove ( ):This method is used to remove the last element returned by the iterator, from the current collection. We can call this method only once per call to the next method.

Till now to loop through the various elements stored in Collection object I have used the for-each loop. Alternative to for-each loop is Iterator. Steps to use Iterator: 1: create an Iterator object corresponding to the elements stored in the Collection frame work. 2: loop through the Collection object to retrieve the elements by the use of hasNext() method 3:extract the element by next() method package demo; import java.util.*; class X{ int i;

397

} class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>(); for (int j=0;j<5;j++) { X a=new X(); a.i=j; arrX.add(a); } Iterator<X> iteR=arrX.iterator(); while(iteR.hasNext()){ X a=iteR.next(); System.out.println(a.i); } } Output: 0 1 2 3 4 The hasNext() method, each time when it is invoked check whether an element existed in arrX or not in its next place, if not it returns false. The next() method return the element stored in arrX(). The way the Iterator is used in case of object of ArrayList class can also be used in LinkedList, HashSet, TreeSet calss. The ListIterator The object ListIterator provides a way to loop through the elements stored in the Collection object bidirectionally. Like Itrator it is also a generic class. steps are same to use the ListIterator object. Just see the program below package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) {

398

ArrayList<X> arrX=new ArrayList<X>(); for (int j=0;j<5;j++) { X a=new X(); a.i=j; arrX.add(a); } System.out.println("Fore ward traversing"); ListIterator<X> LiteR=arrX.listIterator(); while(LiteR.hasNext()){ X a=LiteR.next(); System.out.println(a.i); } System.out.println("Back ward traversing"); while(LiteR.hasPrevious()){ X a=LiteR.previous(); System.out.println(a.i); } } } Output: Fore ward traversing 0 1 2 3 4 Back ward traversing 4 3 2 1 0 hasPrevious() & previous() method behaves in the opposite way the hasNext() & next() behaves. ListIterator object can also be used in LinkedList, HashSet, TreeSet to perform the similar to that of ArryList.

Map interface Map is an interface by the help of which, we can establish a mapping between keys to the corresponding element. We cannot have any duplicate

399

values in a map. In the process of mapping each key is mapped to one & only one unique element. This interface consists of methods for basic operations, bulk operations and Collection view. The different operations that can be made on a map are: put, get, remove, containsKey, containsValue, size and isEmpty. The bulk operations are putAll and clear methods. The Collection views are keySet and entrySet methods.  void clear ( ) This method removes all the mappings from the current map.  boolean containsKey (Object keyused) This method returns true or false accordingly, whether the current map is mapping one or more keys to the value or not.  boolean containsValue (Object v ):This method returns a boolean true when the current map maps one or more keys to the value v. Otherwise, it returns a boolean false.  Set entrySet( ) This method returns a Set interface reference which specifies a view of the mappings established in the current map.  boolean equals (Object mp ) The return type of this method is boolean. It returns true when the object mp is equal to the current map, else it returns false.

 Object get(Object mp):This method is responsible to return the value to which the current map maps the key key  int hashCode( ):This method returns an integer representing the hash code value of this map  boolean IsEmpty( ):Checks whether the current map key value mappings. If the map does not contain any mapping then it returns true, else it returns false  Set keySet( ):The return type of this method is the Set interface reference which gives the representation of the keys in the map.  Object put(Object mapkey,Object mapvalue ) The job of this method to associate the mapvalue with the mapkey in the current map.  Object remove(Object mapkey) When there is an already existing mapping present for key in the current map, Then it is removed by the provided mapkey.object a is equal to the current map,else it returns false  Object get(Object keyused)

400

We can get the available value to which the mapping has been established using the key keyused.  int hashCode( ) Every map has a hashcode value. We can avail the value by using this method.  boolean IsEmpty( ) Checks whether the current map key value mappings. If the map does not contain any mapping then it returns true, else false.  Set keySet( ) The total no of keys used for mapping inside the Map can be returned using this method.  Object put(Object keyused,Object valueused ) To attach the value valueused with the key keyused in the map, this method is used.  Object remove(Object keyused) This method removes the mapping which is present in the map for the key keyused.  Int size( ) This method is used to get the total number of mappings established inside the Map.  Collection values( ) This method returns a Collection reference which represents the view of the values contained in the map.

StoredMap interface SortedMap is an interface which also extends the Map interface. The elements are maintained in an ascending order in case of StoredMap interface. The sorting may be done in two ways.  According to the default ordering principle provided by Java.  According to a user defined Comparator provided by the programmer explicitly. The methods of SortedMap interface are  Comparator comparator( ):This method returns the comparator which is associated with the SortedMap. If the SortedMap keys follows default ordering principle provided by Java, the method returns null.

401

 Object firstKey( ) From the ascending ordered SortedMap, this method returns the lowest key.  SortedMap headMap(Object keyused ):This method is used to return a reference of the portion of the currently stored map elements whose keys are less than keyused.  Object lastKey( ):From the ascending ordered SortedMap, this method returns the highest key.  SortedMap subMap(Object sm1, Object sm1 ) It returns a reference of the portion of the SortedMap whose keys are ranging from the key specified by sm1, to the key specified by sm2, the range includes sm1 and excludes sm2.  SortedMap tailMap(Object sm ) This method is used to return reference of the portion of the SortedMap whose keys are greater than or equal to the key as specified by sm1

The HashMap class This class uses the hash table data structure. It has both key & a value and data associated with the key. How it is used can be understood through a program. HashMap does not implement Iterable interface. This means programmer can not traverse a HashMap neither by Iterators nor by for-each loop. package demo; import java.util.*; class K { int key; } class V{ int data; } class Demo { public static void main (String arg[]) { HashMap<K,V>hashM=new HashMap<K,V>(); K keyArr[]=new K[5]; for(int i=0;i<5;i++) { K key1=new K(); key1.key=i;

402

keyArr[i]=key1; V val=new V(); val.data=i+5; hashM.put(key1,val); } for(int i=0;i<5;i++){ V a=hashM.get(keyArr[i]); System.out.println(a.data); } }

} Output: 5 6 7 8 9 Data is sored in the HashMap along with the key value. Just see the put method, it keeps inserting data in the HashMap with the key value. To extract data from HashMap key is required. Therefore I have declare an array to store the key value. Then each key value stored in the array is used to extract data from the HashMap. The get() method only requires the key to extract the data. The entrySet() method HashMap is not a part of collection frame work, since it does not implement the Collection interface. How ever, java provides an entrySet() method to have collection format of HashMap. This method returns Set object which contains the element of the HashMap. Lets have an example package demo; import java.util.*; class K { int key; } class V{ int data; } class Demo { public static void main (String arg[]) {

403

HashMap<K,V>hashM=new HashMap<K,V>(); for(int i=0;i<5;i++) { K key1=new K(); key1.key=i; V val=new V(); val.data=i+5; hashM.put(key1,val); } Set<Map.Entry<K, V>> s=hashM.entrySet(); for(Map.Entry<K, V> x:s) { K z=x.getKey(); System.out.print("For key: "+z.key+" Value:"); V c=x.getValue(); System.out.println(c.data); } }

} Output: For key: 2 Value:7 For key: 4 Value:9 For key: 3 Value:8 For key: 1 Value:6 For key: 0 Value:5 Here the object of Set s is going to hold the entries of HashMap in set format by the invocation of setEntry() method through hashM the object of HashMap. The setEntry() method returns the return the object of Set containing all the stored in HashMap. Remember that each element present in s is a reference of of Map.Entry. Entry is a inner class of Map. That is why I have created a reference of Map.Entry in for each loop. The getKey() method returns the reference of class K & the getValue() method returns the reference of class V. Now the output is straight forward.

The Comparators You must have noticed while explaining the treeSet, the programming example I have given used a wrapper class instead of user defined class. treeSet stores the object in a sorted order. Java defines a natural ordering principle like B comes after A or 2 comes after 1 for treeSet & only for

404

the predefined class. when it comes to deal with user defined classes, then programmer must explicitly define ordering principle by the use of Comparator interface. The Comparator interface defines two method compare() & equal(). The signature of the Comparator interface is interface Comparator<genR>. Yes this is a generic interface. The signature of compare() method is int Compare(genR X,genR Y). If X equals Y then 0 is returned If X>Y then positive value is returned If X<y then negative value is returned Now lets use the concept. package demo; import java.util.*; class X { int i; } class userComp implements Comparator<demo.X> { public int compare(X a, X b){ return a.i-b.i; } } class Demo { public static void main (String arg[]) { TreeSet<X> treeS=new TreeSet<X>(new userComp()); for(int i=0;i<5;i++) { X a=new X(); a.i=i; treeS.add(a); } for(X a:treeS) { System.out.println(a.i); } } } Output: 0

405

1 2 3 4 this TreeSet<X> treeS=new TreeSet<X>(new userComp()); statement tells the compiler to use the user defined comparator rather than default comprator. Java implicitly invokes the compare() method of userComp class. The object for which the compare() method returns a positive value is stored next to the previously stored object. How to reverse this user defined comparator package demo; import java.util.*; class X { int i; } class userComp implements Comparator<demo.X> { public int compare(X a, X b){ return -a.i+b.i; } } class Demo { public static void main (String arg[]) { TreeSet<X> treeS=new TreeSet<X>(new userComp()); for(int i=0;i<5;i++) { X a=new X(); a.i=i; treeS.add(a); } for(X a:treeS) { System.out.println(a.i); } } } Output:

406

4 3 2 1 0 The Collection Algorithm Java defines various methods to be operated on Collection objects for repositioning of the elements, extracting a particular element say minimum or maximum value, sorting the elements in the specified manner, coping the elements & various other operations. These methods in together constructs the collection algorithm.

Lets have an example package demo; import java.util.*; class Demo { public static void main (String arg[]) { LinkedList<Integer>linkedL=new LinkedList<Integer>(); linkedL.add(-100); linkedL.add(99); linkedL.add(-99); linkedL.add(100); Comparator<Integer>revC=Collections.reverseOrder(); // creation of a reverse comparator Collections.sort(linkedL,revC); // sorting the list according to reverse comparator System.out.println("Descending order:"); for(Integer i:linkedL) System.out.println(i); Collections.shuffle(linkedL); // shuffling the elements present in the list System.out.println("After shuffling"); for(Integer i:linkedL) System.out.println(i); System.out.println("Maximum element:"+Collections.max(linkedL)); System.out.println("Minimum element:"+Collections.min(linkedL));

407

} Output: Descending order: 100 99 -99 -100 After shuffling 99 100 -100 -99 Maximum element: 100 Minimum element:-100 The out put is straight forward & simple. All the method names used in this program define their task. The Vector class The Vector class is much similar to that of ArrayList class used to generate the dynamic array. Vector class is synchronized. package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { Vector<X> vect=new Vector<X>(); for(int i=0;i<5;i++) { X a=new X(); a.i=i; vect.add(a); } X a=new X(); a.i=100; vect.addElement(a); for(X x:vect) System.out.println(x.i); } }

408

Output: 0 1 2 3 4 100 addElement() method behaves similar to that of add() method. you can see that Vector is much similar to that of ArrayList. Here you can Iterators to traverse various elemrts present in Vector object package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { Vector<X> vect=new ArrayList<X>(); for (int j=0;j<5;j++) { X a=new X(); a.i=j; vect.add(a); } Iterator<X> iteR=vect.iterator(); while(iteR.hasNext()){ X a=iteR.next(); System.out.println(a.i); } } Output: 0 1 2 3 4 Vector class & the Enumeration interface Enumeration interface contains various methods by which you can loop through various elements stored in Vector, just like Iterator. This is a legacy interface can only be operated on Vector object.

409

package demo; import java.util.*; class X{ int i; } class Demo { public static void main (String arg[]) { Vector<X> vect=new Vector<X>(); for(int i=0;i<5;i++) { X a=new X(); a.i=i; vect.add(a); } Enumeration en=vect.elements(); while(en.hasMoreElements()){ X a=(X)en. nextElement(); System.out.println(a.i); } } } Output: 0 1 2 3 4 Enumeration is an interface. Vector implements this interface. The element() method returns the enumerations of elements present in Vector which is stored in en. Then hasMoreElements() method is invoked by en. This method returns true until the last element is encountered. Each invocation of hasMoreElements() method just fore ward the implicit pointer to point to the next element. The method nextElement() extracts the element that is pointed by the implicit pointer. Its return type is object type; hence proper type casting is required.

410

The Stack class Stack class extends the Vector class. This class uses the stack data structure to store various elements. The principle to retrieve the data from stack class is last in first out principle.

package demo; import java.util.*;

class Demo { public static void main (String arg[]) { Stack<Byte> s=new Stack<Byte>(); System.out.println("Initially the Stack:"+s); for(int i=0;i<10;i++){ byte b=(byte)i; s.push(b); System.out.println("Initially the Stack:"+s); } while(!s.empty()){ System.out.println("pooped:"+s.pop()); System.out.println(s); } } }

Output: Initially the Stack:[] Initially the Stack:[0] Initially the Stack:[0, 1] Initially the Stack:[0, 1, 2] Initially the Stack:[0, 1, 2, 3] Initially the Stack:[0, 1, 2, 3, 4] Initially the Stack:[0, 1, 2, 3, 4, 5] Initially the Stack:[0, 1, 2, 3, 4, 5, 6] Initially the Stack:[0, 1, 2, 3, 4, 5, 6, 7] Initially the Stack:[0, 1, 2, 3, 4, 5, 6, 7, 8] Initially the Stack:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] pooped: 9 [0, 1, 2, 3, 4, 5, 6, 7, 8]

411

pooped: 8 [0, 1, 2, 3, 4, 5, 6, 7] pooped: 7 [0, 1, 2, 3, 4, 5, 6] pooped: 6 [0, 1, 2, 3, 4, 5] pooped: 5 [0, 1, 2, 3, 4] pooped: 4 [0, 1, 2, 3] pooped: 3 [0, 1, 2] pooped: 2 [0, 1] pooped: 1 [0] pooped: 0 []

push() method pushes a new element in to the stack & increases the stack size by 1. pop() method pops the last element present in the stack & decreases the capacity of the stack by 1. Output clearly shows the performance of these two methods.

Hashtable Hashtable is another powerful feature of Collection Frame Work. This class implements the hash table data structure to store the element with in the hash table object. Actually objects are not stored in fact their reference is stored. Hashtable class is much similar to that of HashMap class but, Hashtable is synchronized. Hashtable implements the Dictionary. Lets have a program for the implementation of Hashtable. package demo; import java.util.*; class K { int key; } class V{ int data; } class Demo {

412

public static void main (String arg[]) { Hashtable<K,V>hashT=new Hashtable<K,V>(); K keyArr[]=new K[5]; for(int i=0;i<5;i++) { K key1=new K(); key1.key=i; keyArr[i]=key1; V val=new V(); val.data=i+5; hashT.put(key1,val); } for(int i=0;i<5;i++){ V a=hashT.get(keyArr[i]); System.out.println(a.data); } }

} Output: 5 6 7 8 9 See the Hashtable behaves similar to that of Hashmap.

Important Methods Of Collection Frame work and their Descriptions  boolean add(Object cls):This method adds the given object to the existing collection. If the addition of the object is successful, then this method returns true. But, if the object is already there inside the collection, then this method returns false. This method invoked by the collection object to which the addition of element has to be performed.  boolean addAll(Object cls):This method is use to add all elements of the Collection which is passed as argument to the existing collection. This method returns true when the elements are added successfully. Otherwise, it returns false.

413

void clear( ):This method is used to erase all the items from the collection object through which it is invoked. boolean contains(Object cls) :This method is used to confirm whether the given object cls is present inside the current collection or not. If it is present, then the method returns true, else it returns false. boolean containsAll(Collection cls):This method is used to check whether the provided Collection elements are contained in the current Collection. If the elements are found, then the method returns true. Otherwise it returns false. boolean equals(Objecct cls):This method checks whether the object a and the current collection are equal and returns true ar false appropriately.int hashCode( )Returns the hash code of the current collectionboolean isEmpty( )Checks whether the current Collection is emptyIterator iterator( )Returns an iterator for the current collectionboolean remove(Oblect a) Removes an instance of the object a from the current collection. If successful, it returns true, else it returns false. boolean removeAll ( Collection cn):This method is used to erase all the items that are present in the provided Collection cn from the existing collection. If successful, it returns true, else it returns false. boolean retainAll ( Collection cn):This method is used to retain all the items of the Collection cn in the current Collection and removes all the other elements from it. int size( ):This method returns the number of elements of the current collection Object[] toArray() :This method returns a copy of all the elements of the current collection to an Object array. Object[] toArray(Object oa[]):This method returns a copy of only those elements of the current collection where the type of the elements will match to that of the object array oa, to an object array.

414

Conclusion: Collection Frame Work is a powerful addition to the java language. This frame work provides various data structures to store & retrieve the data. Its up to the programmer to implement the desired data structure according to the situation. By the introduction of generics in java, most of the constructors, methods are reengineered. It has enhanced scope & efficiency of Collection Frame Work because of generic implements the type-safety principle. In most of the programs I have used generic constructors & methods available. Most of the fundamental classes their most frequently used methods are discussed here. Apart from them a rich library of methods is available in Collection Frame Work. After having these fundamental ideas, your navigation through other methods will be bread & butter for you.

415

Chapter-24

java.util package part II


StringTokenizer Parsing is quite familiar term in Compiler Design. What exactly meant by parsing? When you write a program in any high-level language, say java, it is the task of the compiler to convert the source to some intermediate language like byte code or directly to machine readable language. During this process first compiler checks the syntactical correctness of the program. This checking is done by dividing the text entered by the programmer in to number substrings according to some parsing protocol or rule & this is what we call parsing. Java provides the StringTokenizer class to divide the entered text in to number of sub-string or tokens. StringTokenizer implements the Enumeration interface for which we can traverse through various sub-strings present in the entered text. package demo; import java.util.*;

class Demo { static String str1="Past, Present & future is nothing special, they are just Clock Time!!"; public static void main(String arg[]) { StringTokenizer sTokenizer=new StringTokenizer(str1,","); while(sTokenizer.hasMoreTokens()) { String keyused = sTokenizer.nextToken(); System.out.println(keyused ); } } } Output: Past Present & future is nothing special they are just Clock Time!!

sTokenizer is a object of StringTokenizer class. see the constructor of the StringTokenizer class it takes two argument. 1st argument is the string

416

meant for parsing. The 2nd argument is the string according to which the 1st argument has to be divided in to number of sub-strings. Methods and their Description  int countTokens( ):This method determines the number of tokens left to be parsed and returns the result.  boolean hasMoreElements ( ):This method returns true if one or more tokens remain in the string and returns false if there are none.  boolean hasMoreTokens ( ):This method returns true if one or more tokens remain in the string and returns false if there are none.  Object nextElement( ):This method returns the next token as an Object.  String nextToken (String delimiters):This method returns the next token as a String and sets the delimiters of the string.

StringTokenizer class provides another two constructors. They are 1. StringTokenizer (String string) 2. StringTokenizer (String string, String delimiters, boolean delim) Lets have another program package demo; import java.util.*;

class Demo { static String str1="Past, Present & future is nothing special, they are just Clock Time!!"; public static void main(String arg[]) { StringTokenizer sTokenizer=new StringTokenizer(str1); String arr[]={",","&","is",","}; int i=0; while(i<4) { String keyused = sTokenizer.nextToken(arr[i]); System.out.println(keyused ); i++; } }

417

Output: Past , Present & future is nothing special The output here is quite simple & straight forward. BitSet Java provides the BitSet class to store the bit values. The array created by BitSet class is dynamic in nature i.e. the array can grows & shrinks according to the given input. The constructors available in BitSet class are: 1:BitSet( ) 2:BitSet(int capacity) this constructor is used to initial capacity of the BitSet class object. package demo; import java.util.*; class Demo { static String str1="Past, Present & future is nothing special, they are just Clock Time!!"; public static void main(String arg[]) { BitSet bSet1=new BitSet(32); BitSet bSet2=new BitSet(32); for(int i=1;i<=32;i++) { if(i%2==0) bSet1.set(i); if(i%3==0) bSet2.set(i); } System.out.println(bSet1); System.out.println(bSet2); //Anding of Bits bSet2.and(bSet1); System.out.println("After ANDING:"+bSet2); // The OR operation bSet1.or(bSet2); System.out.println("After OR:"+bSet1);

418

//XOR operation bSet2.xor(bSet1); System.out.println("After XOR:"+bSet2); } } Output: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32} {3, 6, 9, 12, 15, 18, 21, 24, 27, 30} After ANDING:{6, 12, 18, 24, 30} After OR:{2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32} After XOR:{2, 4, 8, 10, 14, 16, 20, 22, 26, 28, 32} set() method sets the particular bit on for the BitSet object through which it is invoked. For example when this statement if(i%2==0) bSet1.set(i); is encountered, 2nd bit, 4th bit, 6th bit, 8th bit & so on of bSet1 is turned on. The and() method performs the and operation & the result is stored in the invoking object bSet2. The Observable class & the Observer interface

The Observable class & the Observer interface is closely entangled with each other. Seldom will you ever find a programmer using only one of the classes to develop an application in java. Java provides a unique tool through these class & interface to keep track of the changes that happens to various objects during the course of execution of the program. The class which is going to keep track of the changes has to implement Observer interface & the class which under the focus must implements the Observable interface. A program will fix the ideas package demo; import java.util.*;

class X implements Observer{ public void update(Observable obs,Object obj) { System.out.print("Object of Y is changed:"); }

} class Y extends Observable {

419

int i; void fun() { i++; this.setChanged(); notifyObservers(this); try{ Thread.sleep(100); }catch(InterruptedException e){} show(); } void show() { System.out.println(i); } }

class Demo { public static void main(String arg[]) { Y a=new Y(); X b=new X(); a.addObserver(b); for(int i=0;i<10;i++) { a.fun(); } } } Output: Object of Object of Object of Object of Object of Object of Object of Object of Object of Object of

Y Y Y Y Y Y Y Y Y Y

is is is is is is is is is is

changed:1 changed:2 changed:3 changed:4 changed:5 changed:6 changed:7 changed:8 changed:9 changed:10

420

class X implements Observer interface. This tells to JVM that the object of X will behave as observer. Class Y extends the Observable interface that means changes made to the object of Y is going to be monitored. Now have a look at class Y. It has an instance variable i. inside main method fun method is invoked by the object of Y. fun method manipulates the object a by performing i++. The statement a.addObserver(b); registers the object b as observer to observe the changes made in object a. Now in side fun method I have invoked the setChanged() method. One thing the observer object & the object to be observed runs in different threads. The setChanged() method made the observer thread in ready state. If you do not invoke this method then observer thread is not going to be executed, because for a thread to run 1st it must go to ready state. The setChanged() method has to be invoked by the object which is to be observed. The notifyObservers(this) method informs the observer when the object is manipulated. This method actually implicitly invoke the update() method & sends the object a to update() method implicitly. Now since the observer & the object to be observed runs in different threads therefore the context switch is required to transfer the control to observer. This is done by the sleep() method. Once the control is transferred, the change is monitored & the message inside the System.out.println() is dispalyed.

package demo; import java.util.*;

class X implements Observer{ public void update(Observable obs,Object obj) { System.out.println("Object of Y is changed:"+(Integer)obj); }

} class Y extends Observable { Integer i ; void fun() { i++; this.setChanged(); notifyObservers(this.i);

421

try{ Thread.sleep(100); }catch(InterruptedException e){} }

class Demo { public static void main(String arg[]) { Y a=new Y(); a.i=new Integer("0"); X b=new X(); a.addObserver(b); for(int i=0;i<10;i++) { a.fun(); } } } Output: Object of Object of Object of Object of Object of Object of Object of Object of Object of Object of

Y Y Y Y Y Y Y Y Y Y

is is is is is is is is is is

changed:1 changed:2 changed:3 changed:4 changed:5 changed:6 changed:7 changed:8 changed:9 changed:10

An object having multiple observers package demo; import java.util.*;

class X implements Observer{ public void update(Observable obs,Object obj)

422

{ System.out.println("Object of Y is changed:"+(Integer)obj); } }

class Y extends Observable { Integer i ; void fun() { i++; this.setChanged(); notifyObservers(this.i); try{ Thread.sleep(100); }catch(InterruptedException e){} }

class Demo { public static void main(String arg[]) { Y a=new Y(); a.i=new Integer("0"); Y c=new Y(); c.i=new Integer("100"); X b=new X(); a.addObserver(b); c.addObserver(b); for(int i=0;i<10;i++) { a.fun(); c.fun(); } } } Output: Object of Y is changed:1

423

Object Object Object Object Object Object Object Object Object Object Object Object Object Object Object Object Object Object Object

of of of of of of of of of of of of of of of of of of of

Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y

is is is is is is is is is is is is is is is is is is is

changed:101 changed:2 changed:102 changed:3 changed:103 changed:4 changed:104 changed:5 changed:105 changed:6 changed:106 changed:7 changed:107 changed:8 changed:108 changed:9 changed:109 changed:10 changed:110

Two Objects monitored two different Observers package demo; import java.util.*;

class X implements Observer{ public void update(Observable obs,Object obj) { System.out.println("Object of Y is changed:"+(Integer)obj); } } class Z implements Observer{ public void update(Observable obs,Object obj) { System.out.println("Object of Y is changed:"+(Integer)obj); } } class Y extends Observable {

424

Integer i ; void fun() { i++; this.setChanged(); notifyObservers(this.i); try{ Thread.sleep(100); }catch(InterruptedException e){} }

class Demo { public static void main(String arg[]) { Y a=new Y(); a.i=new Integer("0"); Y c=new Y(); c.i=new Integer("100"); X b=new X(); Z d=new Z(); a.addObserver(b); c.addObserver(d); for(int i=0;i<10;i++) { a.fun(); c.fun(); } } } Output: Object of Object of Object of Object of Object of Object of Object of

Y Y Y Y Y Y Y

is is is is is is is

changed:1 changed:101 changed:2 changed:102 changed:3 changed:103 changed:4

425

Object Object Object Object Object Object Object Object Object Object Object Object Object

of of of of of of of of of of of of of

Y Y Y Y Y Y Y Y Y Y Y Y Y

is is is is is is is is is is is is is

changed:104 changed:5 changed:105 changed:6 changed:106 changed:7 changed:107 changed:8 changed:108 changed:9 changed:109 changed:10 changed:110

Task Scheduling Task scheduling is another excellent feature provided by this premier programming language. You can schedule your job at any future time & you can set the time interval after which you want the task to be repeated. All these things can be achieved by the Timer & TimerTask method. 1st lets have an example then I will explain all in detail package demo; import java.util.*;

class X extends TimerTask{ public void run() { System.out.println("Hello World!!!"); } } class Demo { public static void main(String arg[]) { X a=new X(); Timer tm=new Timer(); tm.scheduleAtFixedRate(a, 1000, 250); try{ Thread.sleep(5000); }catch(InterruptedException e){}

426

tm.cancel(); } } Output: Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Hello World!!! Here class X extends the TimerTask class. TimerTask class implements the Runnable interface due to which run() method is available there. Codes inside the run method is the task to be executed. Inside main method the task object is created by the statement X a=new X();.You required timer to set the time & the frequency of the task. Timer or you can say scheduler is created by Timer tm=new Timer(); this statement. Next scheduler invokes the scheduleAtFixedRate method. this method takes the task object a, time at which the task is going to be started & the time interval after which the task is going to be repeated. Task executed as separate thread. So to transfer the control context switch is required, which is done by the sleep() method. As long as main thread is sleeping the task is done at a particular interval of time. When the main thread resumes tm.cancel() is invoked to terminate the task. Conclusion: Apart from the discussed classes & interfaces util package contains a huge number of collections of classes. Almost all of them are simple can easily be understood by the reader. Something like Date class, Calendar class, TimeZone class is there to play with date, month & year. My aim is to made reader comfortable with the things like observer & task scheduling. These classes I have discussed are not part of Collection Frame Work.

427

Chapter-25

java.applet package
Applet Generally java programs can be classified into two groups namely applications and applets. Unlike applets, Java applications do not require a browser to run. They can be created like any normal programming language programs. Applets are executed in the browser. Applet is a class file that displays graphics application in the web browser and you can embed applet codes in the web pages by HTML tags. Briefly we can say that applet is a java byte code embedded in a HTML page. The program structure of applets differs from the other java applications we have done till now. Applets have made java a web enabled languase. Definition An applet is a dynamic and interactive program that can run inside a Web page displayed by a java-capable browser such as HotJava Browser, Internet Explorer browser is a World Wide Web Browser used to view Web pages. Applet is a class present in java.applet package.

A special HTML tag is embedded in the applet to make it run on the web browser . appletviewer application is used to run and check the applets , it is present in the jdk. Applets has added advantages such as frame, event-handing facility, graphics context and surrounding user interfaces. Java applets have some restrictions to ensure full security and to make them virus free . Some of these are wriiten below. j Applets have no read or write permisson to the file system. j Applets can communicate with the server in which they were stored originally but not with the others. j Applets cant execute any programs on the system.

Life cycle of Applet: Applets dont have any main method or constructors.so we can compile a applet code but we cannot run it.now lets see how a applet gets executed what are the different states of a applet.

428

   

Newborn state. Running state (display). Idle or stop state. Dead state or Destroyed state.

init() Begin or entering

Newborn state

(By typing URL, address).

paint()

start() stop()

Running state
start()

Idle state

destroy()

Dead state

Exit or End

(Transition diagram of applet life cycle)

429

     

Every java Applet when loaded undergoes a series o f state changes. There are four Applet state. Whenever the init() method is called the applet is created or we can say that it gets life. When the start() method is called the execution of the applet gets started. All the changes in the applet are reflected by the paint method(). Whenever we call the stop() method the applet goes to ideal state that means we have to call the start method again to bring the applet to the ready state. The destroy() method is called to end the execution of the applet or to exit the applet.

There are many methods in the applet class but the methods init() , start(), paint(), stop() and destroy() constitutes the life cycle o f applet. Public void init() Method When the applet starts first the init() method is called and is called only once in the entire life time of the applet. Initialization of all the variables, creation of objects and setting of the parameters can be done in this method. Applet has no constructor but init () behaves as a constructor. public void start() Method This method is executed after the init () method. whenever a user moves from the applet to some other application and again comes back to the applet after some time then the applet resumes execution from start() method . The stop() Method The stop () method is used to halt the running of an applet. When an applet is running in a Java enabled browser, the stop () method is called when you move from to another Web page and when you comes back, the start() method is called to resume the applet. You can call the stop() and start() method repeatedly if you want to do it. The destroy() Method This method is called whenever we want to free the memory occupied by the variables and objects initialized in the applet. Any clean up activity that needs to be performed can be done in this method. we can free the resources held by the applet using the destroy() method. stop() method is always called before the destroy() method is called. The destroy() method is different from the finalize() method. The destroy() method applies only to applets where as the finalize() method is generally used to clean up a single object.

430

The paint() Method Whenever it is needed to redrawn the output of the applet paint() method is called. This method helps in drawing, writing and creating a colored background or an image onto the applet. It takes an argument, which is an instance of the Graphics class. To use this method, it is necessary to import the Graphics class as import java.awt.Graphics. The repaint() Method This method is used in case an applet is to be repainted. The repaint() method calls the update( ) method to clear the screen of an existing content. The update( ) method in turn calls the paint( ) method which draws the contents of the current frame. repaint() can be called in future by mentioning time interval in millisecond. If the time expires before update() can be called, update is not summoned.

void repaint( int x_co, int y_co, int WIDTH, int HEIGHT) repaint() takes four arguments to update only a part of the screen. The first to arguments are the x and y coordinates, the next two arguments are the width and the height of the image. This helps in faster updating of the screen.there are also other versions available they are given below. void repaint(long Delay) void repaint(long Delay, int x, int y, int width, int height) in the above syntax Delay specifies the time in milliseconds that it will wait before update( ) is called.

The other methods available in Applet class are defined below

431

Method AppletContext getAppletContext() String getAppletInfo() AudioClip getAudioClip(URL u)

Describe Determines the applet context and returns it. Gets the information about the Applet. Collects the AudioClip object from the location specified by the url. Collects the AudioClip object from the location specified by the url having the name specified. Collects the base URL Collects the document URL Collects an Image that can painted in the screen Collects an Image that can painted in the screen Gets the value of the name parameter in the HTML tag. Determines whether an applet is active or not. Plays the audio clip in the background of applet. Plays the audio clip in the background of applet. Resize the applet Requests the String to be displayed in the status window of Applet

AudioClip getAudioClip(URL u, String name)

URL getCodeBase() URL getDocumentBase() Image getImage(URL u)

Image getImage(URL u,String name)

String getParameter(String name)

boolean isActive() void play(URL u)

void play(URL u, String name)

void resize(int width,int height) void showStatus(String msg)

HTML Tags Some of the HTML tags used in the .html file are discussed below.

432

Applet Tags The <applet> tag is used to start the applet from inside the HTML document as well as from the appletviewer. Each <applet> tag is executed in separate windows by the appletviewer while the Java capable browser is capable of executing numerous applets inside a single web page. This code instructs the browser or the appletviewer to load the compiled Java applet, namely the .class file. The size of display of the applet is initialized using the WIDTH and HEIGHT tags. To indicate the end of the applet, < / applet> tag is used. It is essential to end the applet using this tag, otherwise it will not be executed. Comment lins can be inserted below, above or at the side of the applet within the HTML file. This is done by including those lines within the < applet > and < / applet > tags. CODE and CODEBASE Tags CODE is a necessary attribute that gives the name of the file that contains the applets compiled class. It assumes that both the .java file and the .html file are in the same directory. If the .html file and the .class fill are stored in different directories, it is essential to mention it specifically. To do this, the CODEBASE tag is used. The CODEBASE tag contains the pathname where the .class file is stored. For example, if the .class file of an applet named Text Applet is stored in the directory /test, the HTML file code will appear as indicated below: <APPLET CODE = TestApplet.class CODEBASE = / test WIDTH=400 HEIGHT=300></APPLET> Passing Parameters to an Applet We have discussed the passing of parameters to a Java application. To pass parameters to an applet, two things are required a special parameter tag in the HTML file and the code in the applet to parse those parameters. The special parameter tag in the HTML file is <PARAM>. This has two attributes namely NAME and VALUE. The init () method of the applet, contains a method called getparameter (). This method takes one argument the string representing the name of the parameter being looked for and returns a string containing the corresponding value of that promoter. If this method is required to return types other than strings, it has to be converted explicitly.

The different methods we use to set the graphical enviorment

433

applets use the classes & methods of AWT to perform its input and output operations. To display the output in the applet we use the drawstring() method present in the Graphics class . Its general form is : void drawString(String msg, int x_co, int y_co) msg holds the string to be written on the aplet screen starting from the coordinates specified by x_cor and y_cor. In a Java window, the upper-left corner is location 0,0. setBackground( ) method is used to set the background color of the applet. setForeground( ) method is used to set the foreground color of the applet means the color of the texts to be written. The above methods are defined in Component class , and their general forms are: void setBackground(Color Color) void setForeground(Color Color) Color specifies the new color. The Color class defines the below constants that can be used to specify colors: Color.black Color.magenta Color.blue Color.orange Color.cyan Color.pink Color.darkGray Color.red Color.gray Color.white Color.green Color.yellow Color.lightGray The below example sets the background color to pink and the text color to magneta: setBackground(Color.pink);

434

setForeground(Color.magneta);

Lets create our first applet

import java.awt.*; import java.applet.*; /* <applet code="SimpleBanner" width=750 height=500> </applet> */ public class abc extends Applet { String mesg = " WELCOME TO APPLET"; public void init() { setBackground(Color.cyan); setForeground(Color.red); } public void start() { mesg = mesg+" MISS SAMITA"; } public void stop() { } public void paint(Graphics g1) { g1.drawString(mesg, 50, 30); } }

Output :

435

Lets see what are the steps to create a applet from the above example. First we have to import both the packages java.applet and java.awt , its a must. After that we have defined the html tag which is required to makes the applet to run in the web browser. After that we defined the init() method , then the start() method and at last the paint method. here we dont need the stop() or destroy() method so we have not defined them. now from the above example we can see that first the init() method is called and the background color and foreground color is set using the setBackground(Color.cyan) and setForeground(Color.red) method. after that start method was called in which the msg variables content is modified then the paint method is called in which the we have written the code g.drawString(msg, 50, 30) to print the output on the applet. Lets see another example which will help to make clear the concepts

Example-2 helps in understanding the usage of passing parameters to an applet. Example-2 import java.applet.Applet; import java .awt .*; public class Second extends Applet { Font f = new Font ("TimesRoman", Font.BOLD, 40);

436

String name; public void init() { name = getParameter ("name") ; if (name == null) { name = "Java" ; name = "Have a nice day " + name ; } } public void paint(Graphics g1) { g1.setFont (f); g1.setColor (Color.blue); g1.drawString (name, 50, 50); } } /*<applet code="Second.class" width=200 height=200 align=TOP> <param name="name" value="Sai"> </applet>*/

437

An instance of the Font class f is declared. This object has been initialized to contain TimesRoman as font name, font size as 40 and font style as BOLD. The init () method declared in line number 7, contains the getParameter () method, which accepts the name (a string) as its parameter. The paint () method of the Component class is overridden to execute the paint () method in the class. This method contains the drawString () method apart form, two methods namely setFont () and setColor (). These two methods are used to set the desired font and color respectively.

Passing parameters to applets


We can set the parameter as we have shown above and to retrieve the value we have to use the getParameter() method. which take the name of the parameter and returns the value stored at the parameter.

import java.awt.*; import java.applet.*;

/* <applet code="SimpleBanner" width=750 height=500> <param name="param1" value ="SAI"> </applet> */ public class abc extends Applet { String mesg ; public void init() {

438

setBackground(Color.white); setForeground(Color.red); } public void start() { mesg = getParameter("param1"); } public void paint(Graphics g1) { g1.drawString(mesg, 50, 30); } }

Output :

HOW TO PLAY A Audio Clip

439

Lets first see the example below . after that i will explain how it is done.

import java.applet.*; import java.awt.*;

public class player extends Applet { AudioClip a1; public void init() { a1=getAudioClip(getCodeBase(),"sai.au"); } public void start() { a1.play(); } public void paint(Graphics g1) { g1.drawString(playing music,50,30); } } /*<applet code="Play" width=200 height=200> </applet>*/

440

Output :

This program will open a applet and the music file named sai.au will be played. The getAudioclip() method returns the URL of the music file specified as its parameter value. Then we call the play method to play the music file. We can only play the *.au format music files.and the music file should reside in the same directory in which the java file is present.

Below given is given a designer applet to play and stop the music files

import java.awt.*; import java.awt.event.*;

441

import java.applet.*; public class Play extends Applet implements ActionListener { AudioClip a1; Button b1,b2; public void init() { b1=new Button("Start"); b2=new Button("Stop"); a1=getAudioClip(getCodeBase(),"sai.au"); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); }

public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { a1.play(); }else{ a1.stop(); }

442

public void paint(Graphics g1) { g1.setColor(Color.red); g1.setFont(new Font("Arial",Font.BOLD,40)); g1.drawString("This Is Music World",50,70); } } /*<applet code="Play" width=200 height=200> </applet>*/

AppletContext

443

AppletContext is an interface which is implemented by an object that represents the applets environment . To use it we have to first create a object of AppletContext using getAppletContext() method.it is shown below

Example AppletContext context= getAppletContext( ); In AppletContext some interesting methods are defined like the getApplet() method ,it returns the name of the applet and getApplets( ) method which returns all the applets in the document base.

getApplet( ) getApplets( )

in AppletContext another method showDocument( ) is also defined which either takes a URL or a URL and the file name in form of a string. it creates an HTML page in the web browser which is showing the applet. It could be useful with HTML frames where the applet should reside in a frame and the new HTML pages should be shown in another frame.

showDocument( )

showStatus( ) method shows the string passed to it as parameter on the status bar at the button of the web browser. The example below shows the use of showDocument( ) and showStatus( ) methods .

AppletContext Code Sample

444

import java.applet.*; import java.awt.*; import java.net.*;

// <applet code="applet1.class" width=400 height=100></applet>

public class applet1 extends Applet{ public void init(){ try{ URL url1=new URL("http://wallpaper.net/pkomisar/Flowere.html"); getAppletContext( ).showDocument(url1); }catch(MalformedURLException me){}

public void paint( Graphics g1){ g1.setFont(new Font("Monospaced", Font.BOLD, 22)); g1.drawString(" Hello World", 55, 65 ); getAppletContext( ).showStatus( "Puts the message in status bar" );

} }

445

Now in the above program we get the current appletcontext using getAppletContext() method then using the showDocument() method we just transferred the control to another html file which is passed to it as parameter .the showStatus() method displays the string passed to it as parameter at the buttom of the applet window .

Note : We can use console output in applet like System.out.println() , the string passed to it will not get displayed on the screen rather it will get displayed in the console. it is used generally for debugging purpose otherwise use of these methods are discouraged.

Advantages
A Java applet has the following advantages:
y y y y

An applet can work properly on "all" the versions of Java installed , excluding the latest plug-in version . All most all web browsers support applet A user can permit it to have full access to the machine on which it is running. it can improve with use: after a first applet is run, the JVM is already running and starts quickly, benefitting regular users of Java but the JVM will need to restart each time the browser starts fresh. When we compare its speed of execution it executes slower than c++ codes but faster than JavaScript

Disadvantages
A Java applet has the following disadvantages:
y y

Sometimes the Java plug-in is required and it isn't available on every web browsers by default. Intially the loading time for a applet is noticeable but you will notice it further

446

Conclusion : This is all about applet. Actually now you can observe that without applet java cannot get the honour of a web enabled languase. The awt package present in java is a important package which is needed to a devlop a sophisticated applet. We will discuss all about awt package in the coming chapters.

447

Chapter-26

The java.awt package


Java facilitates the development of Graphical User Interface components with the help of java.awt package. The awt stands for abstract window toolkit. The awt is an API, i.e. application programming interface. It should be mentioned here, that an API provides libraries, which contains several classes, data-structures and protocols for development of different applications. The java.awt package belongs to the Java Foundation Classes, i.e. JFC. Inside the java.awt package, we can avail various GUI components, the model for the event handling techniques, different tools for graphics and images, and the LayoutManager. Also, it facilitates the mechanism for data transfer by cut and paste process through clipboards. The JavaBeans architecture can be supported by the AWT. The AWT component can be treated as simple beans. The java.awt package provides various classes for the development of user interfaces and for painting graphics and images. There are various subsystems under the java.awt package which enable the development of Graphical User Interface (GUI) components. The subsystems are: j j j j j Graphics primitives, for drawing and rendering lines and images. Components, which include Label, Button and TextField. Containers, which include Frame, Panel and Dialog. LayoutManager, to control the displaying in a portable fashion. Event system, to respond to interactions between the Component and Container in the application.

The Graphics Class Graphics is an abstract class present inside the java.awt package. The signature of this class is: public abstract class java.awt.Graphics extends java.lang.Object

448

This class provides the declaration of various methods which are used for the purpose of drawing lines, rectangles and several other shapes For drawing different figures, the knowledge about the co-ordinate system is required. The co-ordinate system provides the scheme for the identification of all possible points on the screen. For example, the co-ordinate of the upper left corner of the screen is (0, 0). A coordinate pair is formed with a combination of x coordinate(i.e., horizontal coordinate) and y coordinate (i.e., vertical coordinate). The x coordinate denotes the distance moving right from upper left corner. All coordinates are expressed in integers. Graphics Context and Graphics Object Before drawing any shape on the screen, we need an environment that enables the process of drawing. We can get that environment by the help of GraphicsContext. Also, with the help of the GraphicsContext only, we cannot perform the operation of drawing. To achieve this we need the help of a graphics object. The graphics object manages the graphics context, i.e. the graphics object controls the process of drawing the information on the screen. As Graphics class is an abstract class, it cannot be instantiated.But a type of Graphics class (i.e., an object of graphics class) can be defined, by the help of the Component class present inside the java.awt package. The Graphics class makes use of three important methods of Component class for the purpose of creating erasing and updating the graphics. These methods are:  public void paint(Graphics gph) This method is used at the time of creation of graphics.  public void repaint() This method helps to erase the graphics.  public void update(Graphics gph)

449

By this method, we can update the graphics. We will go in details about the aforesaid methods in the Component class. Java.awt contains many methods to handle different operations related to graphics. Some of these methods are which are required for the basic operations related to graphics are give below:

 public void drawLine(int c1, int d1, int c2, int d2): It is used to draw a line, from the starting co-ordinate (c1, d1) to the ending co-ordinate (c2, d2).

 public void drawRect(int c1,int d1,int c2,int d2) It is used to draw a rectangle (the out lines only). Here (c1, d1) is the coordinate from where the drawing of rectangle starts. C2 and d2 represents the width and height respectively.  public void fillRect(int c1, int d1, int c2, int d2) This method is also used to draw a rectangle with its body shaded. Here also, (c1,d1) represents the starting point from where the drawing of the rectangle starts and c2 and d2 represents the width and height respectively.  public void drawOval(int c1, int d1, int c2, int d2) To draw the outlines of an oval, this method of the Graphics class is used.  public void fillOval(int c1, int d1, int c2, int d2) With the help of this method, a filled oval can be drawn on the screen. (c1,d1) denotes the starting coordinate from where the drawing starts. c2 and d2 represents the width and height respectively.

450

 Public void drawRoundRect(int c1,int d1 ,int c2 ,int d2 ,int c3 ,int d3) It is used to draw a the outlines of a rectangle, whose corners are in rounded format.  Public void drawRoundRect(int c1,int d1 ,int c2 ,int d2 ,int c3 ,int d3) It is used to draw a the outlines of a rectangle, whose corners are in rounded format.  public void fillRoundRect(int c1, int d1, int c2, int d2, int c3, int d3) It is used to draw a filled rectangle with its corners in rounded shape.  public void drawstring(String message, int c1, int c2) This method simply draws the specified string on the screen starting from the coordinate (c1, c2).  public void drawPolygon(int c1[], int c2[], int pnt) This method is used to draw a polygon on the screen. It takes two arrays and a point of integer type as the argument.  public void fillPolygon(int c1[], int c2[], int pnt) This method does the same operation of drawing a polygon, but unlike drawPolygon, this polygon is filled with the current color.

 public void drawArc(int c1, int d1,int c2,int d2, int c3, int d3) The job of this method is to draw an arc on the screen, which covers a rectangle that would be formed according to the parameters specified.  public void fillArc(int c1, int d1,int c2,int d2, int c3, int d3)

451

This method does the same operation as of the drawArc, but this time the arc will be filled with the current color.  Public void setColor(java.awt.Color RED) This method takes the predefined color constants of the Color class as the parameter and it is used to set the color of the object to be drawn. Example:import java.awt.*; import java.applet.*; public class A extends Applet { public void init() { System.out.println("Applet is initialized"); } public void paint(Graphics g) { g.drawLine(40,60,100,120); g.setColor(Color.red); g.fillOval(60,80,100,100); g.setColor(Color.green); g.fillRect(20,20,50,50); g.setColor(Color.magenta); g.fillRoundRect(120,120,80,80,10,12); g.setColor(Color.cyan); g.fillArc(150,150,98,98,40,60); int x[]={10,20,90,100,34}; int y[]={17,90,25,67,27}; g.setColor(Color.cyan); g.fillPolygon(x,y,5); g.setColor(Color.blue);

452

g.setFont(new Font("VERDANA",Font.BOLD+Font.ITALIC,25)); g.drawString("Hello GoodMorning",105,35); } } /*<applet code="A.class" width=400 height=400> </applet>*/

Output:-

Color class
Color is a predefined class present in the java.awt package. This class facilitates the user to make use of different colors provided by this class to color the graphics, set the background and foreground color of the component. The signature of this class is:

453

public class java.awt.Color extends java.lanag.Object implements java.awt.Paint, java.io.Serializable 13 predefined colors are provided by this class. Each color is a constant as specified by this class. These are:  public static final  public static final LIGHT_GRAY)  public static final  public static final DARK_GRAY)  public static final  public static final  public static final  public static final  public static final  public static final  public static final  public static final  public static final java.awt.Color white (or WHITE) java.awt.Color lightGray (or java.awt.Color gray (or GRAY) java.awt.Color darkGray (or java.awt.Color java.awt.Color java.awt.Color java.awt.Color java.awt.Color java.awt.Color java.awt.Color java.awt.Color java.awt.Color black (or BLACK) red (or RED) pink (or PINK) orange (or ORANGE) yellow (or YELLOW) green (or GREEN) magenta (or MAGENTA) cyan (or CYAN) blue (or BLUE)

we can also get different colors apart from using the above said color constants , by the help of the Constructor of the Color class, which takes three integer values within the range 0 to 255 values. These three integer values are collectively known as RGB (i.e. red-green-blue values.):  Color(int red, int green, int blue ) For example, We can get the color black by : new Color(0,0,0) We can get the color red by : new Color(255,0,0) We can get the color white by : new Color(255,255,255) There are also some other constructors of the Color class. These are:  Color(int)  Color(int,boolean)

454

 Color(float,float,float) This constructor also takes three values in Red-Green-Blue format. But the values are of float type and the value ranges between 0.0 and 1.0.  Color(java.awt.color.ColorSpace,float[],float)

The Color class is used by the methods of the Component class for setting the background and foreground colors. The mathods of Component class which use the Color class are  public void setBackground(java.awt.Color)  public void setForeground(java.awt.Color)

The Color class is also used by the Graphics class to set the color of the object to be drawn. The method is  public void setColor(java.awt.Color) Methods of Color class:  public Color brighter() It is used to get the brighter version of the current color.  public Color darker() It is used to get the darker version of the current color.  int getAlpha() Every color in java has an alpha value which ranges from 0 to 255. This method helps to retrieve the alpha value of the current color of the object.

Font class
The java.awt package contains Font class which provides the mechanism for setting the attributes of the font used in the Graphics class or in the Component class. The signature of this class is :

455

public class java.awt.Font extends java.lang.Object implements java.io.Serializable If the programmer does not want to use the Font class to manually handle the font, then the operating system, by default, provides support for the font. But if we want to manually adjust the font, then we have to use the Font class. The predefined constants provided by this class are y y y y y y y y public public public public public public public public static static static static static static static static final final final final final final final final int int int int int int int int PLAIN; BOLD; ITALIC; ROMAN_BASELINE; CENTER_ BASELINE; HANGING_ BASELINE; TRUETYPE_FONT; TYPE1_FONT;

Apart from these constants, three other variables are used to set the name, style and size of the font. These are y y y protected String name. protected int style. protected int size. There are also four constants to define the layout of the font on the screen. These are: public static final int LAYOUT_LEFT_TO_RIGHT public static final int LAYOUT_RIGHT_TO_LEFT public static final int LAYOUT_NO_START_CONTEXT public static final int LAYOUT_NO_LIMIT_CONTEXT

y y y y

Constructors of the Font class: y Font(String ftype, int fstyle, int fsize)

The first parameter ftype refers to the name of the font. The availability of Font varies from platform to platform. We can get the list of font available in different platform through String list_of_fonts [] = Toolkit.getDefaultToolkit().getFontList();

456

Here, the second parameter is used to specify the style of the font. This parameter is a constant defined in the Font class. The third parameter is used to specify the size of the font. We can set the font of Graphics class and Component class by the following method:public void setFont(Font fnt) public void paint(Graphics gph) { gph.setColor (Color.blue); Font fnt=new Font(Serif,Font.BOLD+Font.ITALIC,20); gph.setFont(fnt); }

Out of many methods available in the Font class, one of the most important methods is: y static Font getFont(String prop) This method is used to get the font of the text having the system property as of the property specified by prop. If the property does not exists, then it returns null.

Image class The java.awt package contains an abstract class, Image. This class provides the mechanism to handle the operations that are related to image. The signature for the Image class is: public abstract class java.awt.Image extends java.lang.Object The image class cannot be instantiated. Generally, we use the Image class to draw an image on the applet.

457

Image class supports only two types of image files: jpg format (Joint Photographic Expert Group format) gif format (Graphic Interchange Format ) The Image class also provides some constants which are used to the set the scale for the image. These are: public public public public public static static static static static final final final final final int int int int int SCALE_DEFAULT SCALE_FAST SCALE_SMOOTH SCALE_REPLICATE SCALE_AREA_AVERAGING

We can create an empty image by the help of a predefined method of Component class. The method is: public Image createImage(int imgwidth, int imgheight) Example: Image img1=createImage (200,200);

We can draw an image on the screen, by the help of one predefined method of Graphics class. The method is: public void drawImage(Image img, int i, int j, ImageObserver imob)

We can retrieve the image from a desired location by the help of one method, which is present in both the Applet and Toolkit class. The method is: public Image getImage(URL url) public Image getImage(URL url, String imgpath) Example: public void init() {

458

Image img1=getImage(getDocumentBase(),ABCD.jpeg); }

Example:-1 import java.awt.*; import java.applet.*; public class Image123 extends Applet { Image img; public void init() { img=createImage(300,200); Graphics gph=img.getGraphics(); gph.setColor(Color.orange); gph.fillRect(150,100,120,120); gph.setColor(Color.pink); gph.fillOval(90,100,70,70); } public void paint(Graphics g) { gph.drawImage(img,25,100,this); } }

459

/*<applet code="Image123" width=300 height=300> </applet>*/

Example-2 import java.awt.*; import java.applet.*; public class Image123 extends Applet { Image img; public void init() { img=getImage(getDocumentBase(),"CAKE.jpg"); } public void paint(Graphics gph) { gph.drawImage(im,30,50,this); }

460

} /*<applet code="Image123" width=300 height=300> </applet>*/

Component class
The java.awt package provides an abstract class Component which is used to represent the objects on the screen in a pictorial format. The signature of this class is: public abstract class java.awt.Component extends java.lang.Object implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable The Component class has many child classes and they are broadly classified into two categories: Visual Component

461

Menu Component

Visual Component There are 11 classes, which comes in the category of the Visual Component. These are: Button Canvas Choice Checkbox List Label FileDialog Scrollbar ScrollPane TextField TextArea Menu Component There are 5 classes, which comes in the category of the Menu Component. These are: Menu MenuBar MenuItem CheckboxMenuItem PopupMenu Button class The java.awt package contains a predefined class Button to develop push buttons, which can generate ActionListener on pushing upon it. The signature of this class is: public class java.awt.Button extends java.awt.Component implements javax.accessibility.Acceessible

462

A button can be given a label. Upon clicking the button, an instance of the ActionEvent is sent by the help of the method processEvent(), which generates the ActionListener. In order to achieve an action based performance on the button, the application has to implement the ActionListener interface and then register the listener, so that it can receive the events generated upon pushing the button. The listener can be registered by the help of the addActionListener() method. Constructos of the Button class: The Button class constructor is overloaded y Button() We can create a button with this constructor. But the button wont have any label. Here, the size of the button varies from one operating system to other. Button(String l) With this constructor, a button is created having a label l on it. Here, the button size depends on the label size.

Methods of Button class: Out of various methods of the Button class, the commonly used methods are: y public synchronized void addActionListener(java.awt.event.ActionListener)

To receive the event generated upon pushing the button, the listener is registered with the help of this method. public java.lang.String getActionCommand() When any event is fired upon pushing the button, the command name of the event can be retrieved by the method. public java.lang.String getLabel() The label of the button can be retrieved by the help of this method. protacted java.lang.String paramString()

463

The state of a button can be expressed by a parameter string. This method helps to retrieve this parameter string.

public void setLabel(java.lang.String) To set the label of an existing button, this method is used. The label will be set according to the string parameter. The Canvas class Canvas refers to a drawing area, where the components can be drawn. The drawing on the canvas is carried out by the paint() method. The Constructors of the Canvas Class: Canvas() Canvas(java.awt.GraphicConfiguration) Methods of the Canvas class: Out of the various methods of the Canvas class, the commonly used ones are: public void addNotify() a peer of the canvas is created with the help of this method. public void paint(java.awt.Graphics) a canvas can be repainted with the help of this method. The Choice class The java.awt package provides a Choice class by which we can have a popup menu, and from that menu, we can select only one item and only that selected item is visible to the user. Also we can have an arrow side to the item, clicking on which we can avail the list of items. The signature of this class is: Public class java.awt.Choice extends java.awt.Component implements java.awt.ItemSelectable, javax.accessibility.Accessible The Choice class generates one listener known as ItemListener.

464

The constructor of the choice class is: Choice() It help to instantiate the choice class. Methods of the Choice class: The Choice class contains various methods. The most commonly used methods are: public void add(java.lang.String) an item of String type can be added to the choice menu by this method. public void addItem(java.lang.String) This method is also used to add an item of String type to the choice menu. public java.lang.String getItem(int) This method helps to return the string from the choice menu, at the specified index. public int getItemCount() The total number of items present in the corresponding choice menu can be retrieved by this method. Public int getSelectedIndex() By this method the index of the selected item can be retrieved. public synchronized java.lang.String getSelectedItem() With the help of this method the currently selected item can be retrieved in String format. Public synchronized java.lang.Objects[] getSelectedObjects() This method returns an array of Object type having length 1. The array contains the currently selected items. public void insert(java.lang.String,int)

465

This method is used to insert the specified item at the specified position.

public void remove(int) We can delete one item from the choice menu according to the specified index by this method. public void remove(java.lang.String) This method is used to delete one item from the choice menu according to the specified. If there are more than one item with the same name, then the first occurrence of the item is deleted. public void removeAll() With the help of this method, we can erase all the items from the choice menu. public synchronized void select(int) This method is used to set the selected item to be the item at the specified position.

Checkbox class
The java.awt package provides a Checkbox class, which is used to develop checkboxes. A checkbox provides the facility of multiple selections. The signature of this class is: public class java.awt.Checkbox extends java.awt.Component implements java.awt.ItemSelectable, javax.accessibility.Accesseible The Checkbox class generates one listener known as ItemListener. The constructor of Checkbox class Checkbox() This constructor develops a checkbox without having any label on it. Checkbox(java.lang.String)

466

This constructor develops a checkbox with a label on it. Checkbox(java.lang.String, boolean) This constructor also develops a checkbox with a label on it. In addition to it, the state of the checkbox is also specified.

Methods of Checkbox The Checkbox class provides several methods to manipulate the checkbox. The commonly used methods are: public java.lang.String getLabel() This method returns the name or label of the checkbox. public boolean getState() The state of the checkbox in terms of boolean value is returned by this method. public void setLabel(java.lang.String) A label is attached to the checkbox, by this method. public void setState(boolean) A state is assigned to the checkbox with the help of this method We have another class that is related to the Checkbox class, i.e. CheckboxGroup. This class is used to develop radio buttons. In case of radio buttons, only a single item can be selected at a time. The signature of this class is: public class java.awt.CheckboxGroup extends java.lang.Object implements java.io.Serializable To generate radio buttons, we have to pass the object of the CheckboxGroup class in the constructor of the Checkbox class.

467

For example, CheckboxGroup cx=new CheckboxGroup(); Checkbox cb=new Checkbox(Male, cx, true);

FileDialog class
The java.awt class provides a class known as FileDialog. It is a child class of Dialog class. The signature of this class is: public class java.awt.FileDialog extends java.awt.Dialog This class is to display a dialog box on the screen, so that the user can choose a file from it. Until the dialog window is closed, rest of the application goes to a blocked state. The FileDialog is known as a modal dialog. A FileDialog has two modes: LOAD mode SAVE mode Constructor of FileDialog FileDialog(Frame) For the purpose of loading a file, a File Dialog is constructed by this constructor. FileDialog(Frame, String)

This constructor also does the same action as of the above. But, here the dialog window gets a label on it. FileDialog(Frame, String, int) With addition to the above action, here the mode for the file is specified, i.e. either FileDialog.LOAD or FileDialog.SAVE. Methods of FileDialog The commonly used methods of the FileDialog class are: public java.lang.String getFile()

468

This method is used to retrieve the file from the corresponding file dialog. getFileNameFilter() It is used to get the filtered file name from the file dialog. public int getMode() This method is used to get the mode of the concerned file dialog, i.e whether LOAD or SAVE. getDirectory() It is used to get the directory name of the concerned file dialog setDirectory(java.lang.String) The directory name of the concerned file dialog can be set by this method with the specified name. public void setFile(java.lang.String) We can set the specified file for the concerned file dialog by this method. public void setMode(int) We can set the specified mode for the concerned file dialog.

Label class
One of the simplest component in the java.awt package is the label. For setting the label of different GUI objects, this class is used. The signature of this class is: public class java.awt.Label extends java.awt.Component implements javax.accessibility.Accessible The Label class does not generate any listener. The constructors of the Label class are: Label(java.lang.String) This constructor is used to set the label with the specified name. Label(java.lang.String, int)

469

This constructor set the label with the specified name and the alignment. The alignment of the label can have three values which are constants and provided by this class. These are: Public static final int LEFT Public static final int CENTER Public static final int RIGHT

The methods of Label class The commonly used methods of the Label class are: public java.lang.String getText() This method is used to retrieve the text of the concerned label. public java.lang.String paramString() A label can be represented by a parameter string. It is the job of this method to return this parameter string. public void setText(java.lang.String) This method is used to set the text for the concerned label by the specified string.

List class
The java.awt package provides one class List, which enables the user to select more than one item. Also this class facilitates to visualize more than one item at a time. The signature of this class is: public class java.awt.List extends java.awt.Component implements java.awt.ItemSelectable, javax.accessibility.Accessible Constructors of List class List() It is used to develop a list of items, and the list can scroll. List(int)

470

A list of items can be developed with the specified number of visible line. The list can scroll. List(int, boolean) Here the lists with specified number of visible items are generated and a mode can be set also. The ActionListener and ItemListener are fired by the List. Methods of the List class The commonly used methods of the List class are: public void add(java.lang.String) We can attach one item, provided by the String parameter, at the end of the list by their method. Public void add(java.lang.String, int) With the help of this method, we can attach the String as one item at the specified position. public void addItem(java.lang.String) The jab of this method is same as that of the add() method. public void removeAll() This method is used to delete all the items from the list.

Scrollbar class
The java.awt package provides the Scrollbar class for the purpose of adjustment of the window of any GUI components. The signature of this class is:

471

public class java.awt.Scrollbar extends java.awt.Component implements java.awt.Adjustable, javax,accessibility.Accessible There are two constants declared in the Scrollbar class for setting the mode of the scrollbar. These are: public static final int HORIZONTAL public static final int VERTICAL The scrollbar generates one listener known as the AdjustmentListener. The constructors of the Scrollbar class are:

Scrollbar(int) This constructor develops one scroll bar with the specified mode, i.e. either HORIZONTAL or VERTICAL. Scrollbar(int, int, int, int, int) This constructor takes five parameters of integer type. The one sets the mode for the scrollbar. The second one decides the initial value for the scrollbar. The third parameter determines the size of the scrollbar. And the fourth and fifth parameters refer to the minimum and maximum values respectively, upto which the scrollbar can slide. Methods of the Scrollbar class Some of the commonly used methods of the Scrollbar class are: public int getMaximum() This method is used to retrieve the maximum value of the concerned scrollbar. public int getMinimum() This method is used to retrieve the minimum value of the concerned scrollbar. public int getOrientation() This method is used to retrieve the current orientation of the concerned scrollbar.

472

public int getPageIncrement() This method is used to retrieve the increment in pages of by the concerned scrollbar. public int getUnitIncrement() This method determines the increment in unit of the concerned scrollbar. public void getValue() We can retrieve the value of the concerned scrollbar by this method. public void setMaximum(int) Using this method, we can set the specified maximum value for the concerned scrollbar. public void setMinimum(int) Using this method, we can set the specified minimum value for the concerned scrollbar. public void setOrientation(int) The job of this method is to set the provided orientation for the scrollbar. public void setPageIncrement(int) Using this method, we can set the specified int value as the page increment value for the concerned scrollbar. public void setUnitIncrement(int) Using this method, we can set the specified int value as the unit increment value for the concerned scrollbar.

ScrollPane class
The java.awt package provides a predefined class ScrollPane, which is a window and that can fit only one component on it. The signature of this class is:

473

public class java.awt.ScrollPane extends java.awt.Container implements java.accessibility.Accessible We cannot attach more than one component to a ScrollPane. If the component is larger than the size of the ScrollPane window, then the ScrollPane automatically brings the scrollbar into existence. The scrollbar that will be generated, will have both the orientations. The constructors of the ScrollPane class ScrollPane() It develops a scrollpane, by default. ScrollPane(int) It generates a ScrollPane with the specification for displaying the scrollbar. For the conditional requirement of the scrollbar, this class declares three constants, namely Public static final int SCROLLBAR_ALWAYS Public static final int SCROLLBAR_AS_NEEDED Public static final int SCROLLBAR_NEVER

TextField class
The java.awt package provides a TextField class, which is used to take the users inputs in the text form in a single row only. The signature of this class is:
public class java.awt.TextField extends java.awt.TextComponent

If the text length exceeds to the TextField size, then visibility scrolls to the left. ActionListener, TextListener and FocusListener are generated by the TextField.

The constructors of the TextField class

474

TextField() This constructor develops the default TextField. The size of the TextField differs from one operating system to another. TextField(int) These constructor developers an empty TextField with the size specified by the parameter. TextField(java.lang.String) It generates a text field and there will be an already String type content according to the parameter specified. TextField(java.lang.String, int) It constructs a string with specified content and size. Out of the various methods of the TextField class, two of the most important methods are: public void setEchoChar(char) This method hides the letters that are typed in the TextField and shows the user the specified character only. This is commonly used when we try to enter our password for any account. public char getEchoChar() This method is used to retrieve the character.

TextArea class
The java.awt package provides a TextArea class, in which the user can write something two-dimensionally, i.e. both in column and row direction. The signature of this class is:

public class java.awt.TextArea extends java.awt.TextComponent

Two listeners can be generated by the TextArea, namely the TextListener and FocusListener

475

The TextArea class declares some constants in order to set the visibility of the scrollbar. These are: public public public public static static static static final final final final int int int int SCROLLBARS_BOTH SCROLLBARS_VERTICAL_ONLY SCROLLBARS_HORIZONTALLY SCROLLBARS_NONE

The constructors of the TextArea class TextArea() We can develop an empty TextArea by the help of this constructor. TextArea(int, int)

Here also, we can generate an empty TextArea, but the row and column size are specified.

TextArea(java.lang.String) This TextArea contains an initial String type message. TextArea(java.lang.String, int, int) A TextArea will be formed with an already content and the specified number of rows and columns.

Methods of TextArea The commonly used methods of the TextArea are: public java.lang.String getText() To retrieve the content of the TextArea, this method is used. public void setText(java.lang.String) This method is used to attach the specified text in the text area.

476

public java.lang.String getSelectedText() The job of this method is to return the selected text to the caller.

Example: import java.awt.*; import java.applet.*; public class Comp2 extends Applet { Button b1; Choice c1; Canvas cs1; Checkbox cb1,cb2,cb3,cb4; CheckboxGroup cbg; Label l1; List li1; Scrollbar sb1; ScrollPane sp1; TextField tf1; TextArea ta1; public void init() { setBackground(Color.pink);

477

b1=new Button("Interface"); b1.setBackground(Color.red); b1.setForeground(Color.white);

c1=new Choice(); c1.addItem("Male"); c1.add("Female");

cs1=new Canvas(); cs1.setSize(100,100); cs1.setBackground(Color.yellow); cs1.setVisible(true);

cb1=new Checkbox("C"); cb2=new Checkbox("Java",true);

cbg=new CheckboxGroup(); cb3=new Checkbox("Male",cbg,true); cb4=new Checkbox("Female",cbg,false);

l1=new Label("Enter Your Course");

li1=new List(3,true); li1.add("C");

478

li1.add("C++"); li1.add("Java"); li1.add(".Net");

sb1=new Scrollbar(Scrollbar.HORIZONTAL, 425,10,400,600);

sp1=new ScrollPane(); Button b11=new Button("Learn Java"); b11.setFont(new Font("Verdana",Font.BOLD,200)); sp1.add(b11);

tf1=new TextField(10);

ta1=new TextArea(10,10);

add(c1); add(ta1); add(sp1); add(li1); add(l1); add(sb1); add(tf1); add(b1);

479

add(cb1); add(cb2); add(cb3); add(cb4); add(cs1); } } /*<applet code="Comp2" width=300 height=260> </applet>*/ Output:-

480

Menu components:
The java.awt package provides various menu component to develop and manage the menus. All the applications regarding the menu must follow the three steps which are enlightened below: Step-1: y y y Step-2: y The Menu has to be constructed. y The MenuItem has to be constructed y The MenuItem has to be attached with the Menu. The Frame has to be constructed. The MenuBar has to be constructed. The MenuBar has to be attached with the Frame.

Step-3 y The Menu has to be attached in the MenuBar.

Let us have a brief look on the various menu components.

MenuBar class
The java.awt package contains a predefined class MenuBar to manage the topmost level of the window which contains the menu. The signature of the MenuBar class is: public class java.awt.MenuBar extends java.awt.MenuComponent implements java.awt.MenuContainer, javax.accessibility.Accessible In order to develop the MenuBar, first the MenuBar class has to be instantiated. MenuBar mnbr=new MenuBar();

481

Then the required number of selectable menus are to be added to the menu bar by the help of the add() method of the MenuBar class. Now the menu bar has to be attached with the Frame. Frame fm=new Frame(wordpad); fm.setMenuBar(mnbr);

Menu class
Menu is a predefined class present in the java.awt package. It is used to develop a pull-down menu containing a number of items that can be selected. The signature of the Menu class is: public class java.awt.Menu extends java.awt.MenuItem implements java.awt.MenuContainer, javax.accessibility.Accessible The constructed of the Menu class is Menu(java.lang.String) The Menu can be instantiated as Menu mn=new Menu(true); Here, the constructor of the Menu class takes a String type parameter which is used as the label of the Menu object. Then the menu items are added by the help of the add() method. mn.add(item_1); mn.add(item_2); Then the Menu is added to the MenuBar. Mnbr.add(mn); The methods of the Menu class: y Public void add(java.awt.MenuItem)

482

By the help of this method, an object of the MenuItem can be attached with the Menu component. y public void add(java.lang.String)

By the help of this method, a string can be added with the Menu component. y Public void addSeparator()

This method helps to add a separator to the Menu component. y public void remove(int)

We can delete one item from the Menu according to the specified index.

MenuItem class
The java.awt package provides the MenuItem class in order to give the final touch to the development process of the Menu system. The signature of this class is: public class java.awt.MenuItem extends java.awt.MenuComponent implements javax.accessibility.Accessible The constructor of this class is y MenuItem(java.lang.String)

This constructor is used to develop a menu item which is having a label as specified by the String parameter. To instantiate the class, we can write MenuItem mnitm=new MenuItem(open); Then the MenuItem has to be added with the Menu by the add() method. Mn.add(mnitm); Methods of the MenuItem class

483

public string getLabel()

The label of the menu item can be retrieved and returned in the form of a String by this method. y public void setLabel(java.lang.String)

The label of the menu item can be set as the specified String by the help of this method. y public void setEnabled(boolean)

The label of the menu item can be made selectable or deselect-able according to the boolean parameter. If it is true, then the item can be selected, otherwise not.

CheckboxMenuitem class
The CheckboxMenuItem is a child class of the MenuItem class. It generates a dual state for the MenuItem components. The MenuItems state can be managed by this class. We can toggle on or off the MenuItem, just by clicking the CheckboxMenuItem. The signature of this class is: public class java.awt.CheckboxMenuItem extends extends java.awt.Menutem implements java.awt.ItemSelectable, javax.accessibility.Accessible The constructor of this class is CheckboxMenuItem(java.lang.String) The methods of this class are: public boolean getState() The job of this method is to check the state of the Menu item. If the CheckboxMenuItem is selected, then the method returns true, otherwise it returns false. public void setState(boolean)

484

This method is used to set the state of the MenuItem. If true is passed as parameter, then the CheckboxMenuItem gets selected, otherwise, it remains unselected. Example-1 import java.awt.*; public class Pull extends Frame { Menu m,sub; MenuBar bar; MenuItem item1,item2,item3,item4,item5; CheckboxMenuItem cb1; Pull() { Frame f=new Frame("Menu Demo"); f.setLayout(new GridLayout(1,1)); bar=new MenuBar(); f.setMenuBar(bar); //step-1

m=new Menu("File") ; sub=new Menu("Edit");

item1=new MenuItem("new"); item2=new MenuItem("print"); item3=new MenuItem("Quit"); item4=new MenuItem("edit");

485

item5=new MenuItem("Cut");

cb1=new CheckboxMenuItem("ok");

m.add(item1); //step-2 m.addSeparator(); m.add(item2); m.add(item3);

sub.add(item4); sub.addSeparator(); sub.add(item5); sub.add(cb1);

bar.add(m); //step-3 bar.add(sub);

f.setSize(300,300); f.setVisible(true); } public static void main(String args[]) { Pull p=new Pull(); }

486

} Output:-

Container component:
The java.awt package provides a class Container which extends to the Component class. The signature of this class is: public class Container extends java.awt.Component An AWT Container object is used for the purpose of containing the AWT components. To display the components on the screen, it is mandatory to attach the components in a container. A list is maintained for the GUI components that are added to the container. The order of the list determines the components occupancy inside the container. If a component is attached to the container without having any index, then that component will be placed at the end of the list. Methods of the Container class: Component add(Component c): Add the component in the container

487

Component add(Component c, int index): Add the component in a container in a specified position Component add(String name, Component comp): Add the component in the container int countComponents(): This method counts how many components are present in the container Component getComponent(int n): Gets the nth component in the container int getComponentCount(): Gets the number of component in the container void remove(Component comp): Removes the component from the container void setLayout(LayoutManager lm): Sets the layout for the container void removeAll(): Remove all the component from the container

The Container class has some child classes. The hierarchy of the child classes is shown in the figure below:

488

The Container class is divided into five containers. They are y y y y y Panel Window Applet Frame Dialog

Here, the Panel and Window are considered as light weight containers. The Applet, Frame and the Dialog are heavy weight containers. According to java, the components that are attached to the light weight containers are not visible. To make them visible, we have to attach the light weight containers in the heavy weight containers. So for visibility, the light weight containers are to be nested with the heavy weight containers. For example, the container Panel can contain any component and another panel. But it is not visible to the user. To make it visible, we have to attach the panel with the Applet.

489

Let us have a brief discussion about the containers.

Panel class:
The java.awt package provides a class Panel. This class extends the Container class and therefore becomes a container itself. The signature of this class is: public class java.awt.Panel extends java.awt.Container implements javax.accessibility.Accessible Panel is considered as a light weight container in java. It can contain different components as well as other panels also. But, an user cannot visualize the Panel itself. In order to make the panel visible to the users, we have attach the panel with any of the heavy weight containers like Applet, Frame or Dialog according to our convenience. The constructor of the Panel calss is: y Panel()

Window class
The java.awt package provides a class Window, which also extend the java.awt.Container class and therefore acts as a container itself. The signature of this class is: public class java.awt.Window extends java.awt.Container implements javax.accessibility.Accessible The Window is considered as a light weight container. So the user cannot visualize it. In ordered to make it visible, we have to attach the Window with any heavy weight container like Frame. The constructors of the Window class are: y y Window() Window(java.awt.Frame)

Applet class

490

Applet is a class provided by the java.applet package. In java, the Applet is considered as a heavy weight container. So applet is visible to the user. The applets can be executed on the web browsers. Applets do not have any constructor. Also they do not have their own main() method. To know in details about the Applet class, refer to the java.applet package.

Frame class
The java.awt class provides a class Frame, which extends to the Window class and therefore acts as a container itself. The signature of this class is: public class java.awt.Frame extend java.awt.Window implements java.awt.MenuContainer Frame is considered as a heavy weight container. That is why, a frame is visible to the user. Frame cannot be executed on the browser. It is only meant for the standalone application. So, it cannot support the web-enabled applications. The constructors of the Frame class: y Frame() It is used to generate a frame without any title. y Frame(java.lang.String) This constructor is used to generate a frame, having a title as specified by the String type parameter. To properly execute the Frame application, it is mandatory for the programmer to use two methods of the Component class. These two methods are: y y public void setSize(int, int) public void setVisible(booean)

491

Example:
import java.awt.*; public class Frame1 extends Frame { Button b1; Choice c1; List l1; ScrollPane sp1; public Frame1() { Frame f1=new Frame("Frame Demo"); b1=new Button("Interface"); b1.setFont(new Font("Arial",Font.BOLD,20)); c1=new Choice(); c1.addItem("Male"); c1.addItem("Female"); l1=new List(3,true); l1.add("C"); l1.add("C++"); l1.add("Java"); l1.add(".Net"); sp1=new ScrollPane(); Button b2=new Button("Java Is A Language"); b2.setFont(new Font("Arial",Font.BOLD,140)); sp1.add(b2);

492 f1.setLayout(new FlowLayout()); f1.add(sp1); f1.add(c1); f1.add(l1) ; f1.add(b1); f1.setSize(300,280); f1.setVisible(true); } public static void main(String args[]) { new Frame1(); } } Output:

Dialog class

493

The java.awt package provides a class Dialog. The main job of this class is to develop the dialog boxes. The signature of the Dialog class is: public class java.awt.Frame extend java.awt.Window As the Dialog class extends the Window class, it becomes a container. In java, Dialog is considered as a heavy weight container. So, is visible to the users. The dialog boxes can be made modal according to the programmers choice. If it is made modal, then all other components will be blocked till the dialog box is active. The constructors of the Dialog class are: y y Dialog(java.awt.Frame) Dialog(java.awt.Frame, java.lang.String, boolean b)

Example
import java.awt.*; import java.awt.event.*; public class Dial extends Frame implements ActionListener { Frame f; TextField t1,t2; Button b1; Box bx; String s; Dial() {

494 f=new Frame("Display"); bx=new Box(f,"Dialog Box",true); t1=new TextField(20); t2=new TextField(20); b1=new Button("OK"); b1.addActionListener(this); f.setLayout(new FlowLayout()); f.add(t1);f.add(t2);f.add(b1); f.setVisible(true); f.setSize(500,500); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { String s=t1.getText(); if(s==null || s.equals("")) { bx.setSize(200,200); bx.setVisible(true); } } } public static void main(String ars[]) { Dial d=new Dial();

495 } } class Box extends Dialog implements ActionListener { Label l; Panel p1,p2; Button b; Box(Frame f,String s,boolean bb) { super(f,s,bb); p1=new Panel(); p2=new Panel(); l=new Label("Plz Enter Data"); p1.add(l); b=new Button("OK"); p2.add(b); setLayout(new GridLayout(2,1)); add(p1); add(p2); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b) setVisible(false); }

496 }

Output:-

LayoutManager
The java.awt package provides an interface LayoutManager, which facilitates the programmer to place the components in the suitable location. The preferred size of the java components differs from one platform to another. So, it is the job of the LayoutManager to look after the preferred size of the java components. The signature of the LayoutManager is: public interface java.awt.LayoutManager There are five child classes of the LayoutManager, which are used for various layout management process. The child classes are: y y y y y FlowLayout BorderLayout GridLayout CardLayout GridbagLayout

497

FlowLayout class
The java.awt package provides a class FlowLayout, which implements the FlowlayoutManager. The signature for FlowLayout is: public class java.awt.FlowLayout extends java.lang.Object implements java.awt.LayoutManager, java.io.Serializable FlowLayout provides five constants for the arrangement of the layout of the components. These are: y y y y y public public public public public static static static static static final final final final final int int int int int LEFT RIGHT CENTER LEADING TRAILING

The FlowLayout supports two types of java components. These are: y y Applet Panel

The constructors for the FlowLayout are: y FlowLayout() This constructor helps to develop a layout, which is having the center alignment. There wii be a padding of 5 pixels between the components. FlowLayout(int) By calling this constructor a new layout is developed with the specified alignment. FlowLayout(int, int, int)

This constructor also generates a layout with the specified alignment, i.e. the first parameter. Here, the second and the third int parameters denote the horizontal and vertical padding respectively.

498

In case of FlowLayout, the components are attached horizontally. If there wii be no more space, then the next component to be attached moves to the next line with the corresponding alignment. The default alignment of Flowlayout is considered to be CENTER.

import java.awt.*; public class Flow extends Frame { public Flow() { setLayout(new FlowLayout()); add(new Label("Name")); add(new TextField(10)); add(new Button("Send")); setVisible(true); setSize(300,300); } public static void main(String args[]) { Flow f=new Flow(); } }

Output:

499

BorderLayout class
The java.awt package provides another class to manage the layout of the components like Frame, Window and Dialog. This class is known as BorderLayout. The signature of this class is: public class java.awt.BorderLayout extends java.lang.Object implements java.awt.LayoutManager2, java.io.Serializable

The BorderLayout class provides some constants to specify the regions. The constants are: y y y y y y y y y y y y y Public Public Public Public Public Public Public Public Public Public Public Public Public static static static static static static static static static static static static static final final final final final final final final final final final final final java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String java.lang.String NORTH SOUTH EAST WEST CENTER BEFORE_FIRST_LINE AFTER_LAST_LINE BEFORE_LINE_BEGINS AFTER_LINE_ENDS PAGE_START PAGE_END LINE_START LINE_END

The constructor of this class is: y BorderLayout()

This constructor generates a new border layout without any gap between the components. y BorderLayout(int, int)

500

This constructor generates a new border layout, with the horizontal and vertical gap as specified by the parameters. The BorderLayout class does not provide any relaxation for the preferred size. To explicitly set the layout as BorderLayout, the programmer has to make use of the method: public void setLayout(BorderLayout blt)

Methods of the BorderLayout class y public int getHgap()

This method determines the horizontal gap between the components. y public int getVgap()

This method determines the vertical gap between the components. y public void setHgap(int)

This method provides a specific Horizontal gap between the java components. y public void setVgap(int)

This method provides a specific vertical gap between the java components.

Example:
import java.applet.*; import java.awt.*; public class Border extends Applet

501 { public void init() { setLayout(new BorderLayout()); Button b1=new Button("North"); Button b2=new Button("South"); Button b3=new Button("East"); Button b4=new Button("West"); Button b5=new Button("Center");

add(b1,BorderLayout.NORTH); add(b2,BorderLayout.SOUTH); add(b3,BorderLayout.EAST); add(b4,BorderLayout.WEST); add(b5);

} } /*<applet code="Border" width=300 height=300> </applet>*/

Output:

502

GridLayout class
The java.awt package contains the GridLayout. The signature of this class is: public class java.awt.GridLayout extends java.lang.Object implements java.awt.LayoutManager, java.io.Serializable

The GridLayout class, by default, does not support to any Container. Also, the GridLayout class does not provide any support for the preferred size. The GridLayout works like a spreadsheet. All the components in case of the GridLayout acquires same size. The constructors of the GridLayout class are: y GridLayout()

This constructs creates a new grid layout, with the default specifications.

503

GridLayout(int, int)

By the help of this method we can generate a grid layout with specified size of rows and columns. Methods of the GridLayout class y public int getColumns()

We can determine the number of columns in the concerned layout by this method. y public int getRows()

The number of rows of the concerned layout can be derived by this method. y public int getHgap()

This method is used to determine the horizontal gap between the components in the concerned layout. y public int getVgap

This method is used to determine the vertical gap between the components in the concerned layout. y public void setColumns(int)

This method is used to set the specified value for the number of columns in the concerned grid layout. y public void setRows()

This method is used to set the specified value for the number of rows in the concerned grid layout. y public void setHgap()

This method is used to set the specified value for the horizontal gap between the components in the concerned grid layout.

504

public void setVgap()

This method is used to set the specified value for vertical gap between the components in the concerned grid layout.

Example

import java.awt.*; public class Grid extends Applet { public void init() { Button b1=new Button("Button-1"); Button b2=new Button("Button-2"); Button b3=new Button("Button-3"); Button b4=new Button("Button-4");

setLayout(new GridLayout(2,2,5,10)); add(b1); add(b2); add(b3); add(b4);

setBackground(Color.lightGray);

505 } } /*<applet code="Grid" width=300 height=300> </applet>*/

Output:

CardLayout class

The java.awt package provides the CardLayout class by the help of which, only one component can be made visible at a time. The signature for this class is:

506

public class java.awt.CardLayout extends java.lang.Object implements java.awt.LayoutManager, java.io.Serializable The CardLayout, by default, does not support any container. In case of CardLayout, more than one component can be attached. It does not provide support for the preferred size. CardLayout provides some predefined methods , by the help of which we can see other components. The methods are void next() This method is used to visit the next component of the current component.

void previous() This method is used to visit to the previous component of the current displayed component. void first() This method is used to visit the first attached component of the layout. void last() This method is used to visit the last component of the layout.

The constructor of the CardLayout is CardLayout() By this constructor, we get a new CardLayout with default specifications. CardLayout(int, int) By the help of this constructor, a new CardLayout with specified horizontal and vertical paddings will be generated.

507

Example:
import java.awt.*; import java.awt.event.*; import java.applet.*; public class CardDemo extends Applet implements ActionListener { Panel p,p1,p2,p3; Button b1,b2; CardLayout cl; public void init() { p=new Panel(); cl=new CardLayout(); p.setLayout(cl);

p1=new Panel(); Label l1=new Label("Panel-1"); l1.setBackground(Color.yellow); l1.setForeground(Color.red); l1.setFont(new Font("Sans Serif",Font.BOLD,40)); p1.add(l1);

Label l2=new Label("Panel-2"); l2.setBackground(Color.blue);

508 l2.setForeground(Color.white); l2.setFont(new Font("Arial",Font.BOLD,40)); p2=new Panel(); p2.add(l2);

p3=new Panel(); p3.setBackground(Color.green); p3.setForeground(Color.black); Label l3=new Label("Panel-3"); l3.setFont(new Font("Verdana",Font.BOLD,40)); p3.add(l3); p.add(p1,"First"); p.add(p2,"Second"); p.add(p3,"Third"); b1=new Button("NEXT"); b1.addActionListener(this); b2=new Button("Previous"); b2.addActionListener(this);

add(p); add(b1); add(b2); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1)

509 { cl.next(p); }else{ cl.previous(p); } } } /* <applet code="CardDemo" width=500 height=500> </applet> */

GridBagLayout class
This is a predefined class of java.awt package which implements the LayoutManager interface. The signature of this class is: public class java.awt.GridBagLayout extends java.lang.Object implements java.awt.LayoutManager2, java.io.Serializable In case of GridBagLayout, the entire container is divided into cells of equal size. In this case a component can occupy more than one cells at a time. the area occupied by the component is known as the display area.

510

Here, the size of the components can be adjusted according to our requirement. The adjustment mode is denoted by FILL. When the component is smaller than its display area, then the placement of the component is decided by the anchor.

The values of the anchor are: j j j j j j j j j GridBagConstraints.CENTER GridBagConstraints.NORTH GridBagConstraints.NORTHEAST GridBagConstraints.EAST GridBagConstraints.SOUTHEAST GridBagConstraints.SOUTH GridBagConstraints.SOUTHWEST GridBagConstraints.WEST GridBagConstraints.NORTHWEST

Example:
import java.awt.*; import java.applet.*; public class GridbagTest extends Applet { TextField tf1,tf2,tf3,tf4; Label l1,l2,l3,l4,l5; Button b1; public void init() { l1=new Label("Collect The Information") ;

l1.setFont(new Font("Verdana",Font.BOLD,24)); l2=new Label("Enter Your Name");

511 l2.setFont(new Font("Verdana",Font.BOLD,14)); l3=new Label("Enter Your City"); l3.setFont(new Font("Verdana",Font.BOLD,14)); l4=new Label("Enter Your State"); l4.setFont(new Font("Verdana",Font.BOLD,14)); l5=new Label("Enter Mobile Number"); l5.setFont(new Font("Verdana",Font.BOLD,14));

tf1=new TextField(15); tf2=new TextField(15); tf3=new TextField(15); tf4=new TextField(15);

b1=new Button("Submit");

GridBagLayout gbag=new GridBagLayout(); GridBagConstraints gbc=new GridBagConstraints(); setLayout(gbag);

gbc.weighty=1.0; gbc.gridwidth=GridBagConstraints.REMAINDER; gbc.anchor=GridBagConstraints.NORTH; gbag.setConstraints(l1,gbc) ; gbc.anchor=GridBagConstraints.EAST;

gbc.gridwidth=GridBagConstraints.RELATIVE;

512 gbag.setConstraints(l2,gbc) ; gbc.gridwidth=GridBagConstraints.REMAINDER; gbag.setConstraints(tf1,gbc);

gbc.gridwidth=GridBagConstraints.RELATIVE; gbag.setConstraints(l3,gbc) ; gbc.gridwidth=GridBagConstraints.REMAINDER; gbag.setConstraints(tf2,gbc);

gbc.gridwidth=GridBagConstraints.RELATIVE; gbag.setConstraints(l4,gbc) ; gbc.gridwidth=GridBagConstraints.REMAINDER; gbag.setConstraints(tf3,gbc); gbc.gridwidth=GridBagConstraints.RELATIVE; gbag.setConstraints(l5,gbc) ; gbc.gridwidth=GridBagConstraints.REMAINDER; gbag.setConstraints(tf4,gbc); gbc.anchor=GridBagConstraints.CENTER; gbag.setConstraints(b1,gbc); add(l1); add(l2); add(tf1); add(l3); add(tf2); add(l4); add(tf3);

513 add(l5); add(tf4); add(b1); } } /*<applet code="GridbagTest" width=300 height=300> </applet>*/

514

Event Handling
The program is able to respond some dynamic actions in an interactive environment. Clicking on the mouse, pressed the key, select an item from List is an example of performing actions. The fundamentals of event-driven programming are used to translate events to code. In an Object oriented approach it is also possible to handle events. In java AWT when an user generates an action, then AWT generates an event and communicates these events to event handlers. Then the event handlers can respond to the events. There are two popular model was used to handle event in java. y y 1.0 model or Hierarchical model 1.2 model or Delegation model

In 1.0 model the total event handling procedure is done through two methods action( ) and handleEvent ( ) method. action( ) method having three parameters namely the event name that has been occurred, the x and y co-ordinates at which this event occurred. handleEvent ( ) method is implicitly called for every event object. This model having various problems and the problems are solved through 1.2 model.

Event Delegation Model


In event delegation model, an event is fired from a source object to a Listener object by invoking a methods on the listener and passing in the instance of the event subclass which defines the event type generated. When an event is fired, it is received by one or more listener that acts on that event. Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. j In java Listener is an object that implements a specific EventListener interface and extended from the generic java.util.EventListener. j Each and every EventListener interface having one or more methods that are to be invoked by the event source in response to each specific event type handled by the interface.

515

j An Adapter class is an anonymous inner class that includes all methods specified by the corresponding interface but not providing any functionality. Types of event handling The AWT provides two conceptual types of events such as low-level event and semantic event. Low-level event A low-level event is one that represents a low-level input or window-system occurrence on a visual component on the screen. The low-level event classes defined by the AWT are as follows: j ComponentEvent (component resized, moved, etc .) j FocusEvent (component got focus, lost focus ) j InputEvent j KeyEvent (component got key-press, key-release, etc.) j MouseEvent (component got mouse-down, mouse-move, etc.) j ContainerEvent j WindowEvent The low-level event listeners are as follows: j j j j j j j ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener

Semantic Events Semantic Events are defined at a higher level to encapsulate the semantics of a user interface components model. The semantic Events classes defined by the AWT are as follows:

j ActionEvent (do a command); j AdjustmentEvent (value was adjusted); j ItemEvent (item state has changed);

516

j TextEvent (the value of the text object changed)

The semantic listener interfaces defined by the AWT are as follows

j ActionListener j AdjustmentListener j ItemListener j TextListener Let us have a brief look on the 11 listener suggested by the event delegation model. 1. ActionListener:This is one interface suggested by the event delegation model. This interface is declared within the java.awt.event package. The signature for this interface is: public interface java.awt.event.ActionListener extends java.util.EventListener This interface provides the declaration for an abstract method: public abstract void actonPerformed(java.awt.event.ActionEvent) This method is used to receive the action events. Example:import java.applet.*; import java.awt.*; import java.awt.event.*; //1st step public class Button1 extends Applet implements ActionListener //2nd step { Button b1,b2,b3; public void init()

517

{ b1=new Button("Red"); b2=new Button("Green"); b3=new Button("Blue"); //3rd step b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); add(b1); add(b2); add(b3); } //step-4 public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { setBackground(Color.red); }else if(ae.getSource()==b2) { setBackground(Color.green); }else{ setBackground(Color.blue); }

518

} } /*<applet code="Button1" width=220 height=200> </applet>*/

2. ItemListener This interface also inhabits inside the java.awt.event package. The signature for this interface is: public interface java.awt.event.ItemListener extends java.util.EventListener The interface contains the declaration of an abstract method : public abstract void itemStateChanged(java.awt.event.ItemEvent) This method is used to receive the events generated from the Checkbox, Choice and List.

Example:-

519

import java.awt.*; import java.awt.event.*; import java.applet.*; public class Radio extends Applet implements ItemListener { CheckboxGroup cbg; Checkbox cb1,cb2,cb3,cb4; String msg=""; public void init() { cbg=new CheckboxGroup(); cb1=new Checkbox("Oracle",cbg,true); cb2=new Checkbox("Sybase",cbg,false); cb3=new Checkbox("Infomix",cbg,false); cb4=new Checkbox("DB2",cbg,false); cb1.addItemListener(this); cb2.addItemListener(this); cb3.addItemListener(this); cb4.addItemListener(this); add(cb1); add(cb2); add(cb3); add(cb4); }

520

public void itemStateChanged(ItemEvent ae) { repaint(); } public void paint(Graphics g) { msg="Current Selected Item Is "; msg+=cbg.getSelectedCheckbox().getLabel(); g.drawString(msg,170,120); } } /*<applet code="Radio" width=400 height=400> </applet>*/

3. AdjustmentListener

521

This interface is provided in the java.awt.event. The signature for this interface is : public interface java.awt.event.AdjustmentListener extends java.util.EventListener

The AdjustmentListener contains the declaration of one abstract method. The method is: public void adjustmentValueChanged(java.awt.event.AdjustmentEvent) This method is used to receive the events generated by the component Scrollbar.

Example:public class Scroll extends Applet implements AdjustmentListener { Scrollbar h1,h2,v1,v2; Panel p1; TextField tf1; public void init() { setLayout(new BorderLayout()); h1=new Scrollbar(Scrollbar.HORIZONTAL,1,1,1,200); h1.addAdjustmentListener(this); add(h1,BorderLayout.NORTH);

522

h2=new Scrollbar(Scrollbar.HORIZONTAL,1,1,1,200); h2.addAdjustmentListener(this); add(h2,BorderLayout.SOUTH);

v1=new Scrollbar(Scrollbar.VERTICAL,1,1,1,200); v1.addAdjustmentListener(this); add(v1,BorderLayout.WEST);

v2=new Scrollbar(Scrollbar.VERTICAL,1,1,1,200); v2.addAdjustmentListener(this); add(v2,BorderLayout.EAST);

p1=new Panel(); tf1=new TextField(18); p1.add(tf1); add(p1); } public void adjustmentValueChanged(AdjustmentEvent ae) { if(ae.getAdjustable()==h1) { h1.setValue(h1.getValue()); h2.setValue(h1.getValue()); tf1.setText("Horizontal Location :- "+h1.getValue());

523

} if(ae.getAdjustable()==v1) { v1.setValue(v1.getValue()); v2.setValue(v1.getValue()); tf1.setText("Vertical Location :- "+v1.getValue()); } if(ae.getAdjustable()==h2) { h2.setValue(h2.getValue()); h1.setValue(h2.getValue()); tf1.setText("Horizontal Location :- "+h2.getValue()); } if(ae.getAdjustable()==v2) { v2.setValue(v2.getValue()); v1.setValue(v2.getValue()); tf1.setText("Vertical Location :- "+v2.getValue()); } } }

Output:

524

4. TextListener The TextListener is an interface suggested by the event delegation model and present in the java.awt.event package. The signature of this method is: public interface java.awt.event.TextListener extends java.util.EventListener The interface contains one abstract method which is declared as: public void textValueChanged(java.awt.event.TextEvent) This method has to be defined in ordered to receive the events generated by the components TextField and TextArea.

Example:import java.awt.*; import java.awt.event.*;

525

import java.applet.*; public class CopyText extends Applet implements TextListener { TextArea t1,t2; public void init() { t1=new TextArea(10,10); t2=new TextArea(10,10); t1.addTextListener(this); t2.addTextListener(this); add(t1); add(t2); } public void textValueChanged(TextEvent te) { t2.setText(t1.getText()); } } /* <applet code="CopyText" width=400 height=400> </applet> */

526

5. FocusListener The FocusListener is an interface present inside the java.awt.event package. The signature of this class is: public interface java.awt.event.FocusListener extends java.util.EventListener This interface provides the declaration for two abstract methods: y y public void focusGained(java.awt.event.FocusEvent) public void focusLost(java.awt.event.FocusEvent)

Suppose, there are two text fields attached to the screen. But, the user can write in a single text field at a time. So, the textfield which will be in use, is associated with the focusGained() method and the other textfield which is not in use at that particular point of time, is associated with the focusLost() method. The two abstract methods of the FocusListener interface are used to receive the events generated by the TextArea, TextField, Button and Choice Components. 6. KeyListener

527

This interface is also present in the java.awt.event package. The signature of this interface is: public interface java.awt.event.KeyListener extends java.util.EventListener

The abstract methods present inside this interface are y y y public void keyPressed(java.awt.event.KeyEvent) public void keyReleased(java.awt.event.KeyEvent) public void keyTyped(java.awt.event.KeyEvent)

All of the above methods are used in case of a key pressed, released or typed. 7. MouseListener This interface is suggested by the event delegation model and situated in the java.awt.event package. The signature of this interface is: public interface java.awt.event.MouseListener extends java.util.EventListener There are five abstract methods declared in this interface. These are: public void mouseEntered(java.awt.event.MouseEvent) public void mouseExited(java.awt.event.MouseEvent) public void mousePressed(java.awt.event.MouseEvent) public void mouseReleased(java.awt.event.MouseEvent) public void mouseClicked(java.awt.event.MouseEvent) All of the above methods are to be defined in the corresponding child classes in order to handle the events generated by the mouse. 8. MouseMotionListener y y y y y The MouseMotionListener is used to handle the events generated by all type of components. The signature for this interface is: public interfaced java.awt.event.MouseMotionListener extends java.util.EventListener There are two abstract methods declared in this interface. These are

528

y y

public void mouseDragged(java.awt.event.MouseEvent) public void mouseMoved(java.awt.event.MouseEvent)

Example:import java.awt.*; import java.applet.*; import java.awt.event.*; public class CanvasDemo extends Applet implements MouseListener,MouseMotionListener { int x,y; GraphCanvas gc; public void init() { gc=new GraphCanvas(); gc.setVisible(true); gc.setLocation(100,100); gc.setBackground(Color.blue); gc.setSize(300,200); add(gc); addMouseListener(this); addMouseMotionListener(this); } public void mouseDragged(MouseEvent me) {

529

x=me.getX(); y=me.getY(); gc.setLocation(x,y); } public void mouseMoved(MouseEvent me) { } public void mouseClicked(MouseEvent me) { x=me.getX(); y=me.getY(); gc.setLocation(x,y); } public void mouseEntered(MouseEvent me) {} public void mouseExited(MouseEvent me) {} public void mousePressed(MouseEvent me) {} public void mouseReleased(MouseEvent me) {} } class GraphCanvas extends Canvas { public void paint(Graphics g) { g.setColor(Color.white); g.setFont(new Font("Sans Serif",Font.BOLD,30));

530

g.drawString("Painting On Canvas",10,40); g.setColor(Color.pink); g.fillRect(40,50,40,50); } } /* <applet code="CanvasDemo" width=500 height=500> </applet> */

9. ContainerListener

531

This interface is suggested by the event delegation model and situated in the java.awt.event package. The signature for this interface is: public interface java.awt.event.ContainerListener extends java.util.EventListener The ContainerListener provides the mechanism to receive the event generated by all types of containers. This interface declares two methods. These are: y y public void componentAdded(java.awt.event.ContainerEvent) public void componentRemoved(java.awt.event.ContainerEvent)

10.

ComponentListener

This interface is suggested by the event delegation model and inhabits in the java.awt.event package. The signature of this class: public interface java.awt.event.ComponentListener extends java.util.EventListener This interface provides four methods which are to be defined in ordered to provide the mechanism for handling the events generated by all types of components. The methods are: y y y y public public public public void void void void componentShown(java.awt.event.ComponentEvent) componentHide(java.awt.event.ComponentEvent) componentResized(java.awt.event.ComponentEvent) componentMoved(java.awt.event.ComponentEvent)

11.

WindowListener

This is the last listener interface provided by the event delegation model and placed in the java.awt.event package. The signature of this interface is: public interface java.awt.event.WindowListener extends java.util.EventListener

532

There are seven methods declared in this interface for handling the events. These are: y y y y y y y public public public public public public public void void void void void void void windowActivated(java.awt.event.WindowEvent) windowDeactivated(java.awt.event.WindowEvent) windowIconified(java.awt.event.WindowEvent) windowDeiconified(java.awt.event.WindowEvent) windowClosed(java.awt.event.WindowEvent) windowClosing(java.awt.event.WindowEvent) windowOpened(java.awt.event.WindowEvent)

Example:import java.awt.*; import java.awt.event.*; public class WindowDemo extends Frame implements WindowListener { Frame f1; public WindowDemo() { f1=new Frame("Winow Event"); f1.addWindowListener(this); f1.setSize(200,200); f1.setVisible(true); } public void windowActivated(WindowEvent we) {

533

} public void windowDeactivated(WindowEvent we){} public void windowIconified(WindowEvent we){} public void windowDeiconified(WindowEvent we){} public void windowClosed(WindowEvent we){} public void windowClosing(WindowEvent we) { System.exit(0); } public void windowOpened(WindowEvent we){} public static void main(String args[]) { WindowDemo d=new WindowDemo(); } }

Adapter class The main problem that arises in delegation model is that each and every Listener is treated as interface and in interface every methods are implicitly public and abstract. As each and every method of Listeners are implicitly abstract so the programmer is bound to override all the methods present in the inherited Listener. To avoid the problem sun microsystem introduced adapter class for each and every listener that have more than one methods. Adapter classes are treated as anonymous inner class. An adapter class implements event listeners. But the over ridden methods present there in the adapter class does have any codes at all.

534

WindowAdapter
import java.awt.*; import java.awt.event.*; public class Window1 extends Frame implements ActionListener

{ Frame f1; Button b1,b2; public Window1() {

535 f1=new Frame("Frame Demo"); f1.setLayout(new FlowLayout()); b1=new Button("Red"); b2=new Button("Blue"); b1.addActionListener(this); b2.addActionListener(this); f1.add(b1); f1.add(b2);

f1.setSize(200,200); f1.setVisible(true); f1.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent aw) { System.exit(0); } } ); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { f1.setBackground(Color.red); }else{ f1.setBackground(Color.blue);

536 } } public static void main(String args[]) { Window1 w1=new Window1(); } }

MouseAdapter, MouseMotionAdapter
import java.awt.*; import java.applet.*; import java.awt.event.*; public class CanvasDemo1 extends Applet { int x,y; GraphCanvas1 gc; public void init() { gc=new GraphCanvas1();

537 gc.setVisible(true); gc.setLocation(100,100); gc.setBackground(Color.blue); gc.setSize(300,200); add(gc); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { x=me.getX(); y=me.getY(); gc.setLocation(x,y); } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY(); gc.setLocation(x,y); } }); } } class GraphCanvas1 extends Canvas

538 { public void paint(Graphics g) { g.setColor(Color.white); g.setFont(new Font("Sans Serif",Font.BOLD,30)); g.drawString("Painting On Canvas",10,40); g.setColor(Color.pink); g.fillRect(40,50,40,50); } } /* <applet code="CanvasDemo1" width=500 height=500> </applet> */

539

BallRunning.java
import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="BallRunning.class" width=400 height=400> </applet>*/ public class BallRunning extends Applet implements Runnable,ActionListener { Thread t=null; int i,j; boolean stopFlag; Button b1,b2,b3,b4; public void init() { b1=new Button("START"); b2=new Button("RESUME"); b3=new Button("SUSPEND"); b4=new Button("STOP"); setBackground(Color.orange); add(b1); add(b2); add(b3); add(b4); b1.addActionListener(this); b2.addActionListener(this);

540 b3.addActionListener(this); b4.addActionListener(this); } public void actionPerformed(ActionEvent ae) { Object o=ae.getSource(); if(o==b1) { if(t==null) { t=new Thread(this); stopFlag=false; t.start(); } } if(o==b2)

t.resume();

if(o==b3)

t.suspend();

if(o==b4) { if(t!=null)

541 { stopFlag=true; t=null;

t.stop(); } } } public void run() {

for(i=0,j=400; ;i++,j--) { try{ repaint(); Thread.sleep(30); if(stopFlag) break; } catch(InterruptedException e){} } } public void paint(Graphics g) { g.setColor(Color.blue); g.fillOval(i+85,i+45,80,80);

542 g.setColor(Color.red); g.fillOval(j-15,j-45,80,80); } }

Here, I have used two threads. In the main thread the applet program executes and in the child thread t, the two balls simultaneously move in random inside the view port. In, the main thread, since the applet is displayed constantly , therefore a particular colors with a fixed intensity is fired to the moniter screen. This is done by the underlying OS, I think this is quite justified because the main do its unique task. Othe thread just moves the ball in different direction.

543

mballs.java
import java.awt.*; import java.awt.event.*; import java.applet.*; public class mballs extends Applet implements Runnable,ActionListener { Thread t=null; Button b1,b2,b3,b4; int l; TextField tf2,tf1; Label l1,l2; public void init() {

l1=new Label("Enter Speed in ms"); l2=new Label("No of Balls"); l1.setForeground(Color.orange); l2.setForeground(Color.orange); tf1=new TextField(5); tf2=new TextField(5); b1=new Button("start"); b2=new Button("stop"); b3=new Button("pause"); b4=new Button("Resume");

544 b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); setBackground(Color.black); add(l1); add(tf1); add(l2); add(tf2); add(b1); add(b2); add(b3); add(b4); } public void actionPerformed(ActionEvent ae) { if((ae.getSource()==b1)&&(t==null)) { t=new Thread(this); t.start(); } else if((ae.getSource()==b2)&&(t!=null)) { t.stop(); t=null; }

545 else if((ae.getSource()==b3)&&(t!=null)) { t.suspend(); } else if((ae.getSource()==b4)&&(t!=null)) { t.resume(); } } public void run() { for(;;) { try { repaint(); Thread.sleep(Integer.parseInt(tf1.getText())); } catch(Exception e){} } } public void paint(Graphics g) {

for(int k=0;k<(Integer.parseInt(tf2.getText()))%1000;k++) {

546 l=((int)(Math.random()*1000))%100; g.setColor(new Color(((int)(Math.random()*1000))%254,((int)(Math.random()*1000))% 254,((int)(Math.random()*1000))%254)); g.fillOval(((int)(Math.random()*1000))%500+100,((int)(Math.rand om()*1000))%500+100,l,l); } } } /*<applet code="mballs" width=800 height=650> </applet>*/

ncolor.java
import java.io.*;

547 import java.awt.*; import java.awt.event.*; import java.applet.*; import java.net.*; public class ncolor extends Applet implements Runnable,ActionListener { Thread t; Button b1,b2,b3,b4; int x,y; TextField tf,tf1; Label l; String s; public void init() { l=new Label("Enter Speed in ms"); tf1=new TextField(5); tf=new TextField(20); b1=new Button("start"); b2=new Button("stop"); b3=new Button("pause"); b4=new Button("Resume"); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); add(l);

548 add(tf1); add(tf); add(b1); add(b2); add(b3); add(b4); } public void actionPerformed(ActionEvent ae) { if((ae.getSource()==b1)&&(t==null)) { update(getGraphics()); t=new Thread(this); t.start(); } else if((ae.getSource()==b2)&&(t!=null)) { t.stop(); t=null; } else if((ae.getSource()==b3)&&(t!=null)) { t.suspend(); } else if((ae.getSource()==b4)&&(t!=null)) {

549 t.resume(); } } public void run() { x=y=0; draw(); } public void draw() { s=tf.getText(); Graphics g=getGraphics(); g.setFont(new Font("Monotype Corsiva",Font.BOLD,50)); for(int i=0;i<s.length();i++) { if(s.charAt(i)!=' ') { try { getAudioClip(new URL(getCodeBase(), "chime.au")).play(); } catch (Exception e) {} } g.setColor(new Color(((int)(Math.random()*1000))%254,((int)(Math.random()*1000))% 254,((int)(Math.random()*1000))%254));

550 g.drawString(String.valueOf(s.charAt(i)),100+x,100+y); x+=25;y+=25; try{Thread.sleep(Integer.parseInt(tf1.getText()));} catch(Exception e){} } } } /*<applet code="ncolor" width=400 height=400> </applet>*/

Image1.java

551 import java.awt.*; import java.applet.Applet; public class Image1 extends Applet implements Runnable { Image im1; Thread t1; Graphics g; int i=0; boolean flag=true; public void init() { im1=createImage(100,100); g=im1.getGraphics(); setBackground(Color.cyan); } public void start() { t1=new Thread(this); t1.start(); } public void stop() { flag=false; } public void run() {

552 while(flag) { repaint(); try{ Thread.sleep(100); }catch(InterruptedException ie) {

} } } public void paint(Graphics g) { i+=5; if(i>=100) i=5; g.setColor(Color.white); g.fillRect(10,10,100,100); g.setColor(Color.black); g.drawOval(30,60,i,i); g.drawImage(im1,10,10,this); g.setFont(new Font("Verdana",Font.BOLD,22)); g.drawString("Sai",i,i); } } /*<applet code="Image1" width=200 height=200>

553 </applet>*/

554

Chapter-27

The Java Foundation Classes

Java Foundation Classes are the extended version of Abstract Window Toolkit which is mainly used for GUI development. The drawbacks of AWT class are removed by the introduction of JFC. AWT has drawbacks!! Yes it does have. So, let me first address those drawbacks.

if you have ever google through AWT classes you might have come across the term peer component the alias name given to AWT. Why this name is given? Whenever you develop any GUI application in AWT, internally system dependent native codes are executed & the required system call is performed in to display various visual components on the screen. Actually when the AWT class file is executed by JVM, JVM requests the underlying OS to make appropriate system call to develop the GUI & return it to the JVM. This is what we call the peer component. As a java developer you can feel that while performing GUI development in AWT, you are not sticking to the platform independent features & that is why GUI looks different in different platform. A GUI contains various components like button, check-box, text-field etc. Whenever any action is performed on those components, listener attached to it is invoked to perform the desired task. Again here also the task is performed by the system call of the underlying OS. The visual display component & the action component in together is called LOOK & FEEL component. So the LOOK & FEEL component of AWT is platform dependent. With the introduction of JFC, the look & feel can either be system dependent or independent. Its up to the choice of the programmer.

JFC consists of five major packages:

y y

Swing (for the development of platform independent look & feel component) Pluggable Look and Feel (for the development of platform dependent look & feel component)

555 Drag and Drop (for the development of applications where you can drag the data & drop it at the required place & data is transferred to that pace) Accessibility (useful to develop applications for physically challenged people) 2D (for the development of 2-D applications) The geom. Class: this class is meant to develop various geometrical shape.

y y y

Briefly about swing

For gui development programmer often uses JFC methods and constructors. This package contains quite rich set of classes and methods for the development of various visual objects like button text-area, check-box etc. normally these visual objects and components light weight and fallow the MVC architecture. MVC stands for model view controller. Model represents the state of visual objects. State means, assume that there is a radio button in the GUI and whether it is selected or not represents its state or model. view represents the visual appearance of various visual objects when a state change is adapteds by them due to the action performed by the user. For example when u select a radio button u can see the visual change in that button . this is done by the invocation of isSelected() method. When ever user interacts with these visual objects, the state change is first detected by the controller. After that it is the controller which is responsible for the display of changed visual objects present in the GUI.

JComponent:According to the order pf hierarchy, JComponent class resides at the top. This class is extended by all the visual components of JFC, hence its methods & constructors are available to them. Just check hierarchical levels in the diagram.

556

Window panes

Jframe class, the core class of javax.swing package is used to develop GUI in which various visual objects like text field, radio button ,scroll bar , chech box , etc are embedded . this GUI is called window pane. There are four types of window panes are available. They are 1. Content pane

557 2. Layered pane 3. Root pane 4. Glass pane

1. Glass pane Glass pane is designed in such a way that it appears to the user as if the window is just pasted on the monitor. getGlassPane() method is used to communicate with the glass pane window. If you are attaching some visual components to the foreground of any GUI they are attached to the glass pane window.

2. Root pane This window resides just below the glass pane window. When programmer attach any visual objects to the GUI such that it is appeared to be attached at the back ground then actually root pane window contains that visual object. For example if you are doing a moving animated picture of krish flying in the sky then krish (a visual object) should be attached to glass pane where as the clouds and the blue sky has to be attached to the root pane. This can be performed by the invocation of method getRootPane() .

3 Layered pane

This pane resides beneath the root pane . normally it is used to embed a collection of objects. We can communicate with the getLayeredPane () method.

4 Content pane

This pane lays below all the above defined planes . you can communicate with this pane with the use of getContentPane() method .

558 whenever you are attaching any visual objects to GUI u have to attach them to one of these panes.

Your first window

Enough theory lets have a programming example

import javax.swing.*; public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME"); w1.setSize(300,300); w1.setVisible(true); } }

Output :

559

W1 is a JFrame object created by calling the constructor of JFrame which takes the name of the window to be displayed on the screen as its argument. As the name suggests setSize() sets the size and setVisible() makes the window visible. the default size that is passed to the setSize() method is 0 pixel x 0 pixel .

Now there is a interesting thing associated with this program. Although you have clicked the close button , the program is not going to removed from the memory this is because of its TSR characteristics, the program is not going to be removed from the memory this is because of its TSR characteristics. You can check it from the process table of the task manager (windows os) or by performing ps e in linux system that the process javawx exists there. Some thing is lacking for the complete termination of the program , the solution is to invoke the setDefaultCloseOperation() method. Just see the example below import javax.swing.*;

public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME"); w1.setSize(300,300); w1.setVisible(true); w1. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } setDefaultCloseOperation() this method upon calling removes the program from the memory permanently. This method is called when you click the close button.

560

BoxLayout class

BoxLayoutManager provides implementation techniques to embed various visual objects either vertically or horizontally. These visual objects or you can say the components are not going to wrap, when the GUI is resized. Theis Layout manger solely belongs to the JFC. It shows similarity with the FlowLayout. This Layout facilitates to add visual objects vertically or horizontally maintaining a stack principle. You can specify the orientation of the BoxLayout during the construction. The predefined fields X_AXIS & Y_AXIS is used to arrange the visual objects.

BoxLayout follows the principle to maintain the optimum size of various visual objects properties. Suppose the components are gathered around the Y_AXIS then the automatic resizing is done by the BoxLayout class.

The following example emphasizes the utility of BoxLayout. import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; class BoxDemo extends JFrame { public BoxDemo() { setTitle("Box Layout"); JPanel contentpane =( JPanel)getContentPane(); contentpane.setLayout(new BorderLayout()) ;

561 Box mainbox=new Box(BoxLayout.Y_AXIS); JButton ok=new JButton("OK"); contentpane.add("North",ok); JButton cancel=new JButton("CANCEL"); contentpane.add("South",cancel); myadapter myapp=new myadapter() ; addWindowListener(myapp); } private class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String args[]) { BoxDemo b=new BoxDemo() ; b.setSize(400,400); b.setVisible(true); } } Output

562

Setting the back ground color

For this purpose you have to call the setBackground() method through the object of JFrame. The parameter you have to send is the various static fields of Color class. import javax.swing.*; import java.awt.*;

563

import javax.swing.*; import java.awt.*;

public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME"); Container c1=w1.getContentPane(); c1.setBackground(Color.green); w1.setSize(300,300); w1.setVisible(true); w1. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} } Output:

564

Steps to add color

y y y y

Import the java.awt.* package. This package makes the setBackground() method available to you. The background color can only be added to the container. Therefore you have to make a container object for the window w1. This is done by calling the getContentPane () methodthrough w1. By the container object, invoke the setBackground() method. This method takes argument as various static predefined fields of Color class.

Adding text to the window

JFC provides two ways to display text in a window frame

1. by overriding the paintComponent() method. In this technique you have to extend the JPanel class scince paintComponent() is available there.

Lets have a coding example First technique :

import javax.swing.*; import java.awt.*;

class

X extends JPanel{ public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Hello world",50,100);

565 }

} public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME");

Container c1=w1.getContentPane(); X a1=new X(); c1.add(a1); c1.setBackground(Color.green); w1.setSize(300,300); w1.setVisible(true); w1. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} }

566

Steps

y y y y y y y

extend the JPanel class. override the paintComponent(). Invoke the paintComponent() of JPanel class by the statement super.paintComponent(). Invoke the method drawstring() inside the overridden body of paintComponent(). This methods takes the string to be displayed along with the co ordinate position. Inside main() create the object of the class , that has extended the JPanel class. Create the Container object by the getContentPane(). Add the object of class X to the container by the statement c1.add(a1).

Second technique :

import javax.swing.*; import java.awt.*;

public class window1 extends JFrame { JLabel l1;

567 window1() { l1 = new JLabel("hello world"); } public static void main(String a[]) { window1 w1 = new window1();

Container c1=w1.getContentPane(); c1.add(w1.l1); c1.setBackground(Color.green); w1.setSize(300,300); w1.setVisible(true); w1. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} }

steps

y Extend the class JFrame . y Create an object of JLabel. y Add it to the container object. Constructor of JLabel is going to take the string to be displayed as its argument.

Let us have another example for TextArea in case of Swing.

568 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class TextAreaDemo extends JFrame { JTextArea jtx; public TextAreaDemo() { JPanel contentpane=(JPanel)getContentPane( ); contentpane.setLayout(new BorderLayout()) ; setTitle("Text area Example"); jtx=new JTextArea( ); jtx.setFont(new Font("Arial",Font.PLAIN,14)); contentpane.add("Center",jtx); myadapter myapp=new myadapter(); addWindowListener(myapp); } class myadapter extends WindowAdapter { public void windowCloseting(WindowEvent e) { System.exit(0); } } public static void main(String args[])

569 { TextAreaDemo tx=new TextAreaDemo( ) ; tx.setSize(150,150); tx.setVisible(true); } } Output

JComponent class

This class belongs to the javax.swing package . Component class of awt package is its parent class . hence the methods of the Component class is inherited to the JComponent class. along with the inherited method this class has also defined its own methods whenever you are creating any visual components or visual objects , donot embed that object to the frame. Rather create an window pane and embed the visual component to it.

570

Methods add component and remove component

add(Component ) : this method is called by the object of the container class

remove(Component) : like add method this method is invoked by the object of the container class to remove the specified component

removeAll() : this method is invoked by the container object to remove all the components attached.

setLayout() in a GUI development you have to place the visual components at certain places according to a specific manner. The layout manager sets the visual component at the desired places in the GUI. This is done by the invocation of setLayout() method through the object of Container class.

setBackground(): this method is used to add the back ground color to a GUI. This method takes static color element from Color class. for example setBackground(Color.red);

setForeground() this method is similar to the setBackground() method. setFont(Font font_obj): this method used to set different on a GUI application. This method takes the object of Font class as its argument.

Creation of push button using JButton class

571

import javax.swing.*; import java.awt.*;

public class window1 extends JFrame { JButton b1; window1() { b1 = new JButton("hello world"); } public static void main(String a[]) { window1 w1 = new window1();

Container c1=w1.getContentPane(); c1.add(w1.b1); c1.setBackground(Color.green); w1.setSize(300,300); w1.setVisible(true); w1. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} }

Output

572

Creation of push button is similar to that of adding text to a GUI discussed in second technique . instead of creating a object of JLabel you have to create the object of JButton and the rest are similar. Since I have not registered any listener corresponding to the push button b1 no actions are going to be fired upon pressing the push button. Let us have another programming example.

import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class PanelDemo extends JFrame { public PanelDemo( ) { setTitle("Box 1"); JPanel contentpane =(JPanel)getContentPane( );

573 contentpane.setLayout(new GridLayout()); JButton ok=new JButton("ok"); contentpane.add(ok); JButton cancel=new JButton("CANCEL"); contentpane.add(cancel); myadapter myapp=new myadapter(); addWindowListener(myapp); } private class myadapter extends WindowAdapter { public void windowCloseing(WindowEvent e)

{ System.exit(0); } } public static void main(String args[]) { PanelDemo pd=new PanelDemo(); pd.setSize(400,400); pd.setVisible(true); } } Output:-

574

Embedding the Components


Components means the visual objects. Visual objects includes check box, text fields, radio button, buttons etc.

Check box:
First create the object of JCheckBox by the statement JCheckBox=new JCheckBox(); the check box created upon execution of this statement is said as blank CheckBox. it neither has a level name nor any image is attached to it. the constructor of JCheckBox is over loaded. Other forms of the existing constructors are: JCheckBox a=new JCheckBox(String level_name); the argument taken by the constructor is a string holding the level name for the check box. JCheckBox a=new JCheckBox(String l_name, bollean status); you are already familiar with the tskof first argument. The next argument is of boolean data type. If you send boolean true value, then the checkbox is appread as auto selected.

575 JCheckBox a=new JCheckBox(String l_name, Image im); this constructor attach the level name along with a image to the check box. After creation of check box, do the modeling of check box by calling the getModel() method. This is done by the execution of Model mm=a.getModel(); To determine whether the check box is selected or not, you have to use the isSelcted() method. This is done by the execution of the statement boolean x=m.isSelected(); Lets have a program:

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class window1 extends JFrame implements ActionListener { JCheckBox cbox1,cbox2,cbox3; JTextArea tarea; String s1; window1() { //Creation of Content pane Container c1=getContentPane(); //Set flow lay out c1.setLayout(new FlowLayout()); //creation of text area tarea=new JTextArea(10,20); // creation of two check box cbox1=new JCheckBox("java"); cbox2=new JCheckBox("C++"); cbox3=new JCheckBox(".NET");

576 // add these visual objects c1.add(cbox1); c1.add(cbox2); c1.add(cbox3); c1.add(tarea); //embed the listeners cbox1.addActionListener(this); cbox2.addActionListener(this); cbox3.addActionListener(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

public void actionPerformed(ActionEvent ae){ if(cbox1.getModel().isSelected())s1+="java"; if(cbox2.getModel().isSelected())s1+="C++"; if(cbox3.getModel().isSelected())s1+=".NET"; tarea.setText(s1); s1="";

} public static void main(String a[]) { window1 w1=new window1(); w1.setSize(500,500); w1.setVisible(true); }

577 } Output:

Let us have another example for the checkbox.

import java.awt.*; import java.awt.event.*; import javax.swing.*;

578 public class CheckboxDemo extends JFrame implements ItemListener { JCheckbox cb; public CheckboxDemo() { setTitle("check box example"); JPanel contentpane=(JPanel)getContentPane(); contentpane.setLayout(new GridLayout(2,2); cb=new JCheckbox("Toggle"); cb.addItemListener(this); contentpane.add(cb); myadapter myapp=new myadapter(); addWindowListener(myapp); } class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System . exit (0); } }

public void itemStateChanged(ItemEvent e) { if(e.getStateChange( )==ItemEvent.SELECTED) setTitle(checkbox selected );

579 else setTitle(Checkbox unselected) ; } public static void main(String args[]) { CheckboxDemo c=new CheckboxDemo() ; c.setVisible(true) ; c.setSize(250,250); } } Output

Radio button:

580 Radio buttons are created by instanciating the object of JRadioButton class. the constructor of JRadioButton class is overloaded. Its various constructors are 1. JRadioButton() : this is the default constructor for JRadioButton. 2. JRadioButton(String s1) this constructorn takes String s1 as its argument. s1 serves as the level name for the argument. 3. JRadioButton(String s1, ImageIcon i) this constructor takes another extra parameter as image icon to the radio button. 4. JRadioButton(String s1, boolean b) the boolean value b suggests that by default the button is selected or not See the example below import javax.swing.*; import java.awt.*; import java.awt.event.*; public class window1 extends JFrame implements ActionListener { JRadioButton cbox1,cbox2; JTextArea tarea; String s1; window1() { //Creation of Content pane Container c1=getContentPane(); //Set flow lay out c1.setLayout(new FlowLayout()); //creation of text area tarea=new JTextArea(10,20); // creation of two radio button cbox1=new JRadioButton("java"); cbox2=new JRadioButton("C++");

// add these visual objects

581 ButtonGroup b=new ButtonGroup(); b.add(cbox1); b.add(cbox2); //button group is created & two button behaves as a single group from which only one can be selected c1.add(tarea); c1.add(cbox1); c1.add(cbox2); //embed the listeners cbox1.addActionListener(this); cbox2.addActionListener(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

public void actionPerformed(ActionEvent ae){ if(cbox1.getModel().isSelected())s1+="java"; if(cbox2.getModel().isSelected())s1+="C++";

tarea.setText(s1); s1="";

} public static void main(String a[]) { window1 w1=new window1(); w1.setSize(500,500);

582 w1.setVisible(true); } } Output:

If you select the c++ that is going to be displayed on the text area.

Let us have another example:

583 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RadioButtonDemo extends JFrame implements ActionListener { JRadioButton rb1,rb2; ButtonGroup grp=new ButtonGroup(); public RadioButtonDemo() { setTitle("Radio Buttons Example"); JPanel contentpane=(JPanel)getContentPane(); contentpane.setLayout(new FlowLayout()); rb1=new JRadioButton("Enabled"); rb1.addActionListener(this); rb1.setActionCommand("One Activated"); rb1.setSelected(true); contentpane.add(rb1); rb2=new JRadioButton("Disabled"); rb2.addActionListener(this); rb2.setActionCommand("Two Activated"); contentpane.add(rb2); grp.add(rb1); grp.add(rb2); myadapter myapp=new myadapter(); addWindowListener(myapp); }

584 class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==rb1) { setTitle("First radio button enabled."); rb1.setEnabled(false); rb2.setEnabled(true); } else if(e.getSource()==rb2) { setTitle("Second radio button enabked."); rb1.setEnabled(false); rb2.setEnabled(true); } } public static void main(String args[]) { RadioButtonDemo rb=new RadioButtonDemo(); rb.setSize(300,300);

585 rb.setVisible(true); } }

Output:

Navigation through LOOK and FEEL

Swing facilitates plaf, it means plugable look and feel. The visual appearance of a GUI along with it;s visual objects is called LOOK components . when a event is fired or generated on any of those visual objects , the mechanism through which the event is handeled is termed as FEEL component . swing facilitates 3 types of LOOK and FEEL . 1 :Mmetal LOOK and FEEL 2: Motif LOOK and FEEL 3: Window LOOK and FEEL

586 Since everything in java are class and objects therefore the above mentioned LOOK and FEELs are clases of javax.swing.plaf package . the default look and feel choosed whenever we design a swing application is metal. setLookAndFeel() is used to change the default LOOK and FEEL component of swing application. Inorder to have the Motif Look and Feel you have to send the string com.sun.java.swing.plaf.motif.MotifLookAndFeel As a argument to setLookAndFeel(). For windows Look and Feel the string is com.sun.java.swing.plaf.windows.windowsLookAndFeel Then you have to invoke the updateComponentTreeUI() to incorporate the change.

Now lets have a example

import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.plaf.*; public class window1 extends JFrame implements ItemListener {

JButton button; JCheckBox cBox; JTextField tF; JRadioButton rb1,rb2,rb3; ButtonGroup bGroup; Container c; window1(){ //create the content pane c=this.getContentPane();

587 //set the appropiate lay out manager c.setLayout(null);

//embed visual objects button=new JButton("BUTTON"); cBox=new JCheckBox("check box"); tF=new JTextField(); rb1=new JRadioButton(); rb2=new JRadioButton(); rb3= new JRadioButton();

//Design a button group & add all the radio button to that group bGroup=new ButtonGroup(); bGroup.add(rb1); bGroup.add(rb2); bGroup.add(rb3); // locate each visual component on the GUI button.setBounds(100,50, 80, 50); cBox.setBounds(100, 1000, 1000, 50); tF.setBounds(100, 150, 100,40); rb1.setBounds(50, 250, 100, 30); rb2.setBounds(150, 250, 100, 30); rb3.setBounds(250, 250, 100, 30);

// embed these visual objects to the content pane c.add(button); c.add(tF);

588 c.add(cBox); c.add(rb1); c.add(rb2); c.add(rb3); // embed the listener rb1.addItemListener(this); rb1.addItemListener(this); rb1.addItemListener(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void itemStateChanged(ItemEvent ie) { try{ if(rb1.getModel().isSelected())

UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel "); if(rb2.getModel().isSelected())

UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLook AndFeel"); if(rb3.getModel().isSelected())

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.Windows LookAndFeel"); SwingUtilities.updateComponentTreeUI(c); }catch(Exception e){} } public static void amin(String[] args)

589 { window1 w1=new window1(); w1.setSize(500,500); w1.setTitle("My Window"); w1.setVisible(true); }

Execute the codes to go through various available look & feel component.

The JTable class

To create tables for a GUI based application JTable class is used. The constructor of the JTabe class is called to create the table object. Each table consists of rows and column. Methods associated with JTable class

1.

2.

getRowCount() : this method is invoked by the table object. It returns the number of rows present in that table. its return type is integer. getColumnCount() : similar to the getRowCount() it returns the number of columns present in the table.

590 3. getColumnName(int i) : this method takes the index number of the column number as its argument and returns the name of the column in the form of string. getTableHeight() : this method returns the length of the table in terms of pixel. its returns type is integer. getSelectedColumn() : this method is invoked by the JTable object.this method returns the index number of the column which is selected on the GUI. If no column is selected then this method is going to return -1. getSelectedColumns() : this method returns an array of integers . this array contains the index number of all the selected columns. getSelectedRows() : this method returns an array of integers . this array contains the index number of all the selected rows. setValueAt(Object data , int row_index , int column_index) : this is used to put the data in the specified position of the table.

4. 5.

6.

7. 8.

JTabbedPane class

When you instanciate the JTabbedPane class, the visual object of this class is encapsulated with tabs. GUI developed by this class is called JTabbed frame. This class contains some predefined fields such as JTabbedPane.TOP,JTabbedPane.BOTTOM,JTabbedPane.LEFT , JTaabbedPane.RIGHT. These fields are used to indicated by the fields. embed the tabs in the position

Methods

1 add() : this method is used to add tabs to a specific position in the frame. This method is overloaded in this class. other versions of this method takes strings and image as argument for the name of the tabs and icons.

591 2 removeTabAt( int i) : this method is invoked through the object of the JTabbedPane class. the argument I indicates the index of the tab to be removed from the frame . 3 removeAll() : this method removes all the tab from the component pane

4 remove ( Component c) : this method is used to remove a specific component from the tabbed pane.

5 getTabCount() : this method is invoked by the object of the JTabbedPane class to count the number of tabs present in the tabbed pane .

6 getSelectedIndex( ) : this method returns the index number of the selected tabs from the JTabbedPane.

7 getComponentAt( int i) : This method returns the visual object or component associated with the index i.

8 setComponentAt(int index,Component c) This method is used to embed a visual object or a component at the position specified by the index i.

Programming example: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TabbedDemo extends JFrame {

592 JTabbedPane fpane=new JTabbedPane(); JPanel First=new JPanel(); JPanel Second=new JPanel(); JPanel Third=new JPanel() ; public TabbedDemo() { getContentPane().setLayout(new BorderLayout()); fpane.addTab("First",First) ; fpane.addTab("Second",Second) ; fpane.addTab("Third",Third) ; fpane.setSelectedIndex(0) ; getContentPane().add(fpane,BorderLayout.CENTER); myadapter myapp=new myadapter() ; addWindowListener(myapp) ; } private class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } void makePane(String thestring) { TabbedDemo newtab=new TabbedDemo(); newtab.setVisible (true) ;

593 newtab.setSize (400,400) ; } public static void main(String args[]) { TabbedDemo td=new TabbedDemo(); td.setSize(250,200); td.setVisible(true); } } Output:-

JSplitPane class

594

This class is used to divide the GUI or the window in exactly two parts but not more than that. Splitting is done in two ways

horizontal splitting process : in this process it splits the window into two parts horizontally.

Vertical splitting process : in this process it splits the window into two parts vertically.

Methods

setDividerLocation( int pix) : this method sets the divider location between two components.

getDividerLocation( ) : this method divider location.

is

used to get

the

getTopComponent() : this method is used to deal with the top or left component. getButtomComponent() : this method is used to the buttom or right component . deal with

remove() : this method is used to remove the component from the split pane. remove(int i) removes the component specified by the index i.

595 7 setTopComponent(Component object) : deploy the component at top of the frame. setBottomComponent(): deploy the component at bottom of the frame. setLeftComponent():deploy frame. setRightCompnent():deploy frame. the component at left of the

10

the

component

at

right

of

the

import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.plaf.*; public class window1 extends JFrame implements ActionListener {

String st1="This is my area to write java code"; JButton button; JTextArea tA; JSplitPane jsp;

window1(){ Container c; //create the content pane c=this.getContentPane(); //set the appropiate lay out manager c.setLayout(new BorderLayout());

596

//embed visual objects button=new JButton("BUTTON");

tA=new JTextArea("this is the text area"); jsp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, button, tA); jsp.setDividerLocation(300); c.add("CENTER",jsp); button.addActionListener(this);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ie) { tA.setText(st1); } public static void amin(String[] args) { window1 w1=new window1(); w1.setSize(500,500); w1.setTitle("My Window"); w1.setVisible(true);

} }

597

JTreeClass

JTreeClass implements the graphical tree structure to display various nodes in a hierarchical manner. Each node represents the data or entity or some text. You can design the graphical tree structure of directory structure present in a partition by the use of methods & constructors in this class.

Normally when you want to display the entities in tree structure, then two stage approaches is followed. In first stage the root is developed & in second stage Childs are spawned from the root node. To create a root node the JTree() constructor is invoked. In the next stage to spawn child the constructor of DefaultMutableTreeNode() is invoked. The argument passed to JTree class constructor can either be the entity of hash table containing keys & values or element of vector.

Methods of JTree class. y y add(Object node): this method is invoked by the root node in order to add a node to the root node. getNewLeadSelectionPath() Each nodes present in the tree contains data or element. When you select an item, this method is used to return the path that describes the position of the element in the tree. This method returns a TreePath object. getLastPathcomponent(). This method returns the item or element that is selected by the user. getPathCount() To know the number of paths available to the particular node.

y y

JComboBox Class

As the name suggests this class is used to create the combo box component for the GUI interface. You can either create an empty combo box by JComboBox comb=new JComboBox();

598 Or create an combo box having list of items by JCombobox comb=new JComboBox(Object []arr); here the array contains list of items to be displayed in the combo box.

Methods of Combo Box class y y addItem(): This method is invoked by the combo box object to add item to the combo box. getSelectedItem(): this method is used extract an item from the combo box, but first of all you have to select the item to be extracted. getselectedIndex() this method is used to extract the element specified by the index from the combo box. getItem(int i) This method is used to extract the element specified by the index number I from the combo box. getItemCount(): This method is used to count the nuber of elements present in the combo box. removeItem(): This method is used to remove the selected item from the combo box. removeAll(): This method is used to remove all the elements present in the combo box.

y y y y y

JList class
This class is used to create the list of items to be displayed on the GUI. From this list you are able to select more than item. The constructor for creation of JList object is JList jl=new JList(); JList() constructor when create an empty list. invoked through new operator is used to

JList jl=new JList(Object []arr); this constructor is used to create a list containg the array of elements suppilied by the array arr. You can also send the object of vector to supplay the list items.

getSelectedItem():This method returns the selected item from the list.

599 getselectedIndex(): this method is used to retun the index of the selected item. getSelectedValues(): this method returns the array of selected items. getSelectedIndices(): This method is used to return array of indices.

y y y

import java.awt.*; import javax.swing.*; import javax.swing.event.*; class list extends JFrame implements ListSelectionListener { JList j1; JLabel j2; Object ary[]; String mesg="";

list() { Container c1 = getContentPane(); c1.setLayout(null);

String s1[]={"orissa","mharastra","kerela","karnataka","goa"};

j1 = new JList(s1); j1.setBounds(100,50,100,100); c1.add(j1);

600 j2 = new JLabel(); j2.setBounds(50,200,400,40); c1.add(j2); j1.addListSelectionListener( this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void valueChanged(ListSelectionEvent ae1) { ary = j1.getSelectedValues(); for(int i=0;i<ary.length;i++) { mesg += " , " ; mesg += (String)ary[i];

} j2.setText("selected : "+mesg); mesg=""; } public static void main(String a[]) { list tb = new list(); tb.setTitle("MY LIST"); tb.setSize(600,400); tb.setVisible(true);

601 } }

Output :

JMenu class

JMenu class is used to create the visual object of menu . after creation this visual object is added to menu bar.

Steps to create a menu object and add it to the GUI.

602

Create a menu bar by JMenuBar j1 = new JMenuBar();

Attach the menu bar object to the container of GUI. C1.add(j1); Here c1 is the Container class object

Create a JMenu object through new operator.

by

invoking

the

JMenu

constructor

JMenu jm = new JMenu(hello);

Add the JMenu object to the menu bar. J1.add(jm);

JToggle Class

In case of push button when you different state and looks as if it on the pushed-button it comes mechanism of toggle button is some The button goes to the inward push

click it the button goes to a is pushed inwards. When re cliked back to its normal state.the what similar to the push button. state as long as you have pressed

603 the left mouse key and when you release the left mouse key the button comes to it normal state. To create a toggle button you have to invoke the constructor and supply the label name. another overloaded format of the constructor of this class takes the image icon along with the label name.

import java.awt.*; import java.awt.event.*; import javax.swing.*; class TogleButon extends JFrame implements ActionListener { JToggleButton j1; ImageIcon image1;

TogleButon() { Container c1 = getContentPane(); c1.setLayout(new FlowLayout());

image1 = new ImageIcon("start.gif");

j1 = new JToggleButton("START / STOP", image1);

c1.add(j1);

j1.addActionListener(this); }

604 public void actionPerformed(ActionEvent { ImageIcon image2 = new ImageIcon("stop.gif"); ae1)

if( j1.isSelected()) j1.setIcon(image2); else j1.setIcon(image1);

} public static void main(String a[]) { TogleButon tb = new TogleButon(); tb.setSize(800 , 800); tb.setVisible(true); tb.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } } When you 1st clicked see the out put

605

When you clicked for the 2nd time see the output.

606

JProgressBar class

Progress bars are normaly used to have a visual display of process life that means it indicates how much percentage of a executing process is completed , how many percentage remaining , how long it will take to complete the entire execution of the process. You have seen the scroll bar when you copy a file , while installing the software , etc. An interesting aspect is that through JFC classes java provides vertical progress bars . ProgressBar object is created by calling the constructor of the JProgressBar class. the various overloaded constructors are 1. 2. JProgressBar(); JProgressBar( int X ) X indicates the orientation of the progress bar

Methods

1 . getMinimum() : this method is used to get the least value of the progress bar.

2 . getMaximum() : this method is used to get the optimum value of the progress bar.

3 . getOrientation() : this method is used to get the orientation of the progress bar.

4 . getValue() : this method is used to have the current value of the progress bar.

5 . setValue() : progress bar.

this method is used to set the value of the

607

6 . setOrientation() : this method is used to set the orientation of the progress bar.

7. setStringPainted() : this method percentage of the progress of the task bar.

is

used

to

display

the

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Progress extends Object { public static void main (String args[ ]) { JFrame frame =new JFrame("ProgressMonitor Example"); JButton button=new JButton("Start"); frame.getContentPane().add(button,BorderLayout.CENTER); int min = 0; int max = 100; String[] message=new String[2]; message[0]="performing Operation."; message[1]="This may take some time ..."; final ProgressMonitor monitor=new ProgressMonitor(frame, message,"Iteration",min,max ); final Runnable runnable=new Runnable( ) { public void run ( )

608 { int sleepTime = 500; for(int i=1;i<100;i++) { try{ monitor.setNote( "Iteration" + i); monitor.setProgress( i ); if(monitor.isCanceled( )) { monitor.setProgress( 100 ); break; } Thread.sleep( sleepTime ); }catch(InterruptedException dontcare ) { } } } //monitor.close( ); }; button.addActionListener( new ActionListener ( ) { public void actionPerformed(ActionEvent event) { Thread thread = new Thread(runnable); thread.start( );

609 } } ); //show the frame. frame.pack( ); frame.setVisible( true ); } } Output

JColorChooser class

This class is used to select different colors available in the Color menu bar. The constructors of this class are 1. JColorChooser() 2. JColorChooser(java.awt.Color) 3. JColorChooser(javax.swing.colorchooser.ColorSelectionModel)

610

This class provides three String type constants for selecting the model for the color. These are 1. Public static final java.lang.String SELECTION_MODEL_PROPERTY 2. Public static final java.lang.String PREVIEW_PAEL_PROPERTY 3. Public static final java.lang.String CHOOSER_PANELS_PROPERTY Example-13 import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.lang.*; public class ColorChooserDemo extends JFrame { public ColorChooserDemo( ) { setTitle("JColorChooser Example"); JColorChooser jcc = new JColorChooser( ); JPanel content=(JPanel)getContentPane( ) ; content.add(jcc,"Center"); } public static void main(String args[]) { JFrame jf = new JFrame("JColorChooser Example"): ColorChooserDemo c = new ColorChooserDemo(); c.setVisible(true); } }

611

Output

Dealing with the keyboard events

612

Normally an user interacts with the system by entering data through the keyboard. When you press a key, an interrupt is generated and propagates to the operating system.Upon receiving the interrupt signal, the os invokes the appropriate interrupt service routine through device driver. The JVM hides this complex techniques from the programmer by providing listener interfaces and event handling methods. In java the generated interrupt is termed as event. Each event is closely entangled with a listener object. All these listener interfaces and event handling classes belongs to the java.awt.event package. when you press a key, an event is generated according to the status of the key and the value of the key. Status of the key indicates whether a key is pressed or released and the represents which key is pressed.

A state of a key can be determined by various methods available in the java.awt.event package. for detailed description the readers can go through the chapter-26.

The value attribute represents the key that has been pressed.

VK_A to VK_Z holds the logical value of the key between A to Z.

VK_0 to VK_9 holds the logical value of the key between 0 to 9.

VK_F1 to VK_F12 holds the logical value of the key between F1 to F12.

VK_HOME holds the logical value of the key HOME

VK_END holds the logical value of the key END

613 VK_PAGE_UP holds the logical value of the key PAGE_UP

VK_PAGE_DOWN holds the logical value of the key PAGE_DOWN.

VK_INSERT holds the logical value of the key INSERT

VK_CAPS_LOCK holds the logical value of the key CAPS_LOCK

VK_ALT holds the logical value of the key ALT

VK_CONTROL holds the logical value of the key CONTROL

VK_SHIFT holds the logical value of the key SHIFT

VK_TAB holds the logical value of the key TAB

VK_LEFT holds the logical value of the key LEFT ARROW

VK_RIGHT holds the logical value of the key RIGHT ARROW

VK_UP holds the logical value of the key UP ARROW

VK_DOWN holds the logical value of the key DOWN ARROW

VK_ESCAPE holds the logical value of the key ESCAPE

614 We can also get the logical value behind the keycodes such as VK_F1 for F1, VK_SHIFT for SHIFT and etc. in the form of a String by the following predefined method:

Static String getKeyText(int keycode)

Example:-

import java.awt.*; import java.awt.event.*; import javax.swing.*;

class window1 extends JFrame implements KeyListener { Container cnt; JTextArea txt; String st1=;

window1() { cnt=getContentPane();

txt=new JTextArea( please press a key:); txt.setFont(new Font(Arial,Font.BOLD,20));

cnt.add(txt);

615

txt.addKeyListener(this); }

public void keyPressed(KeyEvent kee) { int keycode1=getKeyCode();

if(keycode1==KeyEvent.VK_F1) st1+=The F1 key; if(keycode1==KeyEvent.VK_F2) st1+=The F2 key; if(keycode1==KeyEvent.VK_F3) st1+=The F3 key; if(keycode1==KeyEvent.VK_PAGE_UP) st1+=page-up; if(keycode1==KeyEvent.VK_PAGE_DOWN) st1+=page-down; if(keycode1==KeyEvent.VK_ALT) st1+=the Alter key; if(keycode1==KeyEvent.VK_HOME) st1+=the HOME key; if(keycode1==KeyEvent.VK_END) st1+=the END key; }

public void keyReleased(KeyEvent kee) {} public void keyTyped(KeyEvent kee) {}

public static void main(String arg[]) { KeyBoardEvents kkk=new KeyBoardEvents(); kkk.setVisible(true);

616 kkk.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } Just run code & see the ouput.

MessagePane

MessagePane allows the programmer to develop the GUI, such that when a particular event is fired with respect to a visual object, a MessageBox is poped-up instantly.

Various methods of the MessageBox

Method public static void showMessageDialog(Component c1, Object msg1)

Description C1 determines the visual object or the frame to be poped-up and msg1 represents the message to be displayed.

617 public static void showMessageDialog(Component c1, Object msg1, String title1, int messageType1) C1 determines the visual object or the frame to be poped-up and msg1 represents the message to be displayed. title1 represents the title of the box and message_type1 is used to display the exact type of the message like ERROR_MESAGE, INFFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE

public static void showMessageDialog(Component c1, Object msg1, String title1, int message_type1, Icon icn)

C1 determines the visual object or the frame to be poped-up and msg1 represents the message to be displayed. title1 represents the title of the box and message_type1 is used to display the exact type of the message like ERROR_MESAGE, INFFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE. Here, icn is used to display the picture as an icon for tht particular message box.

618

import java.awt.event.*; import java.awt.*; import java.lang.*; public class MessagePaneDemo extends JPanel implements ActionListener { public MessagePaneDemo( ) { JButton b1 = new JButton("Click here"); b1.addActionListener(this); add(b1); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(this,"Hai,See The Message","Informational Message pane",JOptionPane.INFORMATION_MESSAGE); } public Dimension getPerferredSize( ) { return new Dimension(100,60); } public static void main(String s[])

619 { JFrame frame = new JFrame("Information"); MessagePaneDemo panel=new MessagePaneDemo( ); frame.setForeground(Color.black); frame.setBackground(Color.lightGray); frame.addWindowListener(new WindowCloser( ) ); frame.getContentPane().add(panel); frame.setSize(panel.getPreferredSize()); frame.setVisible(true); } } class WindowCloser extends WindowAdapter { public void WindowClosing(WindowEvent e) { Window win=e.getWindow( ); win.setVisible(false); System.exit (0); } }

Output

620

JOptionPane

A JOptionPane class is used to design option pane dialog box which is encapsulated with four major visual objects. j j j j The The The The Icon object Message object Input object Option object

Each of these objects is stored in their respected areas as shon in the following diagram.

Message Area Icon

621

Input Area

Options Area

Option Attributes
JOptionPane class contains various predefined fields which are used to configure the pane prior it is displayed. You have to to remember these fields to work in different option panes.

622

623

The option type for an OptionPane is used to determine the buttons to be displayed in the option buttons area. There are four defaults setting for this value. We can also create our own button combinations if we use a generic option pane. Each default value is defines as a class variable for JOptionPane.

Example-11 import javax.swing.*;

624 import java.awt.event.*; import java.awt.*; import java.1ang.*; public class Confirm extends JPanel implements ActionListener { public Confirm( ) { JButton b1 =new JButton("click here"); b1.addActionListener (this); add (b1); } public void actionPerformed (ActionEvent e) { int result; result =JOptionPane.showConfirmDialog(this,Continue); switch(result) { case JOptionPane.YES_OPTION: System.out.println(Yes Button was pressed); break; case JOptionPane.NO_OPTION: System.out.println(No Button was pressed); break; case JOptionPane.CANCEL_OPTION: System.out.println(Cancel Button was pressed); break;

625 case JOptionPane.CLOSED_OPTION: System.out.println(Dialog closed); break; } } public Dimension getPreferredSize( ) { return new Dimension (100, 60); } public static void main(String s [ ]) { JFrame frame =new JFrame (Confirm Dialog); Confirm panel =new Confirm ( ); frame.setForeground(Color.black); frame.setBackground(Color.lightGrey); frame.addWindowListener (new WindowCloser ( )); frame.getContentPane ( ).add(panel,Center); frame.setSize(panel.getPreferredSize( ) ); frame.setVisible (true); } } class WindowCloser extends WindowAdapter { public void windowCloseing(WindowEvent { e)

626

Window win =e.getWindow( ); win.setVisible(false); System.exit( 0); } } Output:

Let us have another programming example which shows another task of the JOptionPane.

import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.lang.*; public class InputDialogDemo extends JPanel implements ActionListener {

627 public InputDialogDemo( ) { JButton b1=new JButton("Click here"); b1.addActionListener(this); add(b1); } public void actionPerformed(ActionEvent e) { String output; output=JOptionPane.showInputDialog(this,"Enter your favorite place"); if((output==null)||(output.lenght()==0)) { System.out.println("zero data: "); System.out.println("Enter data in the text field "); } else { System.out.println("Entered data is :" + output); } } public Dimension getPreferredSize( ) { return new Dimension(100, 60); } public static void main(String s[ ] )

628 { JFrame frame = new JFrame("Confirm Dialog"); InputDialogDemo panel = new InputDialogDemo( ); frame.setForeground(Color.black); frame.setBackground(Color.gray); frame.addWindowListener(new WindowCloser( ) ); frame.getContentPane( ).add(panel,"Center"); frame.setSize(panel.getPreferredSize( ) ); frame.setVisible(true); } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.getWindow( ) ; win.setVisible(false); System.exit(0); } } Output

629

630 Chapter-28

Java.net

Introduction to Networking

A group of computer connected by cable to share the information is popularly known as network. A network is a set of computers and peripherals, which are physically connected together. Networking enables sharing of resources and communication. Internet is a network of networks. Java applets can be downloaded from a Web site. This is one of the main attractions of java. Networking in java is possible through the use of java .net package. The classes within this package encapsulate the socket model developed by Berkeley software Division. Network required some components, such as y Server y Client y Peer y Protocol y Physical Media y Physical Devices Servers provide services to the client. If the server provides application services then server is treated as Application Server. Client access services from the Server. Peer is a computer that works as a server and also as a client.

Protocols Communication between computers in a network or a different network requires certain set of rules called protocols. Java networking is done using TCP/IP protocol. Examples of different types of protocol available in TCP/IP are, HTTP (Hyper Text Transfer Protocol enables interaction with the Internet), FTP (File Transfer Protocol enables transfer of files between computers), SMTP (Simple Mail Transfer Protocol provide e-mail facility), NNTP (Network News Transfer Protocol acts as a bulletin board for sharing news), TCP (Transmission Control Protocol acts as communicating data from source to destination within the network) and UDP (User Datagram Protocol acts as communicating data from source to destination within the network).

631

Port Number: A computer is identified by its 32 bits IP address through which the programmer can deliver the data to the destination computer within the network and outside the network. Whereas the port is the 16 bit number, which is used by the TCP or UDP to deliver the data to the appropriate application. Generally the port having three meaning. As a verb, port is a communicating channel between two application. In the context of the hardware, port takes the input from the input devices and loaded in the memory through the CPU. y In the context of TCP or UDP, data is transmitted to the appropriate application within the network or outside the network. Port number ranges from 0-65535. Whereas the registered ports are in between 1-1023. Specific ports are assigned to some protocols by TCP/IP. A few example are port number 21 is assigned for FTP, 23 is assigned for Telnet, 25 is assigned for e-mail, 80 for HTTP and so on. Each protocol establishes specific set of rules to communicate. For example, to transfer hypertext pages and images, web browsers and servers use the HTTP protocol. y y

Client/Server

A computer, which requests for some service from another computer, is called a client. The one that processes the request is called Server. A server waits till one of its clients makes a request. It can accept multiple connections at a time to the same port number. Multithreading is used to serve multiple users at the same time

IP Address Each and every computer connected within a network has a unique IP address. It is similar to every student of a batch having a unique id. An IP address is a 32-bit number which has four numbers separated by periods. It is possible to connect to the Internet either directly or by using Internet Service Provider. By connecting directly to the Internet, the computer is assigned with a permanent IP address. In case connection is made using ISP, it assigns a temporary IP address for each session. A sample IP address is given below.

632

80.0.0.53

IP address .

Domain Naming Service

It is very difficult to remember the IP address to connect to the Internet. The Domain Naming Service (DNS) is used to overcome this problem. DNS maps one particular IP address to a string of characters which is popularly known as domain name. For example, www.yahoo.com implies com is the domain name reserved for US commercial sites, yahoo is the name of the company and www is the name of the specific computer, which is yahoos server.

InetAddress There are classes provided in java to enable networking. They are found in the java .net package. InetAddress is one such class, which is used to encapsulate the IP address and the DNS. To create an instance of InetAddress class, factory methods are used, as there are no constructors available for this class. Factory methods are conventions where static methods return an instance of that class. Methods static InetAddress getLocalHost( ) static InetAddress getByName(String hostName) Returns InetAddress object representing local host Returns InetAddress for the host passed to it.

633 static InetAddress[] getAllByName(String name) Returns an array of InetAddresses that represent all of the addresses that a particular name resolves to.

ll the methods throw UnKnownHostException, if they are unable to locate the host. Program: import java.net.*; public class InetDemo { public static void main(String args[])throws UnknownHostException { InetAddress ia=InetAddress.getLocalHost(); System.out.println(ia); ia=InetAddress.getByName("localhost"); System.out.println(ia); InetAddress is[]=InetAddress.getAllByName("localhost"); for(int i=0;i<is.length;i++) { System.out.println(is[i]); } } }

Output:

634

Datagram Datagram is a type of packet that represents an entire communication. There is no necessity to have connection or disconnection stages when communication using datagrams. This is less reliable than communication using TCP/IP. There are two classes in java, which enable communication-using datagrams. DatagramPacket is the class, which acts as the data container, and DatagramSocket is a mechanism used to send or receive DatagramPackets. DatagramPacket DatagramPacket is a class present in java.net package. This class works as a dada container. This class is used to broken the data into small packets and send it over the net through the DatagramSocket class. A DatagramPacket object can be created as follows. Constructors

The constructor of the class is overloaded. DatagramPacket (byte data[ ], int size) The above constructor takes a byte array and its size as its parameter. DatagramPacket (byte data [], int size, InetAddress ia, int port) In addition to the byte array and its size, the above constructor takes the InetAddress and the port as its parameters.

Methods public synchronized int getPort() public synchronized byte[] getData() Returns the port number. Returns the data in byte format

635 public synchronized int getLength() public void setPort(int i) public void setData(byte data[]) Returns the length of the packet Set the port number Set the data in the packet.

DatagramSocket

The class DatagramPacket does not provide methods to send or receive data. The DatagramSocket class takes up this job. Listed below are its constructors and some of its methods.

Constructors

The creation of a DatagramSocket object throws a SocketException, which must be handled. There are two constructors of DatagramSocket class. The first constructors does not take any parameters and is created as given below: DatagramSocket s = new DatagramSocket( ) ; The next constructor is given as follows. DatagramSocket s= new DatagramSocket (int port); Methods public void send(DatagramPacket d) public synchronized void receive(DatagramPacket p) public void close( ) public int getPort() Dispatches the given DatagramPacket object Receives the given DatagramPacket object

Closes the socket connection Returns the port number of DatagramSocket

636 public InetAddress getLocalAddress() Return the InetAddress of the local address.

Note - The send and receive methods of the DatagramSocket class throw an IOException which must be caught.

Write The Server side Application import java.net.*; import java.io.*; public class DataServer { public static DatagramSocket ds; public static int clientport=9999,serverport=10000; public static void main(String args[])throws Exception { byte buffer[]=new byte[2300]; ds=new DatagramSocket(serverport); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Text"); InetAddress ia=InetAddress.getByName("localhost"); while(true) { String s=br.readLine(); if((s==null)||s.equalsIgnoreCase("end")) {

637 break; } buffer=s.getBytes(); ds.send(new DatagramPacket(buffer,buffer.length,ia,clientport)); } } }

y y y

Write the server side application Compile it :- javac DataServer.java Execute it:- java DataServer

Write The Client Side Application

import java.net.*; import java.io.*; public class DataClient1 { public static DatagramSocket ds; public static int clientport=9999,serverport=10000; public static void main(String args[])throws Exception

638 { byte buffer[]=new byte[2300]; ds=new DatagramSocket(clientport); System.out.println("Client is waiting for server to send data"); DatagramPacket p=new DatagramPacket(buffer,buffer.length); while(true) { ds.receive(p); String str=new String(p.getData(),0,p.getLength()); System.out.println(str); } } } y y Compile Client side Application:- javac DataClient1.java Execute Client side application:- java DataClient

TCP/IP TCP/IP sockets are the most reliable, bi-directional, stream protocols. It is possible to send arbitrary amounts of data using TCP/IP. Sockets are used for data communication using this protocol. There are two kinds of sockets in java a server and a client. Java.net package used ServerSocket class through the server waits for the client and the client connects to the server using Socket class present in java.net package.

639

Socket Class

A Socket object establishes connection between the client and the server. In java Socket is a communicating channel between source and destination. On a Socket we write the data. From the Socket we read the data.

Constructors The first constructor takes the hostname and port as its parameters to create a Socket object. Creation of a Socket object throws an UnknowmHostException or an IOException, which must be caught.

Socket s = new Socket (String hostName, int port);

The next constructor takes the InetAddress and port number as its parameters to create a Socket object. The constructor throws an IOException or an UnknowmHostException, which must be caught and handled.

Socket s=new Socket(InetAddress ia , int port);

Methods InetAddress getInetAddress( ) Returns InetAddress associated with Socket object

int getport( )

Returns remote port to which this Socket object is connected Returns the local port to which the Socket object is connected

int getLocalport ( )

640 InputStream getInputStream( ) OutputStream getOutputStream( ) void close ( ) Returns the InputStream associated with this socket Returns the outputSream associated with this socket Closes both InputStream and OutputStream

How to read the data from Socket?

BufferedReader br=new BufferedReader (new InputStreamReader ( socket.getInputStream ()))

How to write the data on Socket?

PrintWriter out=new PrintWriter(socket.getOutputStream(),true);

ServerSocket Class

The ServerSocket object waits for the client to make a connection. An object of this class registers itself as having an interest in client connections. Apart from using the methods listed above, this class has accept ( ) method which is used to wait for a client to initiate communications. The normal socket object is used for further transfer of data.

Constructors

There are two types of constructors available. The first constructor accepts a port number as parameter to create a ServerSocket object on that port. Creation of this object throws an IOException, which must be caught and handled.

641

ServerSocket ss=new ServerSocket(int port) ;

The next constructor accepts a port and maximum queue length as parameters. The queue length indicates the maximum number of client connections that the system can have before refusing further connections.

ServerSocket ss=new ServerSocket(int port, int max) ;

Write the Server Side Application

import java.net.*; import java.io.*; public class FServer { public static void main(String args[])throws Exception { ServerSocket ss=null; try{ ss=new ServerSocket(9999); }catch(IOException ie) {} Socket s1=null; try{ s1=ss.accept();

642 }catch(Exception e) {} PrintWriter out=new PrintWriter(s1.getOutputStream(),true);

BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter The File Name"); String s=stdin.readLine(); File f=new File(s); if(f.exists()) { BufferedReader d=new BufferedReader(new FileReader(s)); String line; while((line=d.readLine())!=null) { out.write(line); out.flush(); } d.close(); } out.close(); s1.close(); ss.close(); } }

643

y y y

Write the server side application through ServerSocket class Compile the server side application by javac FServer.java Execute the Server side application by java FServer

Write the client side Application import java.net.*; import java.io.*; public class FClient { public static void main(String args[])throws Exception

{ Socket s=null; BufferedReader in=null; String userinput=null; try{ s=new Socket(InetAddress.getLocalHost(),9999); in=new BufferedReader(new InputStreamReader(s.getInputStream())); }catch(Exception ue) {

644 }

while((userinput=in.readLine())!=null) { System.out.println(userinput); } in.close(); s.close(); } } y y Compile the client side application javac FClient.java Execute the client side application java FClient

The ServerSocket object waits for a client to make a connection at some port number 9999. Once a client makes a connection, the accept method is called to accept the connection, after which a message is displayed giving details about the local port number, client address and the port number of the client. The server program requests for a file name. This file may present in the current working directory or anywhere. A check is made at the server end and if the file exists, the data is read by the socket object using the getInputStream () method. The transfer of data between the client program and the server program takes using the socket object. The client end displays the file contents. Both the programs terminate after the request is serviced.

Communication between Server and Client application through multithreading

645 Write the server side application

import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; public class AppServer extends Frame implements ActionListener,Runnable { Button b1; TextField tf; TextArea ta; ServerSocket ss; Socket s; PrintWriter pw; BufferedReader br; Thread th; public AppServer() { Frame f=new Frame("Server Side Chatting"); f.setLayout(new FlowLayout()); f.setBackground(Color.orange); b1=new Button("Send"); b1.setBackground(Color.pink); b1.addActionListener(this); tf=new TextField(15); ta=new TextArea(12,20);

646 ta.setBackground(Color.cyan); f.addWindowListener(new W1()); f.add(tf); f.add(b1); f.add(ta); try{ ss=new ServerSocket(12000); s=ss.accept(); br=new BufferedReader(new InputStreamReader(s.getInputStream())); pw=new PrintWriter(s.getOutputStream(),true); }catch(Exception e) { } th=new Thread(this); th.setDaemon(true); th.start(); setFont(new Font("Arial",Font.BOLD,20)); f.setSize(200,200); f.setLocation(300,300); f.setVisible(true); f.validate(); } private class W1 extends WindowAdapter { public void windowClosing(WindowEvent we)

647 { System.exit(0); } } public void actionPerformed(ActionEvent ae) {

pw.println(tf.getText()); tf.setText("") } public void run() { while(true) { try{ ta.append(br.readLine() +"\n"); }catch(Exception e) { } } } public static void main(String args[]) { AppServer a=new AppServer(); } } ;

648

y y

Compile Server side application:- javac AppSerer.java Execute Server side application:- java AppServer

Write the client side application

import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; public class AppClient extends Frame implements ActionListener,Runnable { Button b;

649 TextField tf; TextArea ta; Socket s; PrintWriter pw; BufferedReader br; Thread th; public AppClient() { Frame f=new Frame("Client Side Chatting"); f.setLayout(new FlowLayout()); f.setBackground(Color.orange); b=new Button("Send") ;

b.addActionListener(this); f.addWindowListener(new W1()); tf=new TextField(15); ta=new TextArea(12,20); ta.setBackground(Color.cyan); f.add(tf); f.add(b); f.add(ta); try{ s=new Socket(InetAddress.getLocalHost(),12000); br=new BufferedReader(new InputStreamReader(s.getInputStream())); pw=new PrintWriter(s.getOutputStream(),true); }catch(Exception e)

650 { } th=new Thread(this); th.setDaemon(true); th.start(); setFont(new Font("Arial",Font.BOLD,20)); f.setSize(200,200); f.setVisible(true); f.setLocation(100,300); f.validate(); } private class W1 extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } public void actionPerformed(ActionEvent ae) { pw.println(tf.getText()) tf.setText("") } public void run() { while(true) ; ;

651 { try{ ta.append(br.readLine()+"\n") ; }catch(Exception e) } } public static void main(String args[]) { AppClient a1=new AppClient(); } } {}

y y

Compile the client side application:- javac AppClient.java Execute the client side application:- java AppClient

652

URL

URL stands for Uniform Resource Locator and it points to resource files on the Internet. The term Web is often used when there is a discussion about the Internet. The Web is a collection of higher level protocols and file formats. An important aspect of a Web is its ability to locate files on the Internet. The URL helps in locating such files using their addresses on the Net. Java provides URL class that provides an API to access information across the Internet.

Components of URL

The URL has four components the protocol, IP address or the hostname, port number and actual file path. The protocols may be HTTP, SMTP, NNTP, FTP or gopher. The most commonly used protocol of the web is the hyper text transfer protocol (HTTP). The IP address is delimited on the let by double slashes (//) and on the right by a slash (/) or a colon. The third component, port, is optional and is delimited on the left by a colon and on the right by a slash. The last component specifies the actual file path.

Given below is an example of an URL.

http://www.yahoo.com:80/root/htmlfiles/index.html

http is the protocol,www.yahoo.com is the host name, 80 is the port number and the file index.html is stored under root/html files directory.

653 Constructors

There are four constructors and creation of a URL object throws a MalformedURLException.

The first constructor takes the urlname as parameter and creates an object. This is the most commonly used constructor to create the URL object.

URL u = new URL(String urlname);

The next constructor takes the name of the protocol, host name, port number and the file path as parameters.

URL u = new URL (String protocolname, String hostname, int port, String path);

The third constructor accepts three parameters as given below.

URL u = new URL (String protocolname, String hostname, String path);

The last constructor accepts the URL object and a string.

URL u = new URL (URL urlobj, String urlspecifier);

Methods

int getPort( )

Returns specified pot number in URL / returns 1 if port is not explicitly set

654 String getHost( ) String getFile( ) Returns host name specified in URL Returns the path of file specified in URL Opens file specified in the URL

InputStream openStream( ) URLConnection openConnection()

Returns the reference of URLConnection associated with URL object. Returns the protocol name

String getProtocol()

Program: import java.net.*; public class U1 { public static void main(String args[])throws Exception { URL u=new URL("http://sify.com:80/index.jsp"); System.out.println("Protocal Used Is "+u.getProtocol()); System.out.println("Host name is "+u.getHost()); System.out.println("Port Number is "+u.getPort()); System.out.println("File Name Is "+u.getFile()); } }

655 Output:

Program: import java.io.*; import java.net.*; public class ReadUrl { public static void main(String args[])throws Exception { URL u=new URL("http://localhost:8085/ex1.jsp"); BufferedReader br=new BufferedReader(new InputStreamReader(u.openStream())); String line; while((line=br.readLine())!=null) { System.out.println(line); } br.close(); } }

656 URLConnection

URLConnection is an abstract class present in java.net package. It is the super class of all classes that represents a communication link between the application and URL. URLConnection is a general-purpose class, which provides methods to know more about the remote resource.

Methods

InputStream getInputStream() String getContentType( )

Read the data from URLConnection reference Returns content type & return null if not known Returns last modified date of object & 0 if not known Returns length of content & -1 if not known Connect the URL object

long getLastModified( )

int getContentLength( )

abstract void connect()

Program

import java.net.*; import java.io.*; public class UrlConn {

657

public static void main(String args[])throws Exception { URL u=new URL("http://localhost:8085/ex1.jsp"); URLConnection uc=u.openConnection(); BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while((line=br.readLine())!=null) { System.out.print(line); } } }

658

CHAPTER 29 JDBC(Java Database Connectivity)

Introduction to JDBC

JDBC stands for Java Database Connectivity .JDBC is an API whose prime task is to execute SQL statements. JDBC API contains a number of classes and interfaces for executing SQL statements. Java Database Connectivity (JDBC) is a standard developed by Sun Microsystem. JDBC is a specification given by Sun Microsystem and standard followed by X/Open SAG (SQL Access Group) CLI (Call Level Interface) to interact with any Database. JDBC API lets the programmer to invoke SQL commands from Java programming language methods. Call Level Interface is a library of function calls that supports SQL statements. CLI requires neither host variables nor other embedded SQL concepts that would make it less flexible from a programmers perspective. It is still possible, however, to maintain and use specific functions of a database management system when accessing the database through a CLI.

659

The goal of creating JDBC is to create an interface that keeps simple tasks simple, while ensuring the more difficult and uncommon tasks are at least made possible. JDBC was developed in 1996. Microsoft ODBC API is used to connect most of the database. But ODBC API is not directly used with java application and applet due to numerous number of reasons. Hence the need for JDBC came into existence. Java and JDBC The combination java with JDBC is very useful because it lets the programmer run his/her program on different platforms. Java programs are secure, robust, automatically downloaded from the network and java is an elegant language to create database applications. JDBC API enables java applications to interact with different types of databases. It is possible to publish vital information from a remote database on a web page using a java applet. Some of the advantages of using java with JDBC are y y y y y Supports a variety of Relational databases. Easy and economical Continued usage of already installed databases Development time is short Installation and version control simplified

There are two types of interfaces-low-level interface and high-level interface. While high level interfaces are user-friendly, low-level interfaces are not. Java uses JDBC API which is a low-level API interface that is used to execute various SQL commands. JDBC API contains a number of pre defined methods where SQL statements are passed as a parameter in String format. JDBC Vs ODBC

The most widely used interface to access relational database today is Microsofts ODBC API. ODBC performs similar tasks as that of JDBC and yet JDBC is preferred due to the following reasons: j ODBC API uses C interface for making the connections with number of databases but from security and implementation point of view JDBC API was introduced. j Pointer is an integral part of ODBC whereas java never permits the programmer to use pointer.

660 j On all client machines ODBC drivers are manually installed whereas JDBC drivers are installed automatically in every client machines.

JDBC Driver Models JDBC supports two tier and three tier models. Two tier model In two tier model java applets and applications are directly connected with any type of database. In two tier model client directly communicate with database server through JDBC driver. Three tier model In three tier model client connect with database server through a middle tier server, which is used for various purposes. Middle tier server performs various functions: j It extracts the SQL commands from the clients and send these commands to database server. j Extracting the results from the database server and submit the result to the client.

Different types of Driver Managers JDBC API contains three components: y y y Application Driver Manager Driver.

The JDBC application through the predefined methods executes SQL Statements and retrieves the results from the database server. Java application and applets are connected with JDBC driver through the DriverManager. The installed JDBC driver is JDBC compatible or not is checked through Driver component. JDBC driver is of four different types. They are: j j j j The JDBC-ODBC bridge plus ODBC driver Native-API partly-java driver JDBC-Net pure java driver Native-protocol pure java driver

661 The JDBC-ODBC Bridge plus ODBC driver This driver is popularly known as Type-1 driver. The Type-1 driver is used to bridge the gap between JDBC-ODBC Bridge and ODBC driver. As ODBC driver installed manually in each client machine so it is not advisable to select this Type-1 driver for a network whose size is large. Architecture:

Java Application

JDBC-ODBC Driver

Native ODBC client driver libraries

DBMS Interface client libraries

DBMS

DBMS Interface server libraries

If oracle is the backend and java is the frontend how the programmer set the path.

Set path=C:\Program Files\Java\jdk1.5.0\bin;


C:\oraclexe\app\oracle\product\10.2.0\server\BIN;

Set classpath=C:\Program Files\Java\jdk1.5.0\bin;


C:\oraclexe\app\oracle\product\10.2.0\server\BIN;

662 Example-1(Type-1 Driver) import java.sql.*; public class Type1 { public static void main(String ll[]) { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con= DriverManager.getConnection("jdbc:odbc:omm","scott","tiger"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp"); while(rs.next()) { String name=rs.getString("ename"); int salary=rs.getInt("sal"); System.out.println("Employee Name is: "+name+" and "+"Salary is :"+salary); } }catch(Exception e1) { System.out.println(e1.getMessage()); } } }

663 Native-API partly-java driver This driver is popularly known as Type-2 driver. This driver is used to convert JDBC calls to client API for any database. Through this driver some binary code has to be loaded in each and every client machine like the bridge driver in case of Type-1 and hence is not suitable for large networks.

Architecture:

JDBC Applicaion

JDBC Type-2 Driver

DBMS Client libraries (Native)

DBMS

DBMS Interface server libraries (Native)

If oracle is the backend and java is the frontend how the programmer set the path. In type-2 driver programmer has to install any middleware server like weblogic server.

%POINTBASE_CLASSPATH%; %JAVA_HOME%\jre\lib\rt.jar;%WL_HOME%\server\lib\webservices.jar;%WL_HOM E%\server\lib\ojdbc14.jar;

Set CLASSPATH=%WEBLOGIC_CLASSPATH%;

Example-2(Type-2 Driver) import java.sql.*; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class Type2 { public static void main(String[] args) {

664

try{ String datasource="ds1"; String pool="pool1"; Properties p=new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"webl ogic.jndi.WLInitialContextFactory"); p.put(Context.PROVIDER_URL,"t3://localhost:700 1"); InitialContext ctx=new InitialContext(p); DataSource source=(DataSource)ctx.lookup(datasource); Connection con=source.getConnection(); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp"); while(rs.next()) { String name=rs.getString("ename"); int salary=rs.getInt("sal"); System.out.println("Employee Name is: "+name+" and "+"Salary is :"+salary); } } catch (Exception e) { }

} }

JDBC-Net pure Java driver This driver is popularly known as Type-3 driver. This Type-3 driver converts JDBC calls into DBMS independent net protocol. The middleware server converts the net protocol to a DBMS protocol. Through this driver the middle ware server connects with a variety of clients. Whatever protocols used in the middleware server is vendor dependent.

665

ARCHITECTURE
JDBC Applicaion JDBC Type-3 Driver Middleware listener DBMS interface client

DBMS

DBMS Interface server listener

Example-3(Type-3 Driver) import java.sql.*; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class Type3 { public static void main(String[] args) { try{ String datasource="ds3";

String pool="pool3"; Properties p=new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi .WLInitialContextFactory"); p.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ctx=new InitialContext(p); DataSourcesource =(DataSource)ctx.lookup(datasource); Connection con=source.getConnection(); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp"); while(rs.next()) { String name=rs.getString("ename");

666

int salary=rs.getInt("sal"); System.out.println("Employee Name is: "+name+" and "+"Salary is :"+salary); } }catch (Exception e) { } } }
Native-protocol pure java drivers This driver is popularly known as Type-4 driver. Type-4 driver converts JDBC calls to network protocols used by the DBMS directly. This type driver supports two-tier architecture. Through this driver client directly make requests to the database server. Type-3 and Type-4 Driver are the most preferred ways to access data from databases Server.

ARCHITECTURE
JDBC Applicaion JDBC Type-4 Driver DBMS Interface server listener

DBMS

Set path=C:\Program Files\Java\jdk1.5.0\bin;


C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;

667

Set classpath=C:\Program Files\Java\jdk1.5.0\bin;


C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;

Example-4(Type-4 Driver) import java.sql.*; class Customer { public static void main(string args[]) throw SQLException { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); System.out.println("Connection to the database.."); try{ Connection cn=DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); Statement st=cn.createStatement(); ResultSet rs=st.executeQuery("select * from emp1); while(rs.next()) { String s=rs.getString(1); System.out.println(s); }

st.close(); cn.close(); }catch(Exception ex)

668 { System.out.println("The exception raised is : " + ex); } } }

In the url, thin is the JDBC driver, rashmi is the database name, 1521 is the port on which the connection to the database name, 1521 is the port on which the connection is to be established and orc11 is the system ID. sai is the user id and sai is password.

java.sql package We have seen that the JDBC API defines a set of interfaces and classes are found in the java.sql package.

Interfaces in java.sql Array This interface is used to map java array into SQL type ARRAY. This interface contains some predefined methods: j j j j Blob Blob is an interface present in java.sql package. An SQL BLOB is a built-in data type that stores a Binary Large Object in a database table. The methods of this interface are: j getBinaryStream() j getBytes() j length() getArray() getBaseType() getBaseTypeName() getResultSet()

669 j position() CallableStatement

CallableStatement is an interface present in java.sql package.CallableStatements is used to call SQL stored procedures. A CallableStatements may return a ResultSets or multiple ResultSets. Escape syntax is used for procedures that return a parameter. This interface extends the PreparedStatement interface. The methods in this interface include the getXXX(where XXXstands for any datatype) methods and the following methods. j registerOutParameter() j wasNull() Clob

Clob is an interface is present in java.sql package. In SQL CLOB is a built-in data type that stores a Character Large Object in a database table. The methods of the CLOB interface are: j j j j j getAsciiStream() getCharacterStream() getSubSting() length() position()

Connection Connection is an interface present in java.sql package. A connection is session in a specific database engine. Information such as database tables, stored procedures and other database objects may be obtained from a connection with the getMetaData() methods. Some of the important methods in this interface are: j j j j j j commit() creaeStatement() getAutoCommit() isClosed() isReadOnly() prepareCall()

670 prepareStatement() rollback() setAutoCommit() setReadOnly()

j j j j

DatabaseMetaData The DatabaseBaseMetaData interface provides information regarding the database itself, such as version information, table names, and supported functions. Many of the method of this interface return lists of information in the form of ResultSet objects. Some of the important methods of this interface are: j j j j j j j j Driver getCatalogs() getColumns() getConnection() getDatabaseProductVersion() getDriverName() getDriverVersion() getMaxRowSize() isReadOnly()

Every driver must implement the Driver interface. The Driver interface is used to create connection objects. When a Driver class is loaded, first it must create an instance of the driver and then it registered in the DriverManager. The following are the methods present in the Driver interface.

j j j j j j Ref

acceptsURL() connect() getMajorVerson() getMinorVerson() getPropertyInfo() jdbcCompliant()

Ref is an interface present in java.sql package. This interface is a reference to an SQL structure type value in the database. The reference of the interface is saved in the persistent storage mechanism. The method present in this interface is

671 getBaseTypeName()

ResultSet

The ResultSet interface provides methods for the retrieval of data returned by a SQL statement execution. A ResultSet maintains a cursor pointing to its current row of data. The most often used methods, namely, getXXX and updateXXX methods are present in this interface. The other important methods present in this interface are: j j j j j j j j j j absolute() afterLast() beforeFast() cancelRowUpdate() close() deleteRow() insertRow() next() previous() wasNull()

DatResultSetMetadata

The ResultSetMetaData interface is used for the collection of meta data information associated with last ResultSet object. Some of the important methods of this interface are:

j j j j j

getCatalogName() getColumnName() getColumnCount() isNullable() isReadOnly()

SQLData

SQLData is an interface present in java.sql package. This interface is used to map the SQL user defined data types.

672 j getSQLTypeName() j readSQL() j writeSQL() SQLInput

SQLInput is an interface present in java.sql package. This interface contains an InputStream that contains a stream oriented values. The programmer does not invoke this interface. Rather, the driver uses it. The readXXX methods (where XXX represents any data type) of this interface are used to read the attributes from the input stream. Another method in this interface is: j wasNull() SQLOutput

SQLOutput is an interface present in java.sql package. This interface used the OutputStream for writing the attributes of user defined data types in the data base. This interface is also used by the driver and the programmer does not invoke it directly. The writeXXX methods (where XXX represents any data type) of this interface are used to write data on SQLData object.

Statement

The methods of the Statement interface are used to execute SQL statements and retrieve data into the ResultSet. A Statement can open only one ResultSet at a time. Some of the important methods of this interface are:

j j j j j j j j

cancel() close() execute() executeBatch() executeUpdate() getConnection() getFetchSize() getMaxRow()

673

j getAttributes() j getSQLTypeName() Classes in java.sql

Date

The Date class contains methods to perform conversion of SQL date formats and Java Date objects. The Date class contains the following important methods:

j j j j j j j j j

getHours() getMinutes() getSeconds() setHours() setMinutes() setSeconds() setTime() toString() valueOf()

DriverManager The DriverManager class is used to load and unload the drivers and establish the connection with the database. The important methods of this class are: j j j j j getConnection() getDriver() getLogStream() println() registerDriver()

DriverPropertyInfo The methods of the DriverPropertyInfo class are used for the insertion and retrieval of driver properties. It is useful for advanced programmers. This class inherits its methods from the java.lang.Object class.

674

Time

The Time class extends the Date class. It allows the JDBC to identify java.util. Date as a SQL Time value. The methods of this class are used to perform SQL time and java Time object conversions. The methods available in this class are y j j j j j j j j j j getDate() getDay() getMonth() getMonth() getYear() setDate() setMonth() setTime() setYear() toString() valueOf()

TimeStamp

The TimeStamp class also extends the Date class. It provides additional precision to the java Date object by adding a nanosecond field. The methods of this class are: j j j j j j j after() before() equals() getNanos() setNanos() toString() valueOf()

Types

The Types class extends the java.lang.object class. The Types class defines constants that are used to identify generic SQL types, called JDBC types. Its methods are inherited from the class object.

675

Exceptions in java.sql

There are four Exceptions in java.sql class. Let us see each of them in detail.

BatchUpdateException The BatchUpdateException extends the SQLException. When an error occurs in the batch update operation then BatchUpdateException is thrown at runtime.

SQLException

The SQLException extends Exception. The SQLException provides information on a database access error. The information given in the exception includes a string describing the error, a string describing the SQLState, the error code and a chain to the next exception. SQLWarning

The SQLWarning extends SQLException. The SQLWarning provides information on database access warnings and is chained to the object whose method caused it to be report. Steps for using JDBC There are seven basic steps for using JDBC to access a database. They are:

j j j j j j j

Import the java.sql package Register the driver Connect to the database Create a statement Execute the statement Retrieve the results Close the statement and the connection

676 Before dealing about each case. of these steps in detail, let us consider the following

Import the java.sql package

The interfaces and classes of the JDBC API are present inside the package called java.sql. When you want to make java-database connectivity then the programmer is bound to import java.sql package. import java.sql.*;

Register the driver

In java if the programmer used to register the driver then the programmer call the static method of DriverManager class. Syntax DriverManager.registerDriver(Driver dr) ;

Connect to the database The next step is to connect to the database .The getConnection() method is used to establish the connection.

Syntax DriverManager.getConnection(String url, String user , String passwd);

Where url is the database url of the form jdbc:subprotocol:subname,user is the database user and passwd is the password to be supplied to get connected to the database. The return value connected to the url.

677 Create a statement

A statement can be created using three methods, namely, createStatement(),prepareStatement() and prepareCall().The syntax of each of these is given below:

Syntax cn.createStatement();

Where cn is a connection object. This method object for sending SQL statement to database.

creates and returns a statement

cn.createStatement(int rsType, int rsConcur);

Where cn is a connection object, rsType and rsConcur denote and type and concurrency of ResultSet , respectively. This method creates a statement object that will generate ResultSet objects with the given type and concurrency. cn.prepareStatement(String str); where cn is a connection object and str is a sql statement that may contain one or more IN parameter place holders. This method creates and returns a PreparedStatement object for sending sql statements with parameters to the database. cn.preparestatement(string str, int rsType , int rsConcur ) ; Where cn is a connection object, str is a SQL statement, rsType is a result set type and rsConcur is a concurrency type. This method creates a preparedstatement object that will generate ResultSet objects with the given concurrency. cn.prepareCall(string str);

678 where cn is a connection Object and is a SQL statement that may contain one or more IN parameter placeholders. This method creates and returns a CallableStatement object for calling database-storing procedures.

cn.preparecall(String str, int retype, int reConcur); Where cn is a connection object, str is a SQL statement, retype is a result set type and rsConcur is a concurrency type. It creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it is more efficient to use a PreparedStatement.

Execute the Statement We have three methods to execute the statement. They are execute (), executeQuery() and executeUpadate(). Let us see the syntax of these below:

Syntax Stmt.execute(); Where stmt is a statement object. This method returns a Boolean value and is used to execute any SQL statement. Stmt.execute(string str); Where stmt is a statement object and str is an SQL statement. This method is used execute an SQL statement that may return multiple results. The return value is a Boolean , which is true if the next result is a ResultSet and false if it is an update count, or there are no more results. Stmt.executeQuery(); Where stmt is a PreparedStatement object. The method returns a result set generated by executing the query in stmt.

679 Stmt.executeQuery(string str); This method takes query as string & is invoked by the statement object Stmt & returns the ResultSet. stmt.executeUpdate(); Here stmt is an object of PreparedStatement. By the object of PreparedStatement this method executes SQL statements. In case of INSERT, UPDATE, DELETE statement this method return value is an int, which counts the number of rows are affected. Stmt.executeUpdate(string str); Here stmt is a statement object and str is a SQL statement for performing INSERT, UPDATE or DELETE task. Retrieve the results The results of the SQL statements (in particular q ueries are) are stored in a ResultSet object. To retrieve the data from the ResultSet we need to use the getXXX methods. These methods retrieve the data and convert it to a java data type. There is a separate getXXX methods for each data type. For example, getString is used to retrieve the string value and getDate() is used to retrieve a date value.The getXXX takes one argument which is the index of the column in the ResultSet and return the value of the column. To move in to the next row in the ResultSet we make use of the ResultSet.next() method. Close the statement and connection It is not absolutely necessary to close the connection. But , since open connection can cause problem, it is better to close the connections. The close() method is used to close the statements and connection.The syntax is given below:

Syntax Stmt.close(); Where stmt is a statement object to be closed. This methods release stmts database.The return type is void. Cn.close(); Where cn is the connection to be closed.

680

Executing DDL and DML Commands Once the connection with the database is established, the user can start creating and working with the objects of the database. In this part we will be learning how to execute Data Definition Language (DDL) and Data Manipulation Language(DML) commands.

DDL Commands

The DDL commands are create, alter and drop .Let us learn how to execute each of these. The create command is used to create database tables. Let us consider the case of The Rhythm. The following are the tables needed by them:

Customer

Custld CustName Address

Number(3) varchar2(15) varchar2(30)

Product

Prodid ProdName

Number(3) varchar2(10)

681 Price Number(5,2) Number(4)

Stock-on-hand

Transaction TranDt TranId ProdId CustId Qty Date Number(3) Number(3) Number(3) Number(2)

The create statement for creating the above three tables are as follows:

Create table Customer (CustId Number(3), CustName varchar2(15), Address varchar2(30)); Create table Product (ProdId Number(3),ProdName Number(5,2), Stock- on- hand Number(4) ); varchar2(10), Price

Create table Transaction (Custid Number(3),ProdId Number(3),Qty Number(2) , TranDt Da2te);

Number(3),tranid

Example-5(Create The table)

import java.sql.* ; public class Customer1 { public static void main(String args[])throws SQLException { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

682 System.out.println("Connection to the database"); Connection cn=DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); System.out.println("Connected to the database"); Statement st =cn.createStatement (); try{ st.executeUpdate("create table Customer(CustId number(3),CustName varchar2(15),Address varchar2(30))");

System.out.println(Table Customer Created); }catch(SQLException ex) { System.out.println(The Exception raised is + ex); } st.close(); cn.close(); } }

Connection to the database Connection to the database Table customer created

Example-6(Table Transaction Altered) import java.sql.*;

683 public class Customer_alt { public static void main(String args[])throws SQLException { DriverManager.registerDriver(new oracle.jdbc.driver.oracleDriver()); try{ Connection cn=DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); System.out.println("Connected to the database"); Statement.st=cn.createStatement(); st.executeUpdate("alter Number(4))"); System.out.println("Table Transaction altered"); }catch(Exeception ex) { System.out.println("The Exeception raised is:"+ ex); } } } table Transaction modify(Qty

The output is as follows:

Connected to the database Table Transaction altered

684 Example-7(Column Dropped) import java.sql.*; public class Customer_drop { public static void main(String args[])throws SQLExeception { DriverManager.registerDriver(new oracle.jdbc.driver.oracleDriver()); System.out.println("Connecting to the database.."); try{ Connection cn=DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); System.out.println("Connected to the database"); Statement st=cn.createStatement(); st.executeUpdate("drop table Trans"); System.out.println("Table Trans dropped"); }catch(Exeception ex) { System.out.println("The exception raised is:"+ex); } } } The out put is follows: Connected to the database Column amount dropped

DML Commands

685

The Data Manipulation Language Commands are the select, insert, update and delete commands. Now the tables are created. Pioneer System Ltd. wants to input the data in the tables. The insert command is used to input the data and the select command is used to retrive the records from the tables.

Example-8(Insert a row in the table)

import java.sql.*; public class CustomerInsert { public static void main(String args[])throw SQLException { DriverManager.registerDriver(new oracle.jdbc.driver.Oracle.OracleDriver()); try{ Connection cn=DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); System.out.println(Connected to the database); Statement st = cn.createStatement(); st.executeUpdate("insert 100,Naya Bazar,Cuttack , Orissa)"); into customer values (100, usha,

System.out.println("one row inserted"); st.close(); cn.close(); }catch(Exception ex) {

686 System.out.println(The Exception raised is + ex); } } }

The output is as follows:

Connected to the database One row inserted Example-9(Update a row)

import java.sql.*; import java.io.*; public class ProductUpdate { public static void main(String args[])throws SQLException,IOException { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); String refValue; String UpdateValue; String Str; try{ Connection cn = DriverManager.getConnection ("jdbc:oracle:thin:@:1521:orc11","sai","sai"); refValue=readEntry("Enter the Product ID: "); updateValue=readEntry("Enter the new Price: ");

687 Statement st=cn.createStatement(); str="update product set price = "+ updateValue + ","+"where prodId ="+refValue ; st.executeUpdate(str); System.out.println("Row Updated"); st.close(); cn.close(); }catch(Exception ex) { System.out.println("The Exception raised is "+ex); } } static String readEntry(String prompt) { try{ StringBuffer tempo=new StringBuffer(); System.out.print(prompt); System.out.flush(); int c=System.in.read(); while (c!='\n' && c != -1) { tempo.append ((char)c); c=System.in.read (); } return tempo.toString().trim(); }catch(IOException ex)

688 { return ""; } } } The input and output are as follows: Enter the product id: 100 Enter the new price: 110.00 Row update

Example-10(Delete One row)

import java.sql.*; public class CustomerDel { public static void main(string args[])throws SQLExeception { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); try{ Connection cn = DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); System.out.println("Connected to the database"); Statement st=cn.createStatement(); st.executeUpdate("delete from Product where ProdId=105"); System.out.println("One row deleted");

689 }catch(Exeception ex) { System.out.println("The Exception raised is:" +ex); } } } The output is as follows: Connected to the database One row deleted

Joins and Transactions

Sometimes we need to use two or more tables to get the data. This is a case where the join is needed. A join is a database operation that relates two or more tables by names of values that they share in common.

Joins

There are different types of joins available in Oracle. Let us see examples of equi join and outer join.

Example-11(Join Two Table)

import java.sql.*; import java.io.*: public class ListTran {

690 public static void main(String args [])throws SQLExeception,IOExeception { DriverManager.registerDriver(new oracle:jdbc:driver.OracleDriver()); try{ Connection cn= DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); Statement st= cn.createStatement(); ResultSet rs product.prodid,prodname,trained,qty product.proid=transaction.prodid"); = from st.executeQuery("select product,transaction where

System.out.println("ProdID\tProdName\t\tTranID\tQuantity"); while (rs.next()) { System.out.Println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+ rs.getgetInt(3) + "\t" + rs.getInt(4))); } rs.close(); st.close(); cn.close(); }catch(Exeception ex) { System.out.println("the exception is " +ex); } } } The output of the program is as follows:

691 Prodid 001 001 002 004 005 prodName Gajani Gajani Lagan Mann Rangeela TranID 1 4 2 5 3 Quantity 2 3 3 1 1

Transaction

In case of transaction one sql statement wait for another statement to be executed. Let us take the instance of The Rhythm. Whenever there is a transaction, in addition to the inserting the corresponding record in the Transaction table, the corresponding row in the Product table should also be updated. If either of the operations fails, then the data will become inconsistent. In order to be sure that either both the operations are executed or neither of them is executed, we can make use of transitions. A transaction is a set of one or more statements that are executed together as a unit. Cn.setAutoCommit (false) ;

Example-12(Transaction) import java.sql.*; import java.io.*; public class TransCmt { public static void main(String args [])throws SQLException,IOException

692 { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()) ; try{ Connection cn=DriverManager.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11","sai","sai"); cn.setAutoCommit(false); Statement stm=cn.createStatement(); stm.executeUpdate("Insert into transaction values(103, 101, 6, 1, '3jan-09)"); Statement st=cn.createStatement(); ResultSet rs; rs=st.executeQuery("select ProdId=103"); rs.next(); int i=rs.getInt(1); i = i -1; Statement stmt = cn.createStatement(); stmt.executeUpdate("Update Product set stock_on_hand = " + i + "where ProdId = 103"); cn.commit(); System.out.prinln("Changes commited") st.close(); cn.close(); }catch(Exception ex) { System.out.println("The Exception raised is " + ex); cn.rollback(); stock_on_hand from product where

693 } } } The output is as follows: Changes commited

Conclusion: In software development alone java is not enough. Although it provides support for distributed web application but, it has to bridge with the data base server. JDBC provides a common technology to communicate with any database. If the database is changed, no matter same program will serve your problem.

694

Chapter-30

Brain Teasers
QUESTION 1

public class Test1 { public static void main(String args[]) { class Foo { public int i = 3; } Object o = (Object)new Foo(); Foo foo = (Foo)o; System.out.println("i = " + foo.i); } }

What is the result? A. i = 3 B. Compilation fails. C. A ClassCastException is thrown at line 6. D. A ClassCastException is thrown at line 7.

QUESTION 2 public class Test2{ public static void main(String args[]){ int i =1,j =10;

695 do { if(i++> --j) { continue; } } while (i <5); System.out.println("i = " +i+ "and j = "+j);

What is the result?

A. i = 6 and j = 5
B. i = 5 and j = 5 C. i = 6 and j = 5 D. i = 5 and j = 6 E. i = 6 and j = 6

QUESTION 3 class Test { private Demo d; void start() { d = new Demo(); this.takeDemo(d); } void takeDemo(Demo demo) { demo = null; demo = new Demo(); }

696 } When is the Demo object, created on line 3, eligible for garbage collection? A. After line 5. B. After line 9. C. After the start() method completes. D. When the takeDemo() method completes. E. When the instance running this code is made eligible for garbage collection.

QUESTION 4 interface Animal { void soundOff(); } class Elephant implements Animal { public void soundOff() { System.out.println("Trumpet"); } } class Lion implements Animal { public void soundOff() { System.out.println("Roar"); } } class Alpha1 { static Animal get( String choice ) { if ( choice.equalsIgnoreCase( "meat eater" )) { return new Lion();

697 } else { return new Elephant(); } } }

Which compiles? A. new Animal().soundOff(); B. Elephant e = new Alpha1(); C. Lion 1 = Alpha.get("meat eater"); D. new Alpha1().get("veggie").soundOff();

QUESTION 5

public class Test { public static void main(String args[]) { int i = 1,j = 10; do { if(i>j) { break; } j--; } while (++i <5); System.out.println("i =" +i+" and j = "+j);

698 } }

What is the result? A. i = 6 and j = 5 B. i = 5 and j = 5 C. i = 6 and j = 4

D. i = 5 and j = 6
E. i = 6 and j = 6

QUESTION 6

class Test { public static void main(String args[]) { Holder h=new Holder(); h.held=100; h.bump(h); System.out.println(h.held); } } class Holder {

699 public int held; public void bump(Holder h) { h.held++; } }

What is the result ? A. B. C. D. 0 1 100 101

QUESTION 7

public class Test { public static void aMethod() throws Exception { try { throw new Exception(); } finally { System.out.println("finally"); } } public static void main(String args[]) { try { aMethod(); } catch (Exception e) {

700 System.out.println("exception"); } System.out.println("finished"); } }

What is the result? A. finally B. exception finished C. finally exception finished D. Compilation fails.

QUESTION 8

package test1; public class Test1 { static int x = 42; } package test2; public class Test2 extends test1.Test1 { public static void main(String[] args) { System.out.println("x = " + x); }

701 }

What is the result? A. x = 0 B. x = 42 C. Compilation fails because of an error in line 2 of class Test2. D. Compilation fails because of an error in line 3 of class Test1. E. Compilation fails because of an error in line 4 of class Test2.

QUESTION 9

public class Delta { static boolean foo(char c) { System.out.print(c); return true; } public static void main( String[] argv ) { int i =0; for ( foo('A'); foo('B')&&(i<2); foo('C')){ i++ ; foo('D'); } } }

What is the result?

702 A. ABDCBDCB B. ABCDABCD C. Compilation fails. D. An exception is thrown at runtime.

QUESTION 10

class Test { public static void main(String args[]) { double d=12.3; Decrement de=new Decrement(); de.decree(d); System.out.println(d); } } class Decrement { public void decree(double d1) { d1=d1-1.0; } }

What is the result ?

703 A. B. C. D. 0.0 1.0 12.3 11.3

QUESTION 11

public class ArrayTest { public static void main(String[] args) { float fl[], f2[]; fl = new float[10]; f2 = f1; System.out.println("f2[0]= " + f2[0]); } }

What is the result? A. It prints f2[0] = 0.0. B. It prints f2[0] = NaN. C. An error at line 5 causes compile to fail. D. An error at line 6 causes compile to fail. E. An error at line 6 causes an expectation at runtime.

QUESTION 12

public class Test { public int aMethod() {

704 static int i = 0; i++; return i; } public static void main (String args[]) { Test test = new Test(); test.aMethod(); int j = test.aMethod(); System.out.println(j); } }

What is the result? A. 0 B. 1 C. 2 D. Compilation fails.

QUESTION 13

public class Test{ public static void main(String args[]){ boolean bool = true; if(bool = false) { System.out.println("a"); } else if (bool) {

705 System.out.println("c"); } else if (!bool) { System.out.println("c"); } else { System.out.println("d"); }

What is the result? A. a B. b C. c D. d E. Compilation fails.

QUESTION 14 public class Xor { public static void main(String args[]) { byte b=10; byte c=15; b=(byte)(b^c) ;

System.out.println(b); } }

706

What is the output ? A. B. C. D. 10 5 250 245

QUESTION 15

class TestSuper { TestSuper(int i) { } } class TestSub extends TestSuper{ } class TestAll { public static void main (String [] args) { new TestSub(); } }

Which is true? A. Compilation fails. B. The code runs without exception. C. An exception is thrown at line 7. D. An exception is thrown at line 2.

QUESTION 16

707 public class Test{ public static void main(String args[]){ int i = 0; for (; i <4; i += 2) { System.out.print(i + ""); } System.out.println(i); } }

What is the result? A. 0 2 4 B. 0 2 4 5 C. 0 1 2 3 4 D. Compilation fails. E. An exception is thrown at runtime.

QUESTION 17

public class SwitchTest { public static void main(String[] args) { System.out.println("value = " + switchIt(4)); } public static int switchIt(int x) { int j = 1; switch (x) {

708 case 1: j++; case 2: j++; case 3: j++; case 4: j++; case 5: j++; default: j++; } return j + x; } }

What is the result? A. value = 3 B. value = 4 C. value = 5 D. value = 6 E. value = 7 F. value = 8

QUESTION 18

public class Foo { public static void main(String[] args) { try { return; } finally {

709 System.out.println( "Finally" ); } } }

What is the result? A. Finally B. Compilation fails. C. The code runs with no output. D. An exception is thrown at runtime.

QUESTION 19

public class Alpha1 { public static void main( String[] args ) { boolean flag; int i=0; do { flag = false; System.out.println( i++ ); flag = i < 10; continue; } while ( (flag)? true:false ); } }

What is the result?

710 A. 000000000 B. 0123456789 C. Compilation fails. D. The code runs with no output. E. The code enters an infinite loop. F. An exception is thrown at runtime.

QUESTION 20

class Super { public Integer getLenght() { return new Integer(4); } } public class Sub extends Super { public Long GetLenght() { return new Long(5); } public static void main(String[] args) { Super sooper = new Super(); Sub sub = new Sub(); System.out.println(sooper.getLenght().toString() + "," + sub.getLenght().toString() ); } }

What is the output? A. 4,4 B. 4,5 C. 5,4

711 D. 5,5 E. Compilation fails.

QUESTION 21

public class Test { public static String output =""; public static void foo(int i) { try { if(i==1) { throw new Exception(); } output += "1"; } catch(Exception e) { output += "2"; return; } finally { output += "3"; } output += "4"; } public static void main(String args[]) { foo(0); foo(1);

712 } }

What is the value of the variable output at line 23?

QUESTION 22

class Base { Base() { System.out.print("Base"); } } public class Alpha extends Base { public static void main( String[] args ) { new Alpha(); new Base(); } }

What is the result? A. Base B. BaseBase C. Compilation fails. D. The code runs with no output. E. An exception is thrown at runtime.

713

QUESTION 23

public class Test{ public static void main(String args[]){ int i = 1,j = -1; switch (i) { case 0,1: j = 1; case 2: j = 2; default: j = 0; } System.out.println("j="+j); } }

What is the result? A. j = -1 B. j = 0 C. j = 1 D. j = 2 E. Compilation fails.

QUESTION 24

714

public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() {} }

What is the result? A. AC B. BD C. ACD D. ABCD E. Compilation fails. Answer: C

715 QUESTION 25

public class Test{ public static void main(String args[]){ Float f = new Float("12"); switch (f) { case 12: System.out.println("Twelve"); case 0: System.out.println("Zero"); default: System.out.println("Default"); } } }

What is the result? A. Zero B. Twelve C. Default D. Twelve Zero Default E. Compilation fails.

QUESTION 26

public class X { public static void main(String [] args) {

716 try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() { throw new RuntimeException(); } }

What is the result? A. AB B. BC C. ABC D. BCD E. Compilation fails.

QUESTION 27

717 public class Test{ public static void main(String args[]){ for (int i =0; i <3; i++) { switch(i) { case 0: break; case 1: System.out.print("one "); case 2: System.out.print("two "); case 3: System.out.print("three "); } } System.out.println("done");

What is the result? A. done B. one two done C. one two three done D. one two three two three done E. Compilation fails. Answer: D

QUESTION 28

public class Conditional { public static void main(String args[]) {

718 int x=4; System.out.println(Value is +((x>4) ? ) 99.9 : 9); } }

What is the output ? A. B. C. D. E. QUESTION 29 Value is 99.9 Value is 9 Value is 9.0 Value is 99 Compile Time Error

class A { final public int method1(int a, int b) {return 0; } } class B extends A { public int method1(int a, int b) { return 1; } } public class Test { public static void main(Strings args[]) { B b; System.out.println("x = " + b.method1(0, 1)); }

719 }

What is the result? A. x = 0 B. x = 1 C. Compilation fails. D. En exception is thrown at runtime.

QUESTION 30

class Super { public int getLenght() { return 4; } } public class Sub extends Super { public long getLenght() { return 5; } public static void main(String[] args) { Super sooper = new Super(); Sub sub = new Sub(); System.out.println(sooper.getLenght() + "," + sub.getLenght() ); }

720 }

What is the output? A. 4,4 B. 4,5 C. 5,4 D. 5,5 E. Compilation fails.

QUESTION 31

class Test { static int x=10; static{ x+=5; } public static void main(String args[]) { System.out.println(x); } static{ x/=5; } }

721 What is the output ? A. B. C. D. Compile time error 10 15 3

QUESTION 32

public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (RuntimeException ex) { System.out.print("B"); } catch (Exception ex1) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E"); } public static void badMethod() { throw new RuntimeException();

722 } }

What is the result? A. BD B. BCD C. BDE D. BCDE E. ABCDE F. Compilation fails.

QUESTION 33

public class Test { public static void main(String args[]) { byte a=2; byte b=2; byte c=a*b; System.out.println(c); } }

What is the output A. Compile time error

723 B. 4 C. 00000100 D. 0 QUESTION 34

public class Foo { public void main( String[] args ) { System.out.println( "Hello" + args[0] ); } }

What is the result if this code is executed with the command line? java Foo world A. Hello B. Hello Foo C. Hello world D. Compilation fails. E. The code does not run.

QUESTION 35

public class Test{ public static void main(String ags[]){ int i = 0, j = 5; tp; for (;;) {

724 i++; for(;;) { if (i> --j) { break tp; break tp; } } System.out.println("i=" +i ",j ="+j);

What is the result? A. i = 1, j = 0 B. i = 1, j = 4 C. i = 3, j = 4 D. i = 3, j = 0 E. Compilation fails.

QUESTION 36

public class Test { public static void main(String Args[]) { int i =1, j = 0; switch(i) { case 2: j +=6; case 4: j +=1; default: j +=2;

725 case 0: j +=4; } System.out.println("j =" +j); } }

What is the result? A. 0 B. 2 C. 4 D. 6 E. 9 F. 13

QUESTION 37

class Super { public int i = 0; public Super(String text) { i = 1; } } public class Sub extends Super { public Sub(String text) { i = 2; }

726 public static void main(String args[]) { Sub sub = new Sub("Hello"); System.out.println(sub.i); } }

What is the result? A. 0 B. 1 C. 2 D. Compilation fails.

QUESTION 38

public class Test{ public static void main(String args[]){ int i = 1,j = 10; do{ if (i>j) { continue; } j--; } while (++i <6); System.out.println("i = " +i+" and j = "+j); }

727 }

What is the result? A. i = 6 and j = 5 B. i = 5 and j = 5 C. i = 6 and j = 4 D. i = 5 and j = 6 E. i = 6 and j = 6

QUESTION 39

public class Test { public static void main(String args[]) { int x=0,y=4,z=5; if(x>2) { if(x<5) { System.out.println(Message One) }else{ System.out.println(Message Two); } } else if(z > 5) ;

728 { System.out.println(Message Three); }else{ System.out.println(Message Four); } } }

What is the output ? A. B. C. D. Message Message Message Message One Two Three Four

QUESTION 40

public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("C"); } finally { System.out.print("B");

729 } System.out.print("D"); } public static void badMethod() { throw new Error(); } }

What is the result? A. ABCD B. Compilation fails. C. C is printed before exiting with an error message. D. BC is printed before exiting with an error message. E. BCD is printed before exiting with an error message.

QUESTION 41

class Exc0 extends Exception { } class Exc1 extends Exc0 { } public class Test { public static void main(String args[]) { try { throw new Exc1(); } catch (Exc0 e0) { System.out.println("Ex0 caught"); } catch (Exception e) {

730 System.out.println("exception caught"); } } }

What is the result? A. Ex0 caught B. exception caught C. Compilation fails because of an error at line 2. D. Compilation fails because of an error at line 6.

QUESTION 42

public class A { void A() { System.out.println("Class A"); } public static void main(String[] args) { new A(); } }

What is the result? A. Class A B. Compilation fails.

731 C. An exception is thrown at line 2. D. An exception is thrown at line 6. E. The code executes with no output.

QUESTION 43

class Bar { } class Test { Bar doBar() { Bar b = new Bar(); return b; } public static void main (String args[]) { Test t = new Test(); Bar newBar = t.doBar(); System.out.println("newBar"); newBar = new Bar(); System.out.println("finishing"); } }

What is the output?

QUESTION 44

732 interface Beta {} class Alpha implements Beta { String testIt() { return "Tested"; } } public class Main1 { static Beta getIt() { return new Alpha(); } public static void main( String[] args ) { Beta b = getIt(); System.out.println( b.testIt() ); } }

What is the result? A. Tested B. Compilation fails. C. The code runs with no output. D. An exception is thrown at runtime.

QUESTION 45

public class Test{ public static void main(String ar[]){

733 int x = 1, y =6; while (y--) { x++; } System.out.println("x =" + x + "y =" +y); } }

What is the result? A. x = 6 y = 0 B. x = 7 y = 0 C. x = 6 y = -1 D. x = 7 y = -1 E. Compilation fails.

QUESTION 46

public class Test{ public static void main(String ar[]){ int i = 0; while (true) { if(i==4) { break; } ++i; }

734 System.out.println("i="+i); } }

What is the result? A. i = 0 B. i = 3 C. i = 4 D. i = 5 E. Compilation fails.

QUESTION 47

public class Test{ public static void main(String args[]){ try { int x = 0; int y = 5 / x; } catch (Exception e) { System.out.println("Exception"); } catch (ArithmeticException ae) { System.out.println("Arithmetic Exception"); } System.out.println("finished"); } }

735

What is the result? A. finished B. Exception C. Compilation fails. D. Arithmetic Exception

QUESTION 48

public class Alpha{ public static void main( string[] args ){ if ( args.length == 2 ) { if ( args.[0].equalsIgnoreCase("-b") ) System.out.println( new Boolean( args[1] )); } } }

And the code is invoked by using the command: java Alpha -b TRUE What is the result? A. true B. null C. false D. Compilation fails.

736 E. The code runs with no output. F. An exception is thrown at runtime.

QUESTION 49

public class Test{ public static void main(String args[]){ int i = 0, j = 1; if ((i++ == 1) && (j++ == 2)) { i = 42; } System.out.println("i = " + i + ", j = " + j); } }

What is the result? A. i = 1, j = 2 B. i = 1, j = 1 C. i = 42, j = 2 D. i = 42, j = 1 E. Compilation fails. Answer: B

QUESTION 50

737 public class X { private static int a; public static void main(String [] args) { modify(a); System.out.println(a); } public static void modify(int a) { a++; } }

What is the result? A. 0 B. 1 C. Compilation fails. D. An exception is thrown at runtime.

QUESTION 51

public class Test { public static void add3 (Integer i) { int val = i.intValue(); val += 3; i = new Integer(val); } public static void main(String args[]) {

738 Integer i = new Integer(0); add3(i); System.out.println(i.intValue()); } }

What is the result? A. 0 B. 3 C. Compilation fails. D. An exception is thrown at runtime.

QUESTION 52

public class Test{ public static void main(String ar[]){ String a = null; a.concat("abc"); a.concat("def"); System.out.println(a); } }

What is the result? A. abc B. null

739 C. abcdef D. Compilation fails. E. The code runs with no output. F. An exception is thrown at runtime.

QUESTION 53

public class Test { public static void main(String [] args) { System.out.println(args.length > 4 && args[4].equals("-d")); } }

If the program is invoked using the command line: java Test One Two Three -d

What is the result? A. true B. false C. Compilation fails. D. An exception is thrown at runtime. Answer: D

QUESTION 54

740 class BaseClass { private float x = 1.of; protected float getVar() { return x; } } class SubClass extends BaseClass { private float x = 2.Of; // insert code here }

Which two are valid examples of method overriding when inserted at comment line ? (Choose two)

A. float getVar() { return x; } B. public float getVar() { return x; } C. public double getVar() { return x; } D. protected float getVar() { return x; } E. public float getVar(float f) { return f; }

QUESTION 55

class A { public byte getNumber() { return 1;

741 } } class B extends A { public short getNumber() { return 2; } public static void main(String args[]) { B b = new B(); System.out.println(b.getNumber()); } }

What is the result? A. 1 B. 2 C. An exception is thrown at runtime. D. Compilation fails.

QUESTION 56

class A { public A() { System.out.println("hello from a"); } } class B extends A {

742 public B () { System.out.println("hello from b"); super(); } } public class Test { public static void main(String args[]) { A a = new B(); } }

What is the result when main is executed? A. Compilation fails. B. hello from a C. hello from b D. hello from b hello from a E. hello from a hello from b

QUESTION 57

class MyThread extends Thread { public void run() { System.out.println("AAA");

743 } public void run(Runnable r) { System.out.println("BBB"); } public static void main(String[] args) { new Thread(new MyThread()).start(); } }

What is the result? A. AAA B. BBB C. Compilation fails. D. The code runs with no output.

QUESTION 58

public class X implements Runnable { private int x; private int y;

public static void main(String [] args) { X that = new X(); (new Thread( that )).start(); (new Thread( that )).start();

744 }

public void run() { for (;;) { synchronized (this) { x++; y++; }

System.out.println(Thread.currentThread().getName() + "x = " + x + ", y = " +y); } } }

What is the result? A. Compilation fails. B. The program prints pairs of values for x and y that might not always be the same on the same line (for example, "x = 2, y = 1"). C. The program prints pairs of values for x and y that are always the same on the same line (for example, "x = 1, y = 1"). In addition, each value appears only once (for example, "x = 1, y = 1" followed by "x = 2, y = 2"). The thread name at the start of the line shows that both threads are executing concurrently.

745 D. The program prints pairs of values for x and y that are always the same on the same line (for example, "x = 1, y = 1"). In addition, each value appears only once (for example, "x = 1, y = 1" followed by "x = 2, y = 2"). The thread name at the start of the line shows that only a single thread is actually executing.

Answer: D

QUESTION 59

public class A extends Thread { A() { setDaemon(true); } public void run() { (new B()).start(); try { Thread.sleep(60000); } catch (InterruptedException x) { } System.out.println("A done"); } class B extends Thread { public void run() { try { Thread.sleep(60000);

746 } catch (InterruptedException x) {} System.out.println("B done"); } }

public static void main(String[] args) { (new A()).start(); } }

What is the result? A. A done B. B done C. A done B done D. B done A done E. There is no exception that the application will print anything. F. The application outputs "A done" and "B done", in no guaranteed order.

QUESTION 60

public class Test { private static int[] x; public static void main(String[] args) { System.out.println(x[0]);

747 } }

What is the result? A. 0 B. null C. Compilation fails. D. A NullPointerException is thrown at runtime. E. An ArrayIndexOutOfBoundsException is thrown at runtime.

QUESTION 61

public class Test{ public static void main(String[] args) { Object obj = new Object() { public int hashCode() { returns 42; } }; System.out.println(obj.hashCode()); }

What is the result? A. 42 B. An exception is thrown at runtime. C. Compilation fails because of an error on line 12.

748 D. Compilation fails because of an error on line 16. E. Compilation fails because of an error on line 17.

QUESTION 62

public class Test { private static float[] f = new float[2]; public static void main(String args[]) { System.out.println("f[0] = " + f[0]); } }

What is the result? A. f[0] = 0 B. f[0] = 0.0 C. Compilation fails. D. An exception is thrown at runtime.

QUESTION 63

public class Test { public static void main(String[] args) { String str = NULL; System.out.println(str); } }

749

What is the result? A. NULL B. Compilation fails. C. The code runs with no output. D. An exception is thrown at runtime.

QUESTION 64

public class Test{ public static void main(String ar[]){ System.out.println(Math.sqrt(-4D)); } }

What is the result? A. -2 B. NaN C. Infinity D. Compilation fails. E. An exception is thrown at runtime.

QUESTION 65

public class Test{ public static void main(String args[]){

750 String a = "ABCD"; String b = a.toLowerCase(); b.replace('a', 'd'); b.replace('b', 'c'); System.out.println(b); } }

What is the result? A. abcd B. ABCD C. dccd D. dcba E. Compilation fails. F. An exception is thrown at runtime.

QUESTION 66

public class Foo { public static void main (String [] args) { StringBuffer a = new StringBuffer ("A"); StringBuffer b = new StringBuffer ("B"); operate (a,b); System.out.printIn{a + "," +b}; } static void operate (StringBuffer x, StringBuffer y) {

751 x.append(y); y = x; } }

What is the result? A. The code compiles and prints "A,B". B. The code compiles and prints "A,A". C. The code compiles and prints "B,B". D. The code compiles and prints "AB,B". E. The code compiles and prints "AB,AB". F. The code does not compile because "+" cannot be overloaded for StringBuffer.

QUESTION 67

public class Test { public static void stringReplace (String text) { text = text.replace ('j' , 'i'); } public static void bufferReplace(StringBuffer text) { text = text.append ("C") } public static void main (String args[]} { String textString = new String ("java"); StringBuffer textBuffer= new StringBuffer ("java");

752 stringReplace (textString); bufferReplace (textBuffer); System.out.println (textString + textBuffer); } }

What is the output?

QUESTION 68

public class Foo { public static void main (String [] args) { StringBuffer a = new StringBuffer ("A"); StringBuffer b = new StringBuffer ("B"); operate (a,b); System.out.println{a + "," +b}; } static void operate (StringBuffer x, StringBuffer y) { x.append {y}; y = x; } }

What is the result?

753 A. The code compiles and prints "A,B". B. The code compiles and prints "A,A". C. The code compiles and prints "B,B". D. The code compiles and prints "AB,B". E. The code compiles and prints "AB,AB". F. The code does not compile because "+" cannot be overloaded for StringBuffer.

QUESTION 69 interface Foo { int k = 0; } public class Test implements Foo { public static void main(String args[]) { int i; Test test = new Test (); i= test.k; i= Test.k; i= Foo.k; } }

What is the result? A. Compilation succeeds. B. An error at line 2 causes compilation to fail. C. An error at line 9 causes compilation to fail. D. An error at line 10 causes compilation to fail.

754 E. An error at line 11 causes compilation to fail.

QUESTION 70

public class Test{ public int aMethod(){ static int i=0; i++; return i; } public static void main (String args[]){ Test test = new Test(); int j = test.aMethod(); System.out.printIn(j); } }

What is the result? A. Compilation will fail. B. Compilation will succeed and the program will print "0" C. Compilation will succeed and the program will print "1" D. Compilation will succeed and the program will print "2"

QUESTION 71

public class Test {

755 public static void main(string args[]) { int 1= 0; while (i) { if (i==4) { break; } ++i; } } }

What is the value of i at line 10? A. 0 B. 3 C. 4 D. 5 E. The code will not compile. Answer: E

QUESTION 72

public class A extends Thread { private int x=2; public static void main(String args[])throws Exception {

756 new A().make(); } public A() { x=5; start(); } public void make()throws Exception { join(); x=x-1; System.out.println(x); } public void run() { x*=2; } }

What is the output?

QUESTION 73

public class Loop { static String o="";

757 public static void main(String args[]) { z: for(int x=2;x<7;x++) { if(x==3)continue; if(x==5)break z; o=o+x; } System.out.println(o); } } What is the output? QUESTION 74

public class Auto { Boolean b1=new Boolean("yes"); boolean b=b1; void show() { if(b){ System.out.println("You Need Money");; }else{ System.out.println("You Need Knowledge"); }

758 } public static void main(String args[]) { Auto a=new Auto(); a.show(); } } What is the output?

QUESTION 75

interface Do2 { float getRange(int low,int high); } interface DoMore { float getAvg(int a,int b,int c); } abstract class DoAbstract implements Do2,DoMore { } class DoStuff implements Do2 { public float getRange(int x,int y) {

759 return 3.14f; } } interface DoAll extends DoMore { float getAvg(int a,int b,int c,int d) ; } public class B { public static void main(String args[]) { } }

What is the output?

QUESTION 76

abstract class Vehicle { public int speed() { return 0; } } class Car extends Vehicle

760 { public int speed() { return 60; } } class RacerCar extends Car { public int speed() { return 150; } } public class C { public static void main(String args[]) { RacerCar racer=new RacerCar(); Car car=new RacerCar(); Vehicle v=new RacerCar(); System.out.println(racer.speed()+","+car.speed()+","+v.speed()); } }

What is the output?

761 QUESTION 77

public class D { public static void main(String args[]) { Sente a=new Sente(); a.go(); Goban b=new Goban(); b.go(); Stone c=new Stone(); c.go(); } } class Sente implements Go { public void go() { System.out.println("go in Sente"); } } class Goban extends Sente { public void go() { System.out.println("go in Goban");

762 } } class Stone extends Goban implements Go{} interface Go { public void go(); }

What is the output?

QUESTION 78

public class Demo { public static void main(String argts[]) { int x,y,z; x=9; y=0; try{ z=x/y; }catch(ArithmeticException e) { System.out.println("You can not devide an intrger by zero"); System.out.println("so using y++"); y++;

763 z=x/y; } System.out.println("I am executed"); } }

What is the output?

QUESTION 79

public class Demo1 { public static void main(String argts[]) { try{ int len=argts.length; System.out.println("Length ="+len); int con=5/len; int mak[]={222}; mak[42]=1000; }catch(ArithmeticException e) { System.out.println("inside catch block"+e); } catch(ArrayIndexOutOfBoundsException aoe) {

764 System.out.println("Inside Catch Block"+aoe); } } }

What is the output?

QUESTION 80

public class Excep { static void test() { try{ String s=null; System.out.print(s.toString()+" "); }finally{ System.out.print("finally"); } } public static void main(String args[]) { try{ test(); }catch(Exception e) {

765 System.out.print("exception"); } } }

What is the output?

QUESTION 81

public class F { public String doit(int x,int y) { return "a"; } public String doit(int...vals) { return "b"; } public static void main(String args[]) { F ab=new F(); System.out.println(ab.doit(4,5)); }

766 }

What is the output?

QUESTION 82

public class Outer1 { String name; int roll; public class Inner1 { String getName(String n) { name=n; return name; } int getRoll(int r) { roll=r; return roll; } } public static void main(String args[]) { Outer1 o1=new Outer1();

767 Inner1 i1=o1.new Inner1(); System.out.println("Name Is "+i1.getName("Asit")); System.out.println("Roll Number Is "+i1.getRoll(4)); } }

What is the output?

QUESTION 83

public class Test { public enum Dogs{collie, harrier}; public static void main(String args[]) { Dogs mydog=Dogs.collie; switch(mydog) { case collie: System.out.print("Collie "); case harrier: System.out.print("harrier "); } } }

768

What is the output?

QUESTION 84

What is the result of compiling and running the following application ? import java.awt.*; public class Test extends Frame { public Test() { setSize(300,300); setLayout(new GridLayout(1,2)); Panel p1=new Panel(); p1.setLayout(new FlowLayout(FlowLayout.RIGHT)); p1.add(new Button(Hello)); add(p1); Panel p2=new Panel(); p2.setLayout(new FlowLayout(FlowLayout.LEFT)); p2.add(new Button(Goodbye)); add(p2); } public static void main(String args[]) { Test t1=new Test(); t1.setVisible(true) ;

769 } } A. The program crashes by throwing an Exception , because Frames default layout cannot be overridden. B. The program crashes by throwing an Exception , because GridLayout must have at least two rows and two columns. C. The program displays two Button which are just large enough to encompass their labels. The Buttons appear at the top of the Frame. The Hello Button is just to the left of the vertical midline of the Frame and the Goodbye Button is just the right of the vertical midline of the Frame. D. The program displays two large Buttons. The Hello Button occupies the entire left half of the Frame and the Goodbye Button occupies the entire right half of the Frame. E. None of these. QUESTION 85 What will happen if you try to compile and run the following code? public class MyClass { public static void main(String arguments[]) { amethod(arguments); } public void amethod(String[] arguments) { System.out.println(arguments); System.out.println(argumen ts[1]); }

1) error Can't make static reference to void amethod. 2) error method main not correct 3) error array must include parameter

770

4) amethod must be declared with String

QUESTION 86 What will be printed out if this code is run with the following command line? Java myprog good morning public class myprog { public static void main(String argv[]) { System.out.println(argv[2]); } } 1) myprog 2) good 3) morning 4) Exception raised: "java.lang.ArraylndexOutOfBoundsException: 2"

QUESTION 87

class Test1 { public void start() { System.out.println(Java); }

771 } public class Test extends Text1 { public void start() { System.out.println(Sai); } public static void main(String args[]) { ((Test1)new Test()).start(); } } What is the output?

QUESTION 88

interface Task1 { String toString(); } public class Task { public static void main(String args[]) { System.out.println(new Task1() {

772 public String toString() { return "Java"; } });

} } What is the output?

QUESTION 89

public class Check { public static void main(String args[]) { S1 a=new S1(); a.go(); S2 b=new S2(); b.go(); S3 c=new S3(); c.go(); } } interface Go {

773 void go(); } class S1 implements Go { public void go() { System.out.println("Java") } } class S2 extends S1 { public void go() { System.out.println("C"); } } class S3 extends S2 implements Go { } ;

774

What is the output?

QUESTION 90

public class Text { int i=12; public void show(int i) { i+=i; System.out.println(i); } public static void main(String args[]) { Text t=new Text(); t.show(10); } } What is the output?

QUESTION 91

public class Boot1 {

775 int i; String s; public Boot1() { this("Java") ; System.out.println("First"); } public Boot1(String s1) { this(1,"See Java Program"); System.out.println("Second"); } public Boot1(int i1,String s1) { i=i1; s=s1; System.out.println("Third"); } public static void main(String args[]) { Boot1 b=new Boot1(); System.out.println(b.s+"\t"+b.i); } } What is the output?

776 QUESTION 92

public class N1 { public static void main(String args[]) { String str="null"; if(str==null) { System.out.println("null"); } else if(str.length()==0) { System.out.println("zero"); } else{ System.out.println("Java") } } } What is the output? ;

QUESTION 93

public class Loop1 {

777 public static void main(String args[]) { int x=0; int y=10; do{ y--; ++x; }while(x<5); System.out.println(x+"\t"+y); } } What is the output?

QUESTION 94

import java.util.*; public class Col1 { public static Iterator reverse(List l) { Collections.reverse(l) ; return l.iterator(); } public static void main(String r[]) { List l1=new ArrayList();

778 l1.add("1"); l1.add("2"); l1.add("3"); for(Object obj : reverse(l1)) { System.out.print(obj+"\t"); } } } What is the output?

QUESTION 95

import java.util.*; public class Col2 { public static Collection get() { Collection sorted=new LinkedList(); sorted.add("B") ; sorted.add("C") ; sorted.add("A"); return sorted; } public static void main(String args[]) {

779 for(Object obj: get()) { System.out.print(obj+"\t"); } } } What is the output?

QUESTION 96

import java.io.*; class Excep1 { public void process() { System.out.print("A,"); } } public class Excep extends Excep1 { public void process()throws IOException { System.out.print("B,"); throw new IOException(); } public static void main(String arg[])

780 { try{ new Excep().process(); }catch(IOException ie) { System.out.println("Exception"); } } }

What is the output?

QUESTION 97

public class Process { static class A { void process()throws Exception { throw new Exception(); } } static class B extends A { void process()

781 { System.out.println("B") } } public static void main(String args[]) { new B().process(); } } What is the output? ;

QUESTION 98

public class Ex1 { static void test()throws RuntimeException { try{ System.out.print("Test") ;

throw new RuntimeException(); }catch(Exception e) { System.out.println("Caught"); } } public static void main(String args[])

782 { try{ test(); }catch(RuntimeException re) { System.out.println("Runtime "); } System.out.println("End"); } } What is the Output?

QUESTION 99

import java.io.*; class Tree {

} public class Forest implements Serializable { private Tree t=new Tree(); public static void main(String args[]) { Forest f=new Forest(); try{

783 FileOutputStream fos=new FileOutputStream("A.txt"); ObjectOutputStream oos=new ObjectOutputStream(fos) oos.writeObject(f); oos.close(); }catch(Exception e) { e.printStackTrace(); } } } What is the output? ;

QUESTION 100

import java.io.*; public class Serial implements Serializable { public int i,j; static ObjectInputStream ois; static ObjectOutputStream oos; public Serial(int i,int j) { this.i=i; this.j=j; } private void writeObject(ObjectOutputStream oos)throws IOException

784 { this.oos=oos; oos.writeInt(i); oos.writeInt(j); } private void readObject(ObjectInputStream ois)throws IOException,ClassNotFoundException { this.ois=ois; i=ois.readInt(); j=ois.readInt(); System.out.println(i+"\t"+j); } public static void main(String args[])throws Exception { Serial s1=new Serial(12,7); s1.readObject(ois); s1.writeObject(oos); } } What is the output?

You might also like