33131308 Core Java Fundamentals by Rashmi Kanta Das



Comments



Description

1Contents 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 2 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 3 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. 4 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 doesn¶t 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. 5 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. 6 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. 7 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. 8 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 9 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 This illusion is created by the implementation of different CPU scheduling algorithm by the underlying OS. but also in different CPUs. virtual machine makes the end user to feel that different processes are running not only in different platform. Each virtual machine provides different environment or platform to the user. Processes those are executed in Virtual Machine-1 cannot be executed in Virtual Machine-2. According to the platform provided. When different processes are running.16 System that implement the virtual machine. only a particular set of processes can be executed in a particular virtual machine. Implicitly these virtual machine perform appropriate system call for the execution of different processes. . Class loader Sub System: when a java file is compiled class file is generated. JVM consists of following components shown in the diagram. If you have read the class file by notepad or word-pad in a windows system. 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.17 The Java Virtual Machine. For this behavior class . These components are abstract in nature. The task of Class loader sub system is to load the classes & interfaces in the memory. 2nd: Checks the correctness of class file. A boot strap loader & other one is user defined class loader. The class loader sub-system performs its task in sequential way 1st: Loading of class file. allocates required memory to static variables (static variables are explained in class fundamental). It completely depend upon the designer to develop these components. 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. then that class file cannot be executed. In Java Virtual Machine there are two types of loader is available. PC registers or Program Counter registers holds the address of the instruction to be executed next. Java does not provide any technique to the programmer to free the memory that has been allocated by new operator. They are the property of classes rather than the property of objects. Native method stacks: When a java application invokes a native method. The Java virtual machine through the use of new operator allocates memory from the heap for a new object. Static variables are treated as class variable. It shrinks & expands according to the size of the application.18 loader sub-system is responsible. . 4th: transformation of symbolic reference into direct reference. 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. Heap: In java when an object or array is created. Java stacks: Method codes are stored inside method area.out. Once memory is allocated from heap to an object or array. The size of the method area is not fixed. memory is allocated to them from heap. 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. The libraries required for the execution of native methods are available to the Java Virtual Machine through Java Native Interface. 3rd: allocates memory to static variables. rather it uses the native method stack also for the execution of native methods. Byte codes are plat form independent & that¶s why JVM is plat form dependent to make the java programming as platform independent. When method starts execution. 5th: sets default value of all static variables. Execution Engine: Execution engine is there to generate & execute the java byte code. PC registers: It keeps track of the sequence of execution of the program. Example public class hello { public static void main(String ag[]) { System. that application is not going to use Java stack only. All the local variables & the arguments method have taken acquires memory from stack. byte codes are portable. This logical section of memory holds the information about classes & interfaces.println(³Hello. For this purpose java stack is there. Native methods are generally in C/C++ & executed in side native method stack. 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. World!!! Program in JAVA Don¶t get surprised with the name it¶s just our first program in java that we are going to write. You can say that it is a intermediate human readable source & machine readable source. Method Area: it is a logical memory component of JVM. That¶s why it cannot be affected by virus. programmer cannot free the memory. it needs memory because of the local variables & the arguments it has taken. because they take memory from method area. Static variables are otherwise known as class variables. Just like C source codes are portable. World!!!´). How to Construct the FAMOUS Hello. It contains an interpreter & Just In Time Compiler. hello. e. then we can save the file in any name.java file using the javac command. } } Output: Hello To get the output: 1: javac xyz.g. 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.19 } } Output: Hello. 3: java hello Restrictions:. But when we will compile the . Example-2 xyz. e.g. 3:-When the class is declared through no access modifier class name and file name may same or may not .class file.g. javac hello.java class hello { public static void main (String ag []) { System.class.out. Then to get the output we have to run the .java file then the name of the class file generated will be same to the name of the class containing the main method.: java hello note : if we are not declaring the class containing the main method as public .java 2: after the file is saved we have to compile the hello. 2:-When the class is declared through public access modifier class name must be same as the file name.class file using java command.java 2: the class file will be generated in name of hello. Now run it with the java command to get the output.println(³Hello´). To get the output we have to run the program using the name of the .1:-In java top level class is declared either through public or no access modifier.class file will be generated.java 3: After compilation hello. e. . . {} () // [] * \ + . interfaces and reference variables of classes. methods.20 CHAPTER 3: Basic Elements of JAVA 1. Identifiers should not begin with a number and an identifier should not contain these following characters . IDENTIFIERS Identifier are the set of rules for giving the names of the variables of primitive data types. Java is said to be strongly typed language. means you must declare the identifier & initialize it before it is used. ³´ µ¶ # % ! ^. user defined classes. KEYWORDS The table below lists the keywords. When Boolean variable is use as instance or static variable its default vaue is false.0. Case clause preceded with integral constant & enum members. Size of a Boolean variable is 8 bit. It is particularly used to break the normal flow of the program.4.21 Like C/C++ (dollar)$ &(underscore) _ is allowed in java. If the condition is true then the program execute in a normal way otherwise an AssertionError is thrown. Default vale of byte variable when it is used as instance variable or static variable is zero. When ever a condition checking is done in java. We will discuss the meaning and function of most of them during this course. but their body is defined else where. . Its size is 1byte or 8 bit. or reserved words. This keyword was introduced in J2SE 1. Boolean is a primitive data type in java. Abstarct methods only have the declaration. KEYWORDS abstract assert boolean break byte case DESCRIPTION it is used to declare a class or method to be abstract. It can have either true or false value. Boolean value is returned by the condition checking operator. Internally Boolean is represented as integral value in JVM. In place integer constant you can have character constants and bytes since they are auto converted to integer. This keyword is used in the program to check whether a specified condition is true or not. An abstract method does not contain its body. Byte is a primitive data type in java. In interface the methods are by default public & abstract which has to be defined concretely where these interfaces are implemented. Break keyword is used in loops & switch case. as of Java 5. The case keyword is used to create individual cases in a switch statement. 22 catch char class const continue default do This is a component of exception handling mechanism.. Continue statement can be followed with a level name to resume execution from the specified level name. that method cannot be overridden. Solely else has no existance. Its size is 32 bit. JDK 1. It is a primitive data type in java of 64 bit used to store real numbers. Extend key word is used to support inheritance in java A boolean constant. Used for condition checking. Unlike c/c++ it is of 16 bit used to hold the Unicode character. When continue keyword is encountered the control jumps to the condition checking part of do. The default is an optional component of switch case.5 has introduces this key word used to create constant. In an if-else statement else part is optional. it is mandatory that the codes inside the catch block has to be executed. It is a component of exception handling in java. Always follows the try block to catch the exception object thrown from catch block. that class cannot be inherited. When no condition is satisfied default case is executed in switch case. Where used in case of class. do-while loop & the increment part of for loop . Final keyword is used in case of variables to create constants. It is a primitive data type in java. It is used along with if statement following the if block. It always entangled with while o form the do-while loop. Class is the key word through which programmer defines the user defined class template. const keyword is not available to the programmer. Solely do has no existence. This keyword is used to store real numbers. When if part is not executed control jumps to else part. Enum is a class in java. When used in case of methods. whenever try block is executed . double else enum extends false final finally float . It¶s 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. Package keyword is used to declare a package. It is used to store integral values . Static entities are accessed through class name. It is a binary operator used to determine the parent child relationship between two objects. To use the methods declared inside a interface u have to override it in the child class. Used to create an object. It is a access specifier. Used to return control from method along with a value. This keyword is not available to the java programmer. Private variables are only accessed inside the class. It is an access specifier. Static keyword is associate with method and constructor. Protected entities are accessed out side the package through inheritance. It is used for condition checking purpose It is used to inherit multiple number of interfaces It is used to import existing packages. Static variables are treated as class variable. it¶s size is 8 bytes Like abstract method the body of native method is defined elsewhere in foreign language. .23 for Goto If implements import instanceof int It is used to create looping statement. By default all the methods declared are public and abstract. A reference literal value. When an entity inside a class is declared as private it cannot be inherited to it¶s child class. Public variables can be accessed from anywhere. It is a operator. It is of 8 bit size. Package is a collection of class files. It is used to store the natural numbers. It is a access modifier. Primitive data type in java. Packages are the collection of class files. switch Switch case is used for condition checking. Synchronized keyword can be used for block or method. While is a key word in java used for creating a loop. Transient keyword is used for those variables if programmer does not want to strew the variable persistently. Volatile is used along with a variable name. Used throw an exception object. A component of exception handling mechanism of java.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. throws transient true try void volatile Throws keyword Is used along with the method signature. synchronized Synchronized keyword is used to avoid dead lock in thread. throw It is a component of java exception handling mechanism. 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. System clock values are stored in volatile variable. It used by the called method to throw the UnhandledException to the calling method. volatile variable changes their value without informing the JVM. this This keyword is used by object to refer to itself. A boolean constant. while . 4E-45 to +/3. +/-infinity. false false NA . +/-infinity.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.7976931348623157E+308. +/-0. NAN +/-4.4028235E+38.9E-324 to +/1. +/-0.0 64 bits char Unicode character \u0000 16 bits 1 bit used in 32 bit integer boolean true. NaN \u0000 to \uFFFF Default 0 0 0 0 float Real numbers 0.0 32 bits double Real numbers 0. 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.c are operand where as + and = are operators. a=b+c a. how the positive & negative integers are stored in memory. Operators acts upon operand to provide desired output. In C++ operators can be overloaded by the programmer. the number is a negative number. int x=12.b. 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. but that is not possible in java. . How to have two¶s complement form 1: convert the no. When the value of sign bit is one. Negative numbers are stored in the form of two¶s complement & left most bit is treated as sign bit. into binary leaving the negative sign.e. e. Java provides user a large set of operators to the programmers. Int x=-12. There is an important aspect that has to be understood by the reader before getting in to the depth of the operators i. Let¶s have an example to clear the idea. The binary form of 12 is 00000000 00000000 00000000 00001100 2: reverse the polarity of each bit to one¶s complement of the number 11111111 11111111 11111111 11110011 3: add 1 to have the final result that is two¶s complement 11111111 11111111 11111111 11110100 in this format -12 is stored in memory.g. I don¶t think explanations are required. } } Output: -12 .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.print(-x). class Demo { public static void main(String []args) { int x=12. System. Output in each program is simple & straight forward. Programs below will give you a clear picture.out. } } Output: 12 .out. System.print(-+x). System. } } Output: -12 class Demo { public static void main(String[]args) { int x=12.28 class Demo { public static void main(String[]args) { int x=12.out.print(-(-x)).print(+x). } } Output: 12 class Demo { public static void main(String[]args) { int x=12.out. System. In the statement j=i++ 1st value of i i. System.e. 6 is assigned to j & then i is incremented to 7. See another interesting behavior of post fix operation class Demo { public static void main(String args[]){ int i=6.out.println(i).29 The postfix operator: class Demo { public static void main(String args[]) { int i=6. .println(j). Now you can think of why the output is 7 & 6. Incase post fix increment operation use of the variable enjoys the highest priority where as increment is done in second phase. System.out. int j=i++. } } Output: 7 6 Explanation: Variable i is initialized to 6. i=i++. println(i). In this case increment enjoys the highest priority. . System.out. It¶s a rule.println(j).println(i).out.30 System. In the above piece of code since assignment & increment is done over one variable the increment part is rejected because of its lower privilege. int j=++i. So first value of i is incremented to 7 & then it is assigned to j. } } Output 6 Foxed dear!!! See I have already said in post fix operation use of the variable enjoys highest priority. } } Output 7 7 In the above code I have used the pre fix increment operator. Similarly you can try for postfix decrement operator. Prefix operation class Demo { public static void main(String args[]){ int i=6. System.out. If you want to cast a smaller data type to a larger one then implicit casting is done in java. System. In java not only data types are casted but also object is casted. . } } Output 7 Since increment enjoys the highest priority output is straight forward.31 class Demo { public static void main(String args[]){ int i=6.println(i). i=++i.out. In java boolean data type cannot be casted to any data type. The result of cast is a new reference or a value. Cast Operator: (type) Casting is used to convert the value of one type to another. 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 other words casting is used to explicitly convert the value of one type to another. // type casting System.4.println(b). Example: public class Cast1 { public static void main(String args[]) { int i=10. byte b.32 The larger type provides more precision than the smaller type and hence no information is lost when the value is cast.out. See the diagram if the flow of data moves from opposite direction then explicit conversion is required. When the larger type is assign to the smaller type then explicit cast must be required. double d=3. // type casting System.out.println(i). b=(byte)i. long l=1. i=(int)l.println(l).out. } . l=(long)d. // type casting System. println("Super Class").out.out. Example: class Test1 { void show() { System.println("Sub Class").33 } Output:10 1 3 Casting Object Instance of one class can be casted to instance of another class. 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. Restriction of this principle is that class that is being casted must be related by inheritance. } } class Test2 extends Test1 { void display() { System. } . }} Output : -13 Lets have a deeper look.34 } public class Test { public static void main(String args[]) { Test1 t1=new Test1().ClassCastException Bit wise inversion operator: (~) class Demo{ public static void main(String args[]) { int x=12.out.lang.println(~x). t2. Hence the value of x is now . Test2 t2=(Test2)t1. When µ~¶ operator is operated on x then 0 turns to 1 & 1 turns to 0.display(). Binary representation of x is 00000000 00000000 00000000 00001100 . t2.show(). } } Output:The program compiles successfully but at the runtime the program is terminated by Exception in thread ³main´ java. System. other wise compilation error will occour. 11111111 11111111 11111111 11110100 When ~ is operated on these bits then the output will be 0000000 0000000 00000000 00001011.35 11111111 11111111 11111111 11110011 . The left most bit is the sign bit.println(~x). Lets have another example class Demo{ public static void main(String args[]) { int x=-12. Two¶s complement= 1¶s complement+1 To get the final out put 1st determine the one¶s 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. class Demo { . since it is turned to 1 because of µ~¶ operator. Finally add 1 & the output is 10000000 00000000 00000000 00001101 Sign bit says it¶s a negative number & rest other says the final output is -13.out. System. All the negative numbers are stored in memory in the form of two¶s complement. This is the binary form of 11 got it! Boolean complement operator As the name suggests this operator work only for Boolean data type. It will be stored in the memory in two complement form. }} Output: 11 Here the number is a negative number. therefore the number becomes a negative number. Type 2 (Binary Operators) Arithmetic operators + . } } Output: false This operator just inverse the value of Boolean variable.-. System. % Assignment operators = .|= Conditional operator ==.&=.< Bitwise operator &.-=.^=.|.+=.print(!x). /.^ Shift operator >>.>>> instanceof operator Short circuit operator &&.out./=.%=.*=.>=. *.<=.>.|| .36 public static void main(String[]args) { boolean x=true.<<. } } . See the example class Demo { public static void main(String[]args) { int x=12. i=j+i. System. All the operators are simple & their behavior is straight forward. } } Output: 2 Assignment operators An interesting fact about assignment operator: class Thread1 { public static void main(String args[]){ byte i=10. x=x%y.print(x).println(i). A novice programmer may be confused about the %.out. the modulus operator. This operator is used to determine the remainder when a division is performed.37 Arithmetic operators Arithmetic operators are used to evaluate mathematical expressions. System. int y=5.out. byte j=9. x=y. byte j=9.lang.Thread1. But.*=. check the codes below class Thread1 { public static void main(String args[]){ byte i=10. } .&=.|= is over loaded.^=. byte y=5. Similarly other assignment operators like -=./=. System. System.out. Why ? because = operator accepts an integer variable in the left hand side when arithmetic operation is done. i+=j.%=.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte at demo.println(i). class Demo { public static void main(String[]args) { int x. } } Output 19 The reason here is that += is overloaded to return appropriate type.out.38 Output: Exception in thread "main" java. 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.print(x).java:9) see the output is compilation error.main(Thread1. out.Demo. Hence there is no problem in assignment. See the codes below.print(x).39 } Output=5. } } Output: Exception in thread "main" java. if the situation is reversed then compilation error will be generated. But.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 Demo { public static void main(String[]args) { byte x. Right hand side is an integer variable where as left hand side is a byte variable.lang.main(Demo.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte at demo. System. int y=5. x=y. class demo1 { . println("not equall").out.out.out.println("not equall").println("equall").println("not equall"). if(i>j) System. if(i!=j) System. int j= 10.println("equall"). if(i<j) System.out.println("equall"). if(i==j) System. else System.40 public static void main(String ar[]) { int i = 5.out.println("equall"). else System.out. else .out. else System. out. .println("not equall").out.out.println("equall").41 System. if(i>=j) System.println("not equall").out.println("equall"). i=20.out. if(i<=j) System. else System.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. else System. }} . x=x&y. 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. then we will go for codes.out. System. int y= 13. Bitwise and operator ( & ) : class Demo{ public static void main(String args[]) { int x=12.println(x).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. } } Output : .out. x= x & y. Let¶s 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. System. See the truth table above.println(x). 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. int y = 13. The result is the binary form of 12 & so is the output.43 Output : 12 Let¶s see what actually happens. Bitwise OR(|)operator class Demo { public static void main(String[]args) { int x=12. x=x|y. The resultant is the binary form of 13 which is the desired output. . } } Output:13 The bit wise OR (|) operator checks individual bits of two different operand. 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. int y=13.44 4 Here x is a negative number hence it will be stored in the memory in the form of twos complement.out.print(x). System. hence it is a positive number which is 4. hence the right most bit of result is 1 as shown above. 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. So it is -3. x=x|y. 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. Finally add 1 & the output is 10000000 00000000 00000000 00000011.45 Lets have another example class Demo { public static void main(String[]args) { int x=-12. } } Output: -3 Here x is a negative number hence it will be stored in the memory in the form of twos complement. To get the final out put 1st determine the one¶s 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. BITWISE XOR OPERATOR( ^ ): class demo1 { public static void main(String ar[]) { . int y=13.out.print(x). System. System. } } 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. int y = 13.46 int x = 12. x= x ^ y. Let¶s see what happens when one of the operands I positive and the other is negative class demo1 { public static void main(String ar[]) { .out. So the output will only have 1 in it¶s rightmost place all other bits will have the value 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.println(x). println(x). y Below program shows how to swap two variables without using third variable through XOR ( ^ ) operator class demo1 { public static void main(String ar[]) { .which will contain 0.out. } } 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 it¶s two¶s complement form and 13 in it¶s usuall form. int y = 13. x= x ^ y. System. 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 . 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 two¶s complement form which will be -7.47 int x = -12. out.out.out. System.println(" AFTER SWAPPING "). } } 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 .println("value of y = "+y). System. y=x^y.println("value of x = "+x). x=x^y. System.out.println("value of y = "+y). int y = 13 .println("value of x = "+x).out. x=x^y. System. System.48 int x = 12 . out. System. e. } } . class demo1 { public static void main(String ar[]) { int i = 5.out. System.e for a positive number it is filled by 0 and for a negative number it is filled by 1.of shifts represents the number of bits the value of the variable should be shifted. i = -5. Bitwise right shift operator shifts the bits of a number to a specified number of bits towars right preserving the signed bit. i = i >> 2.49 The syntax for bitwise right shift opearator is given below. and no. Variable >> no. i = i >> 2.println(i).g x >> 2 ..println(i). We can say that the empty bits are filled with the value of the highest order bit i.of shifts Here variable represents the variable on which we want to carry out the shift operation. Bitwise Left Shift Operator ( << ) The syntax for bitwise left shift opearator is given below. 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. 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.50 Output : 1 -2 Let¶s see what happens in the above example. What actually happens in memory. Variable << no. But in case of negative numbers there is some difference.of shifts . Now let¶s 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. We all know that negative numbers are stored in memory in two¶s complement form and when we want to see the value it is again converted to two¶s complement and the original value is shown to us. } } Output : 20 -20 . System. System. and no. i = i << 2.out. class demo1 { public static void main(String ar[]) { int i = 5.g x << 2 .out.51 Here variable represents the variable on which we want to carry out the shift operation.println(i). We can say that the empty bits are filled with 0 .. e. Bitwise left shift operator shifts the bits of a number to a specified number of bits towards left preserving the signed bit. i = -5.println(i). i = i << 2.of shifts represents the number of bits the value of the variable should be shifted. We all know that negative numbers are stored in memory in two¶s complement form and when we want to see the value it is again converted to two¶s complement and the original value is shown to us. Variable >>> no. Now let¶s 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 ..52 Let¶s see what happens in the above example. and no.of shifts represents the number of bits the value of the variable should be shifted.g x >>> 2 . Bitwise Unsigned Right Sift Operator ( >>> ) The syntax for bitwise right shift opearator is given below. But in case of negative numbers there is some difference. .of shifts Here variable represents the variable on which we want to carry out the shift operation. 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 . 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. e. out.println(i). System. i = i >>> 4 . class demo1 { public static void main(String ar[]) { int i = 64.println(i).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.64. System.out. i = . What actually happens in memory. We can say that the empty bits are filled with 0 . } } Output : 4 268435452 Let¶s see what happens in the above example. i = i >>> 4 . 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 . Short circuit operators && .|| These operators are used particularly in control statement & loops. We all know that negative numbers are stored in memory in two¶s complement form and when we want to see the value it is again converted to two¶s complement and the original value is shown to us. 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. if both the parts are true then codes with in block followed by is executed. Now let¶s 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. here in case of negative numbers also the empty bits are filled with o. If condition_1 is checked as false then condition_2 is never evaluated. The && operator If(condition_1 && condition_2) { Codes } In && operator both condition_1 & condition_2 is checked. class Demo { . class Demo { public static void main(String[]args) { int x=9. if((++x)==10 && (++y)==1) { } System.out. int y=0.println(x).55 public static void main(String[]args) { int x=9. if(++x==1&& ++y==1) { } . But if first statement is evaluated as false then control never goes to the second one.println(y).out. int y=0. see the if statement both sides are evaluated because of && operator. } } Output: 10 1 In the above piece of code. System. int y=0.println(y). if(++x==10||++y==1) { .out.56 System. class Demo { public static void main(String[]args) { int x=9. 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.println(x). } } Output: 10 0 See the output first condition is evaluated as false there fore control does not go to the second condition. System.out. out. class Demo { public static void main(String[]args) { int x=9. } } Output: .println(x). } } Output: 10 0 See the output. if(++x==1||++y==1) { } System. It clearly shows that since 1st condition is evaluated as true control does not go to the second condition.out. System.println(y).println(y).out.println(x).57 } System. System. int y=0.out. 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. int k=0.println(k). k= (i<k)? 10: 5.58 10 1 Here 1st condition is evaluated as false. . there control goes to the second condition.out. Ternary if-then-else operator ( ?: ) We can say that we can execute a if else statement using ternary if-then-else operator ( ?: ). System.g. System.out. e. k =(i>k)? 10 : 5.println(k). class demo1 { public static void main(String ar[]) { int i = 64. OPERATOR PRECEDENCE TABLE Highest () [] ! ~ .+ ++ -- */% +- << >> >>> < <= > >= .59 } } Output : 10 5 From the above example you can check that the Ternary if-then-else operator ( ?: ) works like if else. .60 == != === !== & ^ | && || ?: = += -= *= /= %= <<= >>= >>>= &= ^= |= Lowest If there are more than one operators in an expression then they are evaluated according to their precedence. . If statement. . d. rather than the statement which return any integral value.. Else.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. which use in construction with an expression. Conditional operator. Then it is called branching. Switch case statement. Unconditional branching: This takes place decision. c.   Conditional branching: It based on particular condition.. if ladder. 3.  if statement . b.. if . else. without any Control statement: 1. 2. Nested if.  If statement ± of java will allow only the statement which return true or false..of Java will take only the logical value true or false. If statement: It's a two-way decision making statement. Java not allow the integer value as condition. (0 as false and any non-zero value as true like C and C++). Simple if. a. else: Syntax: If (test Expression) { statement(s)..62 Simple if: if (expression) { statement(s). } else{ statement(s). } . if Test ? true Statement of body of if false Exit if .. } statement (x). .63 if Test False Block of if Block of else True Exit Nested if . } else { statement(s). else: Syntax: if (test expression) { if(test expression) { statement(s). } } else statement(s)... ladder Syntax: ... if ..64 If True Test If False Test Block 3 Expression True False Block 1 Block 2 Statement x Exit else .. } else if (test expression) { statement(s). statement(x).65 if (test expression) { statement(s). } else statement(s). //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 . case statement:   Java has a build in multi-way design statement called a switch. break.66 switch . 4. Each case must be terminated with a break statement. Typically.  Syntax: switch (expression/variable) { case Val 1: statement(s). user menus. n are constant or constant expression. } Another of the decision making constructs is the switch-case construct which is ideally suited for making multiple choice application. break. Value 1.. 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. in situations where we have one value or expression . it will hang the computer. 3. default: statement(s) break.. Each case must end with a colon. break.      If there is no match with any case specified in the switch case than the default statement is executed. The expression inside the switch case may be an integer or character. Each of these values should be unique in a switch block otherwise. for example. 2. case Val 2: statement(s). like. case Val 3: statement(s). It gives you a faster way to make a decision from a multiple number choice. The switch statement is a multiway ± decision making construct based upon the evaluated expression. 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 N Default Statement x Exit . 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.67 that has to be exactly matched with a list of pre-defined values or options the switch « case is the construct of choice. X from mill clothes and Rs. the statement in the block may be executed any no. Jump statement. Body of the loop. Do loop. y Break.   Control statement. If loop continues forever then it is called as infinite loop.g. e. Of time from 0 ± n times. While loop. : ((X!= A)?((X>A)?(4X+100):(X+30)):(3X+50)). In looping a sequence of statement executed until some condition for termination of the loop is satisfied. Y from handloom clothes Looping:       Entry controlled. A program to show compute the net amount paid by the costumer if he purchased Rs. A program will consist of two parts.68 Conditional operator: Syntax: Exp1? Exp 2:Exp 3. For loop. Exit controlled. y Continue. Looping: The process of repeatedly executing a block of statement is called as looping. . g. while (test expression).while (test expression). Here is an example to show the use of for loop in Java. Contain in the body of the loop.1 Exit Increment/ Decrement .. E.  Exit control: Here test is performing at the end of the body of the loop and before that.  Entry control: Here control condition is test before the start of the loop execution. 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. For loop is the easiest to understand of the loop in Java.. the body is executed unconditionally for the first time. It's generally used when you know. do. before entering the loop. Depending upon the position of the condition or the control statement it may be of two types. Of time. Entry if True Test Expr n False Block . how many time the loop will execute the code. The for loop is execute the block of loop for the fixed no. 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... e..g. It will not execute the block of statement for once also if the specified condition is false..69 The control statement tests certain condition and then directs repeated execution of statement. Entry Block . } This loop is run only when the condition is true other wise the will not be executed.70 Entry Control Loop These are the control statement or control condition tested before the body start of loop execution. While (condition) { statement(S). This loop is never execute the statement if the condition is false.1 If True Test n expr False Exit . The example of this type of loop is: e.g. Test for a specified condition for execution of loop. Incrementing or decrementing the counter. Execution of statement in the loop. while loop (Entry control loop) Initialization If N Test exprn Exit Y Statement(s) . Setting and initialization of a counter. } while (condition). 2. which is not possible in the case of Entry control loop. 3. Step in looping process: 1. do { statement(s).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. 4. while(n<=10) { sum=sum+n.72 while loop: initialization. n=n+1. Here the body of the loop may be executed at all if the condition doesn't satisfy for 1st time.: sum = 0. while (test condition) { Loop body. add = 1.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. Initialization do Body of loop While Y Test Condition Exit N . }    e.out. } System. 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++.g. n++.73 do while loop: initialization do { Body of the loop } while (test condition).    Free from language free from any indentation. } while (n<=10). Example-1 /* find out the sum of the first ten natural no. do{ s=s+n. } . test condition. This loop will executed till the condition is true. : "+s).out.println ("Summation of the fist ten natural no.n=1. System. increment or decrement) { Loop body. */ class Test1 { public static void main (String args[]) { int s=0. Since the test. } } For loop (Entry control loop) Format: for (initialization. The program to show the use of do while loop. condition is provided at bottom of the loop it always executed at least one. } .println("Summation of the fist ten natural no. Both initialization and increment in the for statement. We can setup time delay using null statement using for loop. increment or decrement){ for(initialization. for (int n=1. Nesting of for loop: for(initialization. condition.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.out. Test condition may have any compound relation and testing may not be limited only two loop control variable.n++) { s=s+n. : "+s). */ class Test2 { public static void main(String args[]) { int s=0.} statement(s). } System. The increment section also must have more than one part.n<=10. increment or decrement){ statement(s). condition. We can use expression in the assignment statement of initialization of increment section. } } Additional feature of For loop:       More than one variable can initialize at a time in for loop statement. } } Output:- Example-4 public class Nest2 { public static void main(String args[]) { int j=0.j=9.) System.75 Example-3 public class Nest1 { public static void main(String args[]) { int i=0. do for(int i=0. if(j--<i++) { break.println(i+"\t"+j).out.println(i). } } while (i<5).i++<2.out. do{ i++. System. while(j++<2) } } . 76 Output:- Jumping statement in loop: Break and continue:    e. In case of nesting loop break will exit only a single loop. statement(s). Java permits to jump from one statement to the end or beginning as well as jump out of a loop.i<10. } . } 2. 1. An early exit from a loop can be accomplished using a break statement. if (condition) break. if(condition) break. statement(s). while(condition) { statement(s).g.for(int i=0.i++) { statement(s). In while and do loops continue causes the control to go directly to test the condition and then continue the iteration process. public static void main(String args[]) { z: for(int x=2.x++) { if(x==3)continue.do { statement(s).out.77 3. a label is a valid variable name followed by colon. Example-5 public class Loop { static String o="". If we want to jump outside nested loop or continue at an outer loop we can use label break or label continue statement. } System. In for increment section of for is executed before the test condition is evaluated. o=o+x. } . if(condition) break.  Continue causes the loop to be continue of to the next iteration of the skipping statements. statement(s) }while(condition).println(o).x<7.   Label loops:   In java we can give. if(x==5)break z. t=n.in)). . BufferedReader br=new BufferedReader(new InputStreamReader(System.78 } Output:- Brain Drill Assignment-1 Enter a number and check it is an Armstrong number or not? import java.t=0. s=s+(r*r*r). public class Armstrong { public static void main(String args[])throws Exception { int n.r=0. System.*. n=Integer.out. while(n>0) { r=n%10.s=0.io.println("Enter A Number"). n=n/10.parseInt(br.readLine()). io.out.println("Armstrong Number is "+t).79 } if(t==s) System.*. public class PrimeCheck .println("Not an Armstrong Number "+t). } } Output:- Assignment-2 Enter a number from keyboard and check it is Prime number or not? import java. else System.out. out.80 { public static void main(String args[])throws Exception { int a=0. } b++. BufferedReader br=new BufferedReader(new InputStreamReader(System. System. } } .out.out. a=Integer. while(b<=a) { if(a%b==0) { c=c+1.b=1. }else{ System.c=0.println("Prime Number Is "+a).in)). } if(c==2) { System.println("Enter A Number").println("Not A Prime Numer "+a).readLine()).parseInt(br. public class PrimeCount { public static void main(String args[])throws Exception { int a=1.r. BufferedReader br=new BufferedReader(new InputStreamReader(System. .io.println("Enter a Number").out.81 } Output:- Assignment-3 Enter a number and count how many prime number are present within it? import java.in)). System.*. readLine()).out. while(b<=a) { if(a%b==0) c=c+1.println("Prime Number is "+a). b++.82 r=Integer. a++. } } } Output:- .c=0. } if(c==2) System.parseInt(br. while(a<=r) { int b=1. read(). byte b=(byte)System.*.io.83 Assignment-4 Enter A Character and find out the ASCII value of that number? import java.out.in. System.println("Enter A Character and findout the Ascii value").out.print(b). . public class Ascii { public static void main(String args[])throws Exception { System. .parseInt(br.c.readLine()).84 } } Output:- Assignment-5 Enter A Number and check it is a Binary Number or not? import java. System.t. t=n. public class BinaryCheck { public static void main(String args[])throws Exception { int r.n.io. n=Integer.in)).out.*.println("Enter Binary Number"). BufferedReader br=new BufferedReader(new InputStreamReader(System. c=r=0. n=n/10. } if(c==r) { System. r++. } } } Output:- .println("It is a Binary Number"). }else{ System.85 while(n>0) { if(n%10==0 || n%10==1) c++.out.println ("It Is not a binary number").out. i--. i=n.parseInt(br. System.86 Assignment-6 Enter A Number and Find Out The Factorial? import java.i. BufferedReader br=new BufferedReader(new InputStreamReader(System. n=Integer.*. } System. while(i>0) { f=f*i.out. f=1.println("Enter any Numer"). } } Output:- . public class Factorial { public static void main(String args[])throws Exception { int n.f.in)).println ("Factorial of "+n +" Is "+f) .io.out.readLine()). BufferedReader br=new BufferedReader(new InputStreamReader(System.*.87 Assignment-7 Enter A Number and add each digit of that number? import java.out.out. while(n>0) { r=n%10.in)). public class SumDigit { public static void main(String args[])throws Exception { int r=0. n=n/10.readLine()).io.println("Enter Any Number"). n=Integer. s=s+r.n. System. } System.println("Sum Of Digit Is "+s).s=0.parseInt(br. } . . public class Pyramid1 { public static void main(String args[])throws Exception { int i.88 } Output:- Assignment-8 See the Pyramid and Draw It? import java.j.row.io.*. j++) { System. for(i=1.out. System.out.readLine()).print("\n") } } } .println("Enter The Number Of Rows").print("* ").out.i++) { for(j=1.i<=row. row=Integer. } System.parseInt(br.j<=i. Assignment-9 See The Pyramid and Draw It? .in)).89 BufferedReader br=new BufferedReader(new InputStreamReader(System. out.i<=row.j=0. System. "+t).90 import java.t=0.j<(row-i). "+t).i=0.j++) System.k=0. .out.println("Enter The Number Of Rows"). for(k=0.out.s=0.print(" else System.*. } System.readLine()).parseInt(br.i++) { for(j=0. BufferedReader br=new BufferedReader(new InputStreamReader(System.io. public class Pyramid1 { public static void main(String args[])throws Exception { int row=0.in)).print("\n\n") .out.print(" s=(2*i)-1. row=Integer. "). t=1.out. for(i=1.print(" t++.k<s.k++) { if(t<10) System. row.t=1. row=Integer.j. public class NumberTriangle { public static void main(String args[])throws Exception { int i.out.io. System.parseInt(br. BufferedReader br=new BufferedReader(new InputStreamReader(System.in)).readLine()).*. .println("Enter number of rows").91 } } } Assignment-10 Draw A Number Triangle? import java. 92 for(i=0.i<row.j<=i. }else{ System.j++) { if(t<10) { System. t++.i++) { for(j=0.print("\n").out.out.print(" "+t).print(" "+t). } } } .out. } } System. in)).r.print(" "). BufferedReader br=new BufferedReader(new InputStreamReader(System.x++) .x. r=Integer.p>0.*.93 Assignment-11 Draw A Pascal Triangle? import java.io.println("Pascal's Triangle"). b=1.out. public class Pascal { public static void main(String args[])throws Exception { int b. while(q<r) { for(p=30-3*q.parseInt(br. System.q.p--) System.p.out. q=0. for(x=0.x<=q.readLine()). print(" } System. } } } "+b). .out.94 { if(x==0 || q==0) b=1.out. q++.print("\n") . else b=(b*(q-x+1)/x). System. Error: Unresolved compilation problem: The local variable x may not have been initialized at . } } Above program generates compilation error .main(p. It¶s my sincere advice to the reader to be careful & focused. Therefore it cannot be accessed from out side the method. 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. Class can be defined as a template or an abstract model. In . Local variable Example-1 class p { public static void main (String args [ ]) { int x. System.lang. when object is created memory is allocated. It contains variables and methods which are required to modify the values of the variables belonging to the particular class. It is invisible to outside the method.p.java:5) Above program will result a compilation error. the foundation on which the entire java programming language is developed. x is a local variable.95 CHAPTER 6 : CLASS FUNDAMENTALS I must say this is the most important chapter. The error is given below Exception in thread "main" java.println(x). An object is known as the instance of a class.out. Class templates takes no memory. there is no such thing called garbage value in java. } } Above program generates compilation error.java:5) Output: compilation error. . System. Example-2 class p { public static void main(String args[ ]) { int x=3.println(x). {-/ int x=7. In C/C++ block scope is there inside the function but java doesn¶t define block scope inside method.96 C/C++ an uninitialized local variable takes garbage value. So inside a method we cannot have more than one variable having same name. be careful with this.out. } System. The error is given below Exception in thread "main" java.out.Error: Unresolved compilation problem: Duplicate local variable x at p.main(prj1.lang.println(x). But. //orphan object is created } } .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().*/ } } If an object having no reference is created then it is called orphan object. Through new operator constructor is called to create the object of class p. Example-4 class p { public static void main(String a[ ]) { new p(). /*x is known as reference variable of class p. out. if the programmer define the parameterize constructor & call the default constructor then compile time error occurs.println(³Hello. World!!´). } public static void main(String a[ ]) { p x=new p(). y Constructor does not have any return type.98 Constructor is used to create the object of the corresponding class. y Note: If there is no constructor defined by the programmer then JVM automatically recognize the default constructor but. It¶s a rule OOP. y Constructor cannot use any access modifier. Therefore constructor name must be same as that of the class name. y Constructor is of two types  Parameterize constructor  Non-parameterize or default constructor y Constructor cannot be over ridden but cannot be over loaded. } } Above program generates compilation error. Check it out: Example-5 class p { p(int i) { System. The error is given below . If a method is static then the programmer can call the method without creating the object of the corresponding class. //fun can be called through class name since fun is static p x=new p(). //fun is a static method & main is static therefore main can call fun directly.99 Exception in thread "main" java. If the static variable is not initialized then it takes the default value of the data type. Example-6 class p { public static void main(String args[ ]) { fun(). There is only one copy of the static variable exist for a particular class.Error: Unresolved compilation problem: The constructor prj1() is undefined at p.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. It is directly accessed within a non static method & constructor. . p. 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. static variables can be accessed through class name.fun(). object name & directly with in a static method.main(prj1.lang. } static void fun() { System.out. //fun can also be called through object name.out.fun().println("Hello!"). x. } static void fun() { System.fun1(). } .println("Hello!").100 x. } } Output will be Hello! Hello! Hello! Example 7: class p{ public static void main(String f[ ]) { p x=new p(). x.println("Hie"). It is accessed by its name inside non static method. Instance variables are known as class member variable.fun(). If the instance variable is not initialized then it takes default value of the data type. } } Output will be Hie Hello! Hello! Hello! Instance variable y y y y y y y It is declared outside the method & constructor. // fun is called directly from a non-static method p.fun().out. p x=new p(). //fun is called from non static method through class name. Same named instance variable cannot be in a single class.101 void fun1() { System. It is accessed by the object name inside a static method. //fun is called from a non static method through object name. Size of an object is equal to the size of instance variables present in the corresponding class. fun(). . Here return_type indicates the type of data returned by the method.102 Methods Class consist instance variables and the methods to manipulate those instance variables. then the parameter list will be empty. return keyword is used to return a value from a method. If the method does not returns any value it¶s return type must be void. double height.g. Example-8 // This program uses a method. It can be any legal identifier. e. parameters are the variables that receive the value of the arguments passed to the method when it is called. The return type of a method can be of any valid data type. including the user defined classes. Here value represents the value that is returned from method. class Rectangle { double width. The syntax of declaring a method is return_type method_name ( parameters ). Now we are going to discuss the fundamentals about methods. return value . method_name represents the name of the method. . Adding a simple method to class Now we will see how to a simple method to a class. If the method has no parameters. println("Area is " + area).width =10 . // get area of first rectangle area = rec1.out. } } class RectangleDemo { public static void main(String args[]) { Rectangle rec1 = new Rectangle(). . double area.area().103 // compute and return volume double area() { return width * height . rec1. } } Output : Area is 200. // initialize each rectangle rec1.height = 20.0 In the above example we used a method called area to calculate the area of a Rectangle object. System. } // sets dimensions of the rectangle void setValue(double w. double h) { width = w.104 Adding a Parameterized Method to a Class In addition to defining methods that provide access to data. Example-9 // This program uses a parameterized method. } } class RectangleDemo { public static void main(String args[]) . you can also define methods that are used internally by the class itself. height = h. // compute and return volume double area() { return width * height . double height. class Rectangle { double width. System. when rec1. 10 is copied into parameter w and 20 is copied into h.println("Area is " + area). The area() method is used to calculate the area of each rectangle and then the calculated value is returned.0 Area is 18.setValue(10. double area. 6).area(). is called. // get area of second rectangle area = rec2. the setValue( ) method is used to set the dimensions of each rectangle.out.105 { Rectangle rec1 = new Rectangle(). . Rectangle rec2 = new Rectangle(). } } Output : Area is 200. 20).area(). For example. rec2.println("Area is " + area). 20). System.setValue(3.0 As you can see. // initialize each rectangle rec1.out. Inside setValue( ) the values of w and h are then assigned to width and height respectively.setValue (10. // get area of first rectangle area = rec1. double height . This version is shown here: Example-10: class Rectangle { double width . Lets rework the Rectangle example so that the dimensions of a rectangle are automatically initialized when an object is constructed. Let¶s begin by defining a simple constructor that simply sets the dimensions of each rectangle to the same values. Constructors do not have any return type. replace setValue( ) with a constructor. Rectangle() { System. It is quite obvious not to have return type of constructors. the constructor is automatically called immediately when the object is created. } // compute and return area double area() { return width * height .println("Constructing Rectangle").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. //This is the constructor for Rectangle. To do so. width = 10. Once defined.out. } } class RectangleDemo { public static void main(String args[]) { . height = 10. before the new operator completes. both rec1 and rec2 were initialized by the Rectangle( ) constructor when they were created. This is why the preceding line of code worked in earlier examples of Rectangle class where we have not defined a constructor. System. // get area of first rectangle arae = rec1. // get area of second rectangle arae = rec2. then Java creates a default constructor for the class. Since the constructor gives all rectangles the same dimensions .out.area(). System. Parameterized Constructors . Rectangle rec1 = new Rectangle(). Rectangle rec2 = new Rectangle(). When you do not explicitly define a constructor for a class. } } Output : Constructing Rectangle Constructing Rectangle area is 100. and initialize Rectangle objects Rectangle rec1 = new Rectangle().out. both rec1 and rec2 will have the same area.107 // declare. allocate.println("area is " + arae). The default constructor automatically initializes all instance variables to zero.area(). 10 by 10 . double arae.0 area is 100.println("area is " +arae).0 As you can see. new Rectangle( ) is calling the Rectangle( ) constructor. // This is the constructor for Rectangle.0 area is 18.out.0 . } } public class RectangleDemo { public static void main(String args[]) { // declare.out. double height. and initialize Rectangle objects Rectangle rec1 = new Rectangle(10. Rectangle rec2 = new Rectangle(3. Rectangle(double w. double arae. double h) { width = w. allocate. // get area of second rectangle arae = rec2. 20). Example-11 class Rectangle { double width. // get area of first rectangle arae = rec1.} // compute and return area double area() { return width * height . height = h.The following example defines a parameterized constructor which sets the dimensions of a rectangle as specified by those parameters. 6).108 To set different values for different object of Rectangle class we can use parameterized constructor .println("area is " +arae).println("area is " +arae).area(). System. System.area(). } } Output : area is 200. out. double height. System.println("area is " + area).109 See. System. // this line will result an error // // double area. } // compute and return area double area() { return width * height .out.area(). get area of second rectangle area = rec2. For example Example-12 class Rectangle { double width. and initialize Rectangle objects Rectangle rec1 = new Rectangle(10. get area of first rectangle area = rec1. } } public class RectangleDemo { public static void main(String args[]) { // declare. // This is the constructor for Rectangle. Now width and height of rec1 will contain the values 10 and 20 respectively. Rectangle(double w. Rectangle rec2 = new Rectangle(). making call to the default constructor will show an error. each object is initialized as specified in the parameters to its constructor. the values 10 and 20 are passed to the Rectangle( ) constructor when new creates the object. double h) { width = w. in the following line. height = h. 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. 20). For example.area(). } } .println("Volume is " + area). 20). Rectangle rec1 = new Rectangle(10. allocate. main(RectangleDemo. along with the method name the type of argument method is taking is also necessary. In OOP terminology method over loading is termed as static binding or static polymorphism.lang. but we have not defined the default constructor. } . In case of method overloading method name must be same where as differ in the type and/or number of their parameters. // this line will result an error we make call to the default constructor . JVM invokes the method according to the type and/or number of arguments the method is taking. I hope reader can sense that when a method is invoked. but take different types of arguments.out. So it is the duty of the programmer to define the default constructor whenever he is defining a parameterized constructor. Method overloading is a powerful feature of Java. class Overload { void show() { System.110 Output : Exception in thread "main" java.Error: Unresolved compilation problem: The constructor Rectangle() is undefined at RectangleDemo. then the methods are overloaded.println("No parameters"). Example-13 // method overloading. In case of method overloading methods may have same or different return types. When an overloaded method is invoked. Because in the line Rectangle rec2 = new Rectangle(). only the method name is not sufficient to uniquely determine a method. Overloading Methods When we define two or more methods within the same class that have the same name.java:18) The above program will result in an compilation error. if he is going to use the default constructor. and the fourth takes one double parameter.show(20. The first method takes no parameters.show(20.println("Result of ob.println("a: " + a). // call all versions of test() ob.println("a and b: " + a + " " + b). the second takes one integer parameter. void show(int a) { System. } } class Demo{ public static void main(String args[]) { Overload ob = new Overload(). } // Overload show for two integer parameters.out. } // overload show for a double parameter double show(double a) { System.25). show( ) is overloaded four times. the third takes two integer parameters. System. } } Output: a: 10 a and b: 10 20 double a: 20. result = ob.show(10).25 Result of ob. ob. ob.0625 As we can see.show(20.25): 410.111 // Overload show for one integer parameter. double result. 20).25): " + result). Overloading Constructors We can also overload constructors. int b) { System. return a*a.out.println("double a: " + a).out. void show(int a.show().out. Example-14 .show(10. // get area of rec2 arae = rec2.112 Let see the example below /* Here. */ class Rectangle { double width.area(). double height.0. Rectangle defines three constructors to initialize the dimensions of a rectangle in various ways.0). System. double h) { width = w. } // constructor with no arguments Rectangle() { width = 25.0). double arae. System. // get area of rec1 arae = rec1.println("area of rec1 is " + arae).area(). } } public class Demo { public static void main(String args[]) { // create rectangles using the three constructors Rectangle rec1 = new Rectangle(10. // constructor with two arguments Rectangle(double w.out.println("area of rec3 is " + arae). System. } // compute and return volume double area() { return width * height . 20. height = 25.out. Rectangle rec2 = new Rectangle().out. .area(). // get area of rec3 arae = rec3.println("area of rec2 is " + arae). height = h. Rectangle rec3 = new Rectangle(15. } // constructor with one argument Rectangle(double var) { width = height = var. 113 } } Output : area of rec1 is 200. Before an object is garbage collected garbage collector implicitly calls finalize() method of object class. Example-15 To get a clear view what this refers to.0 area of rec2 is 625. this is always a reference to the object on which the method was invoked.0 Here the required constructors are called according to the type and/or number of arguments.0 area of rec3 is 225. this can be used inside any method to refer to the current object. Rectangle defines three constructors to initialize . 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 . consider the following example /* Here. finalize() method is called just before the object is garbage collected. Java defines the this keyword. 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. width = this.width * this. } // compute and return volume double area() { return this. double height. this. // constructor with two arguments Rectangle(double w.height . } // constructor with one argument Rectangle(double var) { this. } } .height = var.height = h.width = w.114 the dimensions of a rectangle in various ways.width = 25.height = 25. this. double h) { this. */ class Rectangle { double width. } // constructor with no arguments Rectangle() { this. println("area of rec2 is " + arae).here instead of using only the variable name inside the methods and constructors we have used this. Rectangle rec2 = new Rectangle().out. System.115 public class RectangleDemo { public static void main(String args[]) { // create rectangles using the three constructors Rectangle rec1 = new Rectangle(10. // get area of rec2 arae = rec2.out.0 area of rec2 is 625.0 This example operates exactly like the previous example.0).println("area of rec3 is " + arae).out. System. 20.area().0.area().0 area of rec3 is 225. // get area of rec3 arae = rec3.println("area of rec1 is " + arae). System.0). } } Output : area of rec1 is 200. double arae.area(). Rectangle rec3 = new Rectangle(15.variable name to assign values . // get area of rec1 arae = rec1. } In java there are two types of blocks one is Static block and the other one is the non static block. } The nature of static block is that the codes inside it gets executed before the main method is execute i.e. Let¶s have an example to know how it exactly behaves Example-16 class Demo { static { System. this will always refer to the invoking object.out. Syntax is { //Java codes. Static and Non Static block in java Block starts with a µ{¶ and ends with µ}¶. Inside Rectangle( ). this is useful in various contexts. Its syntax is static { //Java codes. then it is known as static block. Static block Whenever a block is declared with the static keyword. } .116 to the variables of the invoking objectof Rectangle class . when you run the class file first the codes within the static block is executed and after that the main method starts execution.println("Samita is in Static block"). int x= a+b.out.println("Value of x= "+x).out. System. } } 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. int b=6.println("Samita is in main method").out.println("Lory is inside static block"). By the use of static block we can execute any code before main is called. } public static void main(String ag[]) { . Example is given below Example-16 class Demo { static { System. int a=5.117 public static void main ( String ag[]) { System. println("Samita is in the second static block").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. } } Output : Lory is in the first Static block Samita is in the second static block . } static{ System. Example-17 public class Demo { static { System.out. } public static void main ( String ag[]) { System.out.out.println("Lory is in the first Static block").println("Lala is in the main method"). Non Static block A block without static key word is known as Non Static block. } } Compile it javac Test.java Class Demo{ static { System. An interesting fact can we execute a java program without main method? Answer is yes!! Foxed folks Example-18 Test. The statements inside the Non Static block gets executed whenever a object of that class is created.exit(0). System.java Run it by java Demo Out put is hello world Actually when we call System.exit(0) in side static block. Static block is executed only once.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 forces the termination of the program. it doesnot matter whether we put the static block above or below main method . Note : Static block cannot be declared inside any method.out. .println(³hello world´). } } .out. Demo a1= new Demo(). public class Demo { { System.out.out. } Demo() { System.println("Samita is in the second Non static block"). Demo a= new Demo().println("Asim is inside the constructor").println("Lory is in the first Non Static block").out. } public static void main ( String ag[]) { System.120 Example-19 Let¶s see a example.println("Lala is in the main method"). } { System. 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 it¶s 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 Z 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 it¶s 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 a 1000 1000 x=1 B 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 i¶s 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 a 1000 1000 x=2 B 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 array¶s 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) mak[1]=2. If the data type is of object reference then size will be 4 bytes.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.out.println(mak[2]). //Array declaration in java mak[0]=1. Creating a programmer-initialized array Example-4 public class Demo { public static void main(String args[]) { int [ ]mak={1. even to an extent you can execute methods on them.2.3}. Accessing the element beyond the size of an array throws a compile time error as shown in the program below. mak[2]=3. mostly of the object class. . you can not create child class or sub class of an array. But. Array actually are objects. } } 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. System. mak[1]=2. 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]. } static void changeIt(int []p) { p[0]=100.out.println(mak[3]).java:13) Creation of reference to a primitive: This is a useful technique to create a reference of primitive data type. System.lang. changeIt(mak). //Array declaration in java mak[0]=1.3}.out. //Array declaration in java mak[0]=10.2.ArrayIndexOutOfBoundsException: 3 at Demo.main(Demo. } . System.println(mak[0]). Array in java provides such technique. mak[2]=3.137 Example-5 public class Demo { public static void main(String args[]) { int [ ]mak={1. } } This program generates an Exception in thread "main" java. 138 } Out put are 100 Due to reference change is reflected. For example. town in fact a reference to an array of integer reference. What exactly town is?.) A closer look at two dimensional array. the following declares a two-dimensional array variable called twoD.c++ you can feel that it is something like pointer to an array of pointers. The declaration Int [][]town. Or int [][]town=new int[3][3] creates a two dimensional array. . This allocates a 4 by 5 array and assigns it to twoD. int twoD[ ][ ] = new int[4][5].(If you are good in c. A closer look at two dimensional array. MULTIDIMENTIONAL ARRAY Two dimension array: To declare a multidimensional array variable. Surprised!!. town=new int[3][3]. specify each additional index using another set of square brackets. [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. .Fine lets check it out programmatically.Actually no of rows represents the number of integer references to which town is pointing.The no.(If you are good in c. it is the number of rows. Or int [][] town=new int[3][3] creates a two dimensional array. town in fact a reference to an array of integer reference.139 The declaration Int [][]town. Really is it happens! Yes 100%.c++ you can feel that it is something like pointer to an array of pointers.ofcolumn represents the length of the integer array towhich each element of the array of references pointing. town=new int[3][3]. Surprised!!.) In the statement town=new int [3][3]. Confused!!! Ok lets have the snap short of memory representation of two dimensional array . What exactly town is?. } } 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.out. . If you check that table reference type variable¶s 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. System.println(town[1]).140 Exampe-7 class demo { Public static void main(String args[]) { Int [][]town=new int[4][].println(town[2]).out. System. System.println(town[0]).out. i++) for(j=0. town[0]=new int [1].j.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][].j++) . town[2]=new int [2]. for(i=0.k=0. town[2]=new int [3].i<3. Int I.j<=I. } } } Output: 0 1 2 3 4 5 Let me explain the program.i++) { for(j=0.print(town[j][j]+´ ³).out. .142 { town[i][j]=k.println( ). } for(i=0. 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 . K++. } System.j<i.i<3.j++) { System.out. 143 town[o] is a reference to integer type. 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 Let¶s begin this section with an example class Demo { int x. town[0]=new int [1]. So through a new operator we allocate memory to it. public static void main(String args[]) . implies that integer array of length one is created in the heap and its starting address 6000 here is allocated to town[0]. arr[1]=new Demo(). if 1000 is the address of the 1st element of the array then next one is 1004 & so on. arr[0]=new Demo(). for(int i=0. arr[0]. When the statement Demo []arr=new Demo[3].x).is executed array of references is created inside stack.println(arr[i]. in Java a variable of class type is not a normal variable. Demo is the class name.x=2. Each element of the array is a reference variable of Demo class. } } 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.x=0. So arr is a reference to an array of references & each element of the array is a reference of class Demo created inside heap. rather it is a reference variable. Finally I have to allocate memory to each element present in the array to access the instance variable. arr[1].144 { Demo []arr=new Demo[3]. & the staring address is stored in arr. so you cannot access instance variable x. arr[2]. What is arr? As I have mentioned in the previous sections.i++) System. This is .out. Remember that size of a reference variable is 4 bytes. This is because whenever a reference variable is created in side heap.i<3. Let me explain the program: Demo [] arr=new Demo[3]. arr[2]=new Demo(). if you try to do that then null pointer exception will arise.x=1. Diagram: arr is created inside stack. its default value is null. Let¶s have a snap shot of memory. println(arr_Ref[2]). Method returning reference to an array See the example below. } int[] funRef() { int [ ]arr1=new int[3].funRef().145 done by calling the constructor of Demo class through new operator. arr1[2]=3. Example-10 class Demo { public static void main(String args[ ]) { Demo x=new p1().out. } } . return arr1. arr1[1]=2. arr1[0]=1. (arr[0]=new Demo(). Just check the signature of the method returning the reference else everything is straight forward. int[ ] arr_Ref=x. System.) Now I can store a value in the instance variable x. public class ArrayTask1 { public static void main(String args[]) { .*.io.146 Brain Drill Assignment-1:Draw this By the help of Array in java? Program:import java. char c[][]=new char[r][]. } for(int k=0.k++) { for(int j=0.k<r.j++) { if(j==0) c[k][j]='*'. } .k<r.println("Enter The Number Of Rows"). int r=Integer. else c[k][j]=' '.k++) { c[k]=new char[k+1]. System.in)). else if(k==(r-1)) c[k][j]='*'.j<=k.out. else if(j==k) c[k][j]='*'.147 try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.parseInt(br.readLine()). for(int k=0. System.j<=k. } }catch(IOException ie) { } } } Assignment-2:Draw This Triangle By Array? .out.k<r.println().148 } for(int k=0.k++) { for(int j=0.out.print(c[k][j]).j++) System. System.io.*.in)) . .out. int r=Integer. public class ArrayTask2 { public static void main(String args[]) { try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.println("Enter Number Of Rows").readLine()).parseInt(br.149 Program:import java. out.out.j++) { System.150 char c[][]=new char[r][r].out.k<r. else c[k][j]='*'.k++) { for(int j=0. } System. } }catch(IOException ie) { } } .k<r.println().j++) { if(j<k) c[k][j]=' '.print(c[k][j]).k++) { for(int j=0.j<r.j<r. } } System. for(int k=0.println("See The Structure"). for(int k=0. length. for(j=0.readLine()).in)). public class ArrSortA { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.parseInt(br. ar[i]=temp.temp.j.151 } Assignment-3:Enter four integer value from keyboard and Sort the elements of array in Ascending order? import java. int ar[]=new int[4].println("Enter The Array Elements").i<ar. System.j<ar.i++) { ar[i]=Integer. for(i=0.j++) { if(ar[i]<ar[j]) { temp=ar[j].io.*.out. ar[j]=ar[i]. int i=0.length. } . i<ar.out.i++) { System.println(ar[i]+"\n"). } } } Output: Assignment-4:Enter 5 integer through an array and find out Smallest Number? .length.152 } } for(i=0. System.i<5. int ar[]=new int[5].out. } } } System.j.*. BufferedReader br=new BufferedReader(new InputStreamReader(System.println("Enter The Array Elements").temp=0.println("Smallest No is "+temp) } . ar[j]=ar[i].in)). for(j=0.i++) { ar[i]=Integer.j++) { if(ar[i]<ar[j]) { temp=ar[j].readLine()).j<5.io. public class ArrSmall { public static void main(String args[])throws Exception { int i.out.153 import java. for(i=0.parseInt(br. . temp=ar[i]. *. .i=0.j.out. int a[]=new int[20].println("Enter any number"). System.io. BufferedReader br=new BufferedReader(new InputStreamReader(System.154 } Output: Assignment-5:Enter A Number and find out the Binary Value? import java. public class Binary { public static void main(String args[])throws Exception { int num.k.in)). int b[]=new int[20]. 155 num=Integer.print("\n\n").print(b[j]). k--.out.j<i.j++) { b[j]=a[k]. } } } Output: . while(num>0) { a[i]=num%2. } k=i-1. for(j=0.readLine()).parseInt(br. System. num=num/2. i++.out. System. *.q. while(num>0) { . System. BufferedReader br=new BufferedReader(new InputStreamReader(System. int b[]=new int[10].println("Enter Any Number").156 Assignment-6:Enter a decimal and find out the octal value? import java.readLine()).o.io. num=Integer. public class DecimalOctal { public static void main(String args[])throws Exception { int r. o=0.out.num. int a[]=new int[10].in)).parseInt(br. num=num/8. r++.out.q++) . for(q=0. } } r=0. } System.q>=0.q--) { b[r]=a[q]. o++.println("Octal Number Is ") . for(q=o-1. o++.q<r.157 if(num<8) { a[o]=num. break. }else{ a[o]=num%8. print(b[q]). } } } Output: .158 { System.out. The general syntax is class X { //Codes } class Y extends X { //Codes } Class baseClass extends superClass{ //Codes } should be the syntax. let¶s begin with a short example. . you can create a general class that defines traits common to a set of related items. each adding those things that are unique to it. This class can then be inherited by other. Java uses extends keyword to support inheritance. Restriction: if the super class members are private. Using inheritance. 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). To inherit a class. In the terminology of Java.159 CHAPTER 9 : Inheritance Inheritance is one of the fundamental concepts of object oriented programming. more specific classes. 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. To see how. then child class cannot copy them & another thing JAVA does not support multiple inheritances. you simply incorporate the definition of one class into another by using the extends keyword. Therefore it can be inherited with in a package.out.show().println("Hello. Multi-level inheritance. By using extend keyword show() method is copied to class Y. It has default access specifier.println("Hello. Hence any object of class Y can invoke show() method. a. In side main() method object of child class is created but the show() method of parent class is invoked. } } . } } class Y extends X { } class Demo { public static void main(String argts[]) { Y a=new Y(). show() method is not a member of Y. Java I am inherited"). Java").out. In case of inheritance child class copies members of the parent class those are not private.160 class X{ void show() { System. 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. } } Output: Hello. to it self. show() method belongs to class X. class X { void show() { System. In this way inheritance facilitates code reusability. Through the use of super keyword programmer can access the members of super class. then to access the super class instance variable super keyword is used only the inside sub class.out.161 class Y extends X { } class Z extends Y { Z() { super.println(super. } } Output: Hello. } class Y extends X { int i=90.println(i). Java does not allow the use of super keyword inside static method & static block.i).show(). Hence the object of class Z can invoke show() method which is written in class X. 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. super Keyword super is a keyword.out. Java Hello. class X{ int i=9. Java Here show() method of X is copied to class Y & from class Y to class Z. System. void showSuper() { System. } } . Y is derived from X & also has the instance variable i.i programmer can access the super class instance variables.162 class Demo { public static void main(String args[]) { Y a=new Y(). The first statement inside the showSuper() method prints the value of i that belongs to child class Y. } } class Y extends X { Y() { super(). other wise it will give compile time error. Inside the child class Y showSuper() is a method. Example: class X { X() { System.println("Parent class"). Restriction: y super must be the first statement in side the child class constructor.out. a.showSuper(). Through the use of super. y Java uses super keyword for explicitly calling the super class constructor within child class constructor. To access the parent class i. } } Output: 90 9 X is the base class which has the instance variable i. super keyword is used. . } public static void main(String argts[]) { Demo d=new Demo(3). System.out. } Demo(int i) { this().out.println("Inside parameterized constructor").out. } } Output: Parent class Child class y Just like super.println("Inside Default constructor"). } } class Demo extends Y { public static void main(String argts[]) { Y d=new Y().163 System. 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. } } .println("Child class"). } } class Y extends X { } class Demo { public static void main(String argts[]) { Y d=new Y().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.println("Inside super class parameterized constructor"). } X(int i) { System. } } 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.out.out. class X { X() { System. . at that time the super class default constructor is implicitly invoked.println("Inside super class default constructor"). 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. That¶s 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. System. } } class Y extends X { int i. public abstract void display().i).println("Finally I got Life!!"). But on the other hand if any of the method of a class is abstract then the class has to be abstract. public void display() { System. 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.out. } } class Demo { public static void main(String argts[]) { X a=new Y(). } } . Abstract methods are declared inside the abstract class but defined in their child class. a. abstract class X { int i=10.println(a. { System.out.display().println("Hello").out. } . } Y() { super().out. abstract class X { public abstract void fun(). When a class is declared with final keyword. X() { System. There fore abstract class can not use final keyword.out.fun(). } } class Y extends X { public void fun() { System. Although you can not call the constructor of abstract class. Constructors can not be abstract. } } class Demo { public static void main(String argts[]) { X a=new Y().println("X constructor"). Using super keyword inside the constructor of child class you can invoke the constructor of abstract parent class. that class can not be inherited. But abstract class has to be inherited in order to define its abstract methods.181 Output: Hello Finally I got Life!! 10 final & abstract behave complement to each other. a.print("Hello"). still you can declare the constructor of the abstract class. g. Interface declaration is same as class declaration.182 } Output: X constructor Hello Interface First of all interface is a keyword. Interface cannot be instantiated. As the methods are public & abstract by default therefore those methods has to be overridden in their corresponding child class. } . Example:-1 interface in { String toString(). In interface all the methods are public & abstract by default. e. static & final. interface supports multiple inheritance. The methods belonging to an interface are looked up at runtime. 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. In interface variables are implicitly public. public interface X { } Interface X { } Interfaces are implicitly abstract in nature. out. } }). } public class A implements Declare { . } } Output:test Example-2 interface Declare { public static final int i=3.183 public class Test implements in { public static void main(String a[]) { System. void doStuff(int i1).println(new in() { public String toString() { return "test". } } Output:Output is 16 Final keyword: Final keyword is used in class.184 public static void main(String args[]) { int x=5. If the class is declared as final the then the class cannot be inherited. class X { Final void show() { //code here } } .doStuff(++x). } public void doStuff(int s) { s+=i + ++s.println("Output Is "+s). Ex. Wrapper classes are treated as final so these classes have no child class. System. String.out. new A(). In technical term final method cannot be override. method and variable. Ex. class X extends String //error as String is a final class If the method is declared as final then method cannot be override. Math. show(). . If the variable is declared as final then the value of final variable cannot be changed or modified. } } Error: This program generates a compile time error that µi¶ is not initialized. In technical term we cannot assign the value to final variable. Ex. As i is a final variable .println(i). final int i=10. public class X { final int i. void show() { i++. ab. Ex. void show() { System. i must be initialized.out. } public static void main(String args[]) { X ab=new X().185 class Y extend X { void show() { //code here } } //error final method cannot be override. //Error } final variable must be initialized. More readable. Nested class can be declared by using any access modifier. no access or public member of enclosing class. Advantage of Using Inner / Nested class:1. Increased encapsulation 3.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. In java outer class or enclosing class is declared by using public or no access modifier. For Example:class X { static class Y { } . protected. Logical grouping of classes 2. maintainable code Static Inner Class If the Inner class uses the static modifier then the Inner class is treated as static inner class. Nested class is able to access private. 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. Static Inner class static member access the non-static member of the Inner class through the instance of static Inner Class. } static int getRoll(int r) . Static Inner class access the static member of outer or enclosing class through the outer class name or directly.187 } Here Y class is treated as static inner class. private String getName(String n) { name=n. static int roll. Example-1:public class Inner1 { String name. Static Inner Class supports inheritance. Static Inner class¶s non-static member access the non-static member of the inner class directly. Static Inner Class¶s Non-static member access the static member of the inner class through the Inner class name or directly. Static Inner class static member access the static member of the Inner Class through the name of the static inner class or directly. 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. return name. Static Inner class access the non-static member of the outer or enclosing class through the instance or object of the outer class. println("Age Is "+age+"\t"+"Address Is "+add). return roll.println("Roll Number Is "+Inner1.getName("Sai")). static String add="Cuttack".getRoll(1)). t1.out.188 { roll=r.println("Name Is "+i1. } static class Test { int age=10. System. System. } } Output: . System.out.out. } } public static void main(String args[]) { Test t1=new Test(). void display() { Inner1 i1=new Inner1().display(). . static int roll.189 Example-2 public class Inner2 { String name. return name. return roll. } static class Test { int age=10. } static int getRoll(int r) { roll=r. private String getName(String n) { name=n. static String add="Cuttack". add).display(). } } Output: Example-3 public class Inner3 { String name.getName("Sai")).190 static void display() { Inner2 i1=new Inner2(). System.out.out.println("Age Is "+t. Test t=new Test(). System.println("Name Is "+i1. } } public static void main(String args[]) { Test.out. .println("Roll Number Is "+Inner1. System.getRoll(1)).age+"\t"+"Address Is "+Test. i3. return roll. private static class Test1 { int roll.age=a. } int getAge(int a) { Inner3.name. String getName(String n) { Inner3 i3=new Inner3(). return Inner3. } . } } protected static class Test2 extends Test1 { int getRoll(int r) { roll=r.191 static String add.age. return i3.name=n. static int age. return Inner3.println("Address Is "+t.add.println("Age Is "+t. System.out.println("Roll Number Is "+t.add=a. System. } } public static void main(String args[]) { Test2 t=new Test2().getRoll(1)).getName("Sai")).out.out.192 String getAddress(String a) { Inner3.println("Name Is "+t. System.getAge(10)).out. System.getAddress("Cuttack")). } } Output: . We declare non-static inner class by using any access modifier. 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. static int age. private String getName(String n) . 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. y y Example-4 public class Inner4 { String name. Within non-static inner class we cannot declare any static member This inner class is very popularly used. Non-static inner class is popularly known as Inner class.193 Non-static Inner Class:Class declared within another class without using static modifier is treated as non-static Inner class. int getRoll(int r) { roll=r. return age. return roll.194 { name=n. } String getAddress(String s) { add=s. } static int getAge(int a) { age=a. } private class Test1 { int roll. return name. String add. } void display() . return add. System.show().195 { System. System.out.println("Name Is "+getName("Sai")).getAge(10)). } void show() { Test1 t1=new Test1().println("Roll Number Is "+getRoll(1)). System.out.out.println("Age Is "+Inner4. t1.display().out. } } Output: . t1. } } public static void main(String args[]) { Inner4 t1=new Inner4().println("Address Is "+getAddress("Cuttack")). System. return name. int roll.new Inner1(). Inner1 i1=o1. } } public static void main(String args[]) { Outer1 o1=new Outer1().196 Example-5 public class Outer1 { String name.getRoll(4)).println("Roll Number Is "+i1. return roll.out. System. . public class Inner1 { String getName(String n) { name=n. } int getRoll(int r) { roll=r.println("Name Is "+i1.getName("Asit")).out. 197 } } Local Inner Class:Class declared within the method is treated as local inner class. Local Inner class access the private member of the outer class . Key Points of Non-Static Inner Class:y y Local inner class is declared through no-access modifier but not declared through public. class X { void show() { class Y { } } } Here class Y is treated as Local inner class as it is declared within the method show. private and protected access modifier. protected static int age. void go(final int a. private static int roll. class Inner { String getName(String n) { name=n. Local inner class only accesses the final member of the method where the class is declared. Example-6 public class Local1 { String name. String add. . Programmer creates the object of local inner class within the method where the class is declared.int b) { final int x=a+b. Local inner class non-static member directly access the nonstatic 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. int y=a-b. println("Name Is "+getName("Sai")). return age.199 return name. } void show() { System. } int getAge(int a) { age=a. . return roll. } int getRoll(int r) { roll=r.out. return add. } String getAddress(String s) { add=s. l1.println("Value Of B Is "+b).println("Value Of X Is "+x).out. } } Inner i1=new Inner().println("Value Of A Is "+a). System. i1.out.out. System.go(10. System.show().2).out.out. } public static void main(String args[]) { Local1 l1=new Local1().println("Roll Number Is "+getRoll(1)). } void display() { System. } } .println("Age Is "+getAge(10)).println("Address Is "+getAddress("Cuttack")). //System.display().200 System. i1.out. 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. .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. things are completely different in case of checked exception. Briefly here is how they work.202 CHAPTER 11: Exception Handling Introduction Exceptions are abnormal behavior of program during its execution state. Exceptions that can be generated in a java programs are     If the array index cross the range. If the programmer does not handle the checked exception then java compiler detects them & program terminate at the compilation stage. When the programmer manually handles the exception. 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. You can say that exceptions are runtime error. Exception occurs only at the execution state of the program.throws & finally. java programmer can create programs having unchecked exceptions. They are simply errors. Programmer can not ignore the checked exception. But. Programming codes that you want to monitor for exceptions are embedded inside this block. he has to use throw keyword.throw. 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. The general syntax of exception handling block is try{ //Block of code to monitor for errors } .catch. If an exception is generated inside try block then it has to be thrown. When an exception is thrown out of a method throws keyword has to be used. In this case catch follows the try block in order to handle the exception. Since unchecked exceptions are generated during the execution of the program. Compile time errors never come under exception. If some piece of code that is necessary to be executed after try block then those has to be written in side finally block. In java exception handling is done by 5 keywords: try. The file you try to open may not exist. If the number divide by zero. .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 } //«. catch. throws. finally{ //Codes that has to be executed must } In java Exception is handled by five keywords try. finally. throw. ClassCastException. IllegalStateException. ArrayStoreException. . IndexOutOfBoundsException. & its child classes all Unchecked Exception: Error. IllegalThreadStateException.204 In java Exception is of two types Checked and Unchecked Exception.RuntimeException & its child classes all are treated as unchecked exception. IllegalMonitorStateException. Checked exceptions: ClassNotFoundException. Types of Exception:         ArithmeticException. ArrayIndexOutOfBoundsException. IllegalArgumentException. IOException are checked exceptions. NoSuchMethodException. Throwable is the super class of Exception and Error. ClassNotFoundException. CloneNotSupportedException. UnsupportedOperationException. Types of Error:     AWTError VirtualMachineError OutOfMemoryError StackOverFlowError AssertionError Throwable Class Throwable is a class present in java. public Throwable(String mess) this constructor creates a Throawble object with a the message µmess¶ supplied by the programmer embedded within the object.205             NegativeArraySizeException.lang package. NumberFormatException. SecurityException. Constructors of Throwable class public Throwable() this constructor creates a Throawble object with a null information embedded within the object. NullPointerException. NoSuchFieldException. InstantiationException. public Throwable(String message. Throwable reason) . StringIndexOutOfBounds. IllegalAccessException. If the programmer is able to caught the exception. Finally block: In java the try block is executed means the finally block must be executed. 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. then the program is terminated. Finally block is executed in java to give control to the programmer. The catch block caught the exception that will arise within the try block. catch & finally block: try block: All the exception generating codes are embedded within try block. public Throwable(Throwable reason) this constructor creates a Throawble object with a the reason behind the exception by Throwable object µrason¶. Without try block finally block cannot be executed. first catch block is executed & then finally block is executed. then the programmer is able to handle the exception. But in the other hand if the programmer is not able to caught the exception. In java one try block can have multiple catch block.206 this constructor creates a Throawble object with a the message µmess¶ supplied & the reason behind the exception through the Throwable object µreason¶ . . It is used in method definition. The matching is done by JVM using instanceof operator. On the other hand if the catch if the catch parameter is not matched. 2: Prevents the automatic termination of the program. If the catch parameter matched with the exception. with in the finally block you can use another try catch block. catch block: catch block is treated as exception handler. Exception handling provides two benefits 1: Allows to fix the bug. finally block is executed & program terminates. As the finally block must be executed. Use of try. Every try block must be followed by a catch block. Java supports nested try block. Either the programmer caught the exception or not finally block must be executed. At that instant of time JVM generates unchecked exception object & throws it.z. If programmer manually does not handle the exception then JVM handle them by default handler.y=0. This terminates the execution at the runtime.207 How JVM handles an exception Now it is important for the beginners to understand what will happen if you don¶t handle the exception. z=x/y. When the exception is thrown. } } Output:- This program is compiled successfully. In the given program there is no exception handler provided by the programmer so the default exception handler of JVM caught the exception.out. there must have some technique to handle or mange it by the use of catch block. JVM detects the attempt to divide by zero. System. The default handler throws a message to the screen as . During its execution.println(³I am not executed´). Let me explain it through an example Example-1 public class Demo { public static void main(String argts[]) { int x=12. Use of try & catch block Let me use the try. When such run time exception occurs.java:7). .out.println("You can not devide an intrger by zero"). x=9. Actually when exception occurs & it is handled by JVM. 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. If you see the message carefully it clearly shows exception occurs in demo package¶s Demo class¶s main method at line no: 7. Example-2 public class Demo { public static void main(String argts[]) { int x.ArithmeticException: / by zero at Demo.y. y=0.out.z. catch tool for the previous program.main(Demo. try{ z=x/y. System.lang.println("so using y++"). }catch(ArithmeticException e) { System.208 Exception in thread "main" java. it leads to abnormal termination of the program. JVM shows the stack trace message from the point where exception has been occurred. x=9. } System. A catch block immediately follows the try block to catch the thrown exception. . When an integer is divided by zero java generates ArithmeticException. y=0. The catch block catches the exception by the ArithmeticException object e. } } Output:- In the first case there no exception handler provided by the programmer.println("I am executed"). 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.out. To prevent the abnormal termination of the program. So the program does not terminate abnormally. z=x/y. The program below illustrates the above fact.z.y.println("I am not Executed"). Example-3 class Demo { public static void main(String argts[]) { int x.209 y++. try{ z=x/y. simply put the codes to be monitored inside the try block.out. therefore the program terminates abnormally. But. System. out. 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.println("Exception is handled"). }catch(ArithmeticException e) { System.210 }catch(ArithmeticException e) { System.println("inside catch block"+e).ArithmeticException: / by zero Multiple catch blocks .lang. try{ x=x/0. } } } Output: Exception is handled A try block holds a piece of Exception arising codes and its catch block treats as an Exception handler. Example-4 public class Demo { public static void main(String argts[]) { int x=9. Through this method returns a string where it describes about the type of 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.out. } } Output: inside catch block java. since the int array mak has a length of 1. int con=5/len. mak[42]=1000. yet the program attempts to assign a value to mak[42].println("inside catch block"+e).println(³Inside Catch Block´+aoe). System. } } } Output:- This program will generate an ArithmeticException if in the command line the programmer not passes any arguments.211 In some special case one try block can have multiple catch block.length. int mak[]={222}. To handle such situations multiple catch blocks are required. Example-5 public class Demo { public static void main(String argts[]) { try{ int len=argts.out. When multiple Exception is generated. 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. each catch statement inspected in order.println(³Length=´+len).out.out. }catch(ArithmeticException e) { System. In other words more than one Exception can be generated within a single line of code. . so the length is equal to zero. so the programmer required multiple catch statement for one try block. } catch(ArrayIndexOutOfBoundsException aoe) { System. length.212 Parent class reference variable can hold the object of child class. Example-6 import java.readLine()). throw new New(). try{ System. So the exception thrown by a try block can be caught by its parent class reference.println("Caught"). }catch(ArithmeticException ae) { ae.println("Enter A Number").in)). } } } Use of throw statement So far we have caught the exceptions generated by JVM.parseInt(br.*.io. Java provides .out. class New extends Exception { } public class Multi { public static void main(String args[])throws IOException { int a=10.out. int i=Integer. } catch(NumberFormatException ne) { System.println(ne.getMessage()).out. It is a restriction otherwise it generates compile time error. When one try block having multiple catch statement then Exception of sub class must placed before Exception of super class.println(a/b) . } catch(Exception n) { System.out. System. BufferedReader br=new BufferedReader (new InputStreamReader(System. int b=args.printStackTrace(). The execution stops when JVM encounters the throw statement & controls jumps to the catch block. } } public class Demo { public static void main(String argts[]) . System. } } } Output: inside catch block Example-8 class X extends RuntimeException { void show() { throw new X().println("inside catch block").out.213 support to generate exception manually by the programmer just by instantiating the appropriate exception class. try{ throw a. The codes below the throw statement are never going to be executed.out. }catch(ArithmeticException e) { System. The general form will be throw instance_of_Throwable_or_its_child_class. You have to use the throw statement to thyrow the exception.println("inside try block"). You can throw the object of Throwable or the object of the child class of Throwable. Example-7 public class Demo { public static void main(String argts[]) { ArithmeticException a=new ArithmeticException(). or until all of the nested try blocks are exhausted. try{ a. This process will continue unless until one of the catch statements matched.println("inside catch block"). then stack is unwound and the next try statement¶s catch block are inspected to handle the Exception of the Inner try block. This class has show method which has a statement throw new X(). When you want to call the method. If no catch statement matches. } } } Output: inside catch block Explanation: this program represents another way to generate exception inside a method. Nested try block: Java supports nested try block. Nested try block means one try block defined within another try block. Rests of the things are straight forward. when the try statement executed each and every time. then the programmer must specify throws keyword so that the caller of the method can guard it¶s code against that exception.214 { X a=new X(). it should be inside try block.show(). The context of the Exception is stored in stack. 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 . If the inner try block has no catch block or has a catch block that is not able to handle the Exception. The throws keyword If a method generate an Exception and not handle the exception by catch block.out. class X extends the RuntimeException.. }catch(RuntimeException e) { System. then at the runtime the Java run-time system will handle the Exception. } } } Output:- Example-10 public class Excep2 { public static void main(String afg[]) { try{ show().215 unchecked exception then the programmer should not throw them out by using throws keyword.println("Finished"). }catch(Exception e) { System.out. Example-9 public class Excep1 { public static void main(String args[]) { try{ amethod(). }finally{ System.println("Finally") . } public static void amethod()throws Exception { try{ throw new Exception().println("Exception"). } System.out. .out. println("C").216 System. Catch statement work like a method statement. which is reference to the exception object thrown by try block. the remaining statement in the try block is skipped and exception is jumped to catch block. } finally{ System.out. }catch(RuntimeException re) { System.println("D"). } System. } } Output:-  If any statement generates exception. 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. Both try and catch block have more than one statement. Every try block must be followed by at least one catch block.out.println("E"). } public static void show() { throw new RuntimeException().println("A").out.out. Catch statement is passed a single parameter. } catch(Exception e) { System.      .println("B").out. *. } } public class User { public int x.println("Enter A Number in between 1-10"). System. String line. Example-11 import java.parseInt(line). The advantage of creating such an exception class is that.io. It also possible to set any condition or value to a variable and generate user defined exception. void getInt() { try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.out. if(x==5) { .readLine())!=null) { x=Integer. while((line=br.in)) . final int k=5. Excep1(int b) { a=b. } public String toString() { return "Excep1[" +a+ "]" . according to situations user generate user defined exception. class Excep1 extends Exception { private int a.217 User-defined Exception Customized exceptions are necessary to handle abnormal conditions of applications created by the user. println("Generated Exception : "+e1).println("Try Again") .println("Please Enter A Number"). }else System. } }catch(Excep1 e1) { System. } catch(IOException ie) { } } public static void main(String args[]) { User u=new User(). continue.out. u.out.println("Congrats You Will Generate an Exception"). } } Output:- Exception Restriction:- . } catch(NumberFormatException ne) { System.218 System.out.out.getInt(). throw new Excep1(x). 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. we can throw only the exceptions that have been specified in the base-class method. including exceptions. It is useful to realize that. the exception specifications are not part of the type of a method. although exception specifications are enforced by the compiler during inheritance.219 When we override a method. . Packages contain classes and interfaces in a hierarchical order and are imported when the programmer wants to access classes or interface within it. When class files are created. Package contains a set of classes in order to ensure that class names are unique. At the runtime the java interpreter search the . they must be placed in a directory hierarchy that reflects the package name. Advantage:     Classes contained in the packages of other program can be easily reused. Package name must be same as the directory name. In case of creating a user defined package ensure that the root directory of the package is included in the classpath variable.class files in the path specified in the classpath environmental variable. Classpath variable: When a class is defined without package declaration. Packages provide a way to hide classes. 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. Two classes in two different packages can have the same name. then it is defined that the class is included in java¶s default package. Keyword package followed by package name.220 Chapter-12 Package It consists of classes and interfaces grouped together according to functionality. Packages provide a way for separating design from coding. 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. Package is the container for classes or interfaces. 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 . import java. 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. domain name as used as prefix to package name.util.221 package p1. Access protection: Java having four different types of access specifiers namely private. protected and public. no access. To ensure uniqueness in naming packages. import p1. Every package name must be unique. to best use of package.*. Naming convention:    Package begins with lower case letter. import is a keyword in java that is used to access the class files of the user defined package and pre defined package.*. If the members are public then the data is freely access within the package and outside the package either through inheritance or not.222 If the members are private then the data is only accessed within the class but it is not accessed outside the class.java . Program:y y Create a directory named as pack Open a file Name. 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 no access then the data is accessed within the class and accessed within the same package either the class is inherited or not. public String getAddress(String a) { .223 package pack. class Name { String n.Roll. protected int getRoll(int r) { roll=r.java package pack.java package pack.setName("Amit")). System. y In the same package open Roll. y y Inside the pack directory creates a subdirectory named as subpack Inside the subpack directory creates a file named as Address.out. } } In Name class the class. Name n1=new Name(). return n.println("Name Is "+n1. public class Address extends Roll { public String address. } } As the Roll class members are protected then it accessed outside the package through inheritance. method and variable are declared without using any access specifier that means the members are only accessed within the same package ³pack´. String setName(String name) { n=name. return roll. public class Roll { protected int roll. import pack.subpack. out.out.java import pack. y In c:\java open PackDemo.java. Here c:\java is the root directory.getAddress("Nayabazar.getRoll(7)). } } In this class the members are public so it is freely access within the package and outside the package either through inheritance or not.println("Address Is "+a1. In the root directory write the main application PackDemo.224 address=a. System. Address a1=new Address().subpack. System. } } Output: .Address. public class PackDemo { public static void main(String args[]) { Address a1=new Address(). Cuttack")). return address.println("Roll Number Is "+a1. Text and HTML class files that provides help to the user. JAR is a platform independent file format that aggregates many files into single unit.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. Programmer creates java archive file format for compress number of class files and improve the download performance of applet and application. Audio and video clips. Provide verbose output Extract files from the archive. Tabulate the content of the archive. These commands are performed in java by using jar tool. In JAR programmer can store not only . Option C f m Description Create an Archive The first element in files is the name of the archive to be created. In java some commands are used to perform main operations for the jar file. Static Images. Configuration data. JAR stands for the Java Archive. The following files may be packed into one JAR file: y y y y y y The Beans Any Supporting class files. The second element in the file is the name of the manifest file. Don¶t use Compression Don¶t create a manifest file T V X O M .class files but store different types of file. This file format helps the programmer to reduce the size of the file and collect many file in one by compressing these files. System.io. int l1=first.i<l1-1.out. System. int l2=second.c<128. int count1=0.println("Enter Second String"). for(int c=0. String first=br.println("Enter First String").length(). Step-1 Write the source code import java.i.i++) { if((byte)c==(byte)first.readLine().count2=0.in)).length(). public class Sort { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.226 The jar utility provided with jdk is to create and manage the JAR files.charAt(i)) { .readLine().out. String second=br.*.c++) { for(i=0. i<l2-1. } }else{ for(i=1. } } if(count1>count2) { for(i=1.charAt(i)) { count2++.print((char)c).i++) { System.print((char)c).i<=count2. } } for(i=0. } } } } .227 count1++.out.i<=count1.i++) { if((byte)c==(byte)second.i++) { System.out. 228 } Step-2 Create the manifest file named as Sort.class Java-Bean: True Step-3 Create the jar file.mft Name: Sort. Tabulating the contents of the jar file Extracting Files from a jar file . class Java-Bean: True The first line of the manifest file provides version information.0 Name: Sort. One of the most important items to note in this file is Java-Bean: True. . This file consists Manifest-Version: 1. The other lines provide information about each of the element in the JAR file.229 Manifest File This is an ordinary text file that can be viewed with an editor. lang. Strings in java. such statement it implicitly invoke new operator to allocate memory from heap. cannot be changed on the same reference.lang package. how object is created inside without new operator!! When JVM encounters String s1=´Java´. Let¶s check it out class Demo { public static void main(String args[]) { String s1="Java". Serializable interfaces.String class is final which implies no class can extend it. Java String Class is immutable. i. 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. once created and initialized. But. Each quoted string is an object of the String class. A java.e.230 Chapter-14 String In java strings are sequence of Unicode characters. String is a predefined class present in java. .println(s1. Therefore s1 must have a hash code value. So it is created inside heap. s1 is a reference of string class. Comparable. } } Output: 71355168 Yes. String is a final class that means String class cannot be inherited. System.out.hashCode()). String is the child class of Object class and implements the CharSequence. If you change the content of the original String object then an entirely new String object is created. } } .'b'.'f'. String s1=new String(mak). and length specifies the number of characters to be used from the character indicated by start. System.out.'e'. int length). class Demo { public static void main(String args[]) { char mak[]={'a'.'d'.'g'}.'b'. String(char chars[ ]) This constructor can be used to create a string from array of characters y class Demo { public static void main(String args[]) { char mak[]={'a'.3).println(s1).3. String s1=new String(mak.out. System.println(s1). int start.'c'}. } } Output: abc y String(char[] c.'c'. The parameter start specifies the index from which the charcters are used to create the String object.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. e.out. The constructors are String(byte b[ ]) String(byte b[]. System.out. The parameter start specifies the index from which the characters are used to create the String object. class SubStringConstructiom { .int start.println(s1).e.Java!"). System. int length) The parameter b represents the array of bytes. the range. Unicode characters take 2 byte from memory.Java! class Demo { public static void main(String args[]) { String s2="Hello World!". only ASCII character set then it is advisable to use byte data type rather than char. If the programmer is assured that the user characters in a string are only from keyboard i.232 Output is def y String(String stringObj). String s1=new String(s2). class Demo { public static void main(String args[]) { String s1=new String("Hello. } } Output is Hello.println(s1). } } Output is Hello World! In java Strings are set unicode character sequence. and length specifies the number of characters to be used from the character indicated by start i. 3). S1=´java´.println(s1). String s2 = new String(ascii. 2. 66. } } Output Surprised!!! S1 is reference of string class. See the program below. } } 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. 67. However.println(s2).out. String s2="java". class Demo { public static void main(String args[]) { String s1="java". if(s1==s2) System. Similarly s2 is . But when == used in case of string references some abnormal behavior is shown. statement instructs the JVM to call the constructor of string class through new operator implicitly. 68. S1 created inside stack & memory is allocated to it from heap. System. Behavior of == operator in case of string The == operator is used to determine whether the content of two variables are same or different.println("Surprised!!!"). String s1 = new String(ascii). most of the time.out. you will want to use the default encoding.out. 70 }.233 public static void main(String args[]) { byte ascii[] = {65. System. 69. Strings are immutable i. So.234 created in side stack & JVM implicitly calls the constructor to allocate memory to it from heap. So s1 is now not equal to s2 class Demo { public static void main(String args[]) { String s1="java". content of a string object can not be altered in a given reference. JVM searches the heap to find whether same character set in same sequence present or not. allocates to s2. when programmer explicitly calls the constructor through new operator a new separate memory chunk is allocated. If such a memory chunk is available then.e. So when JVM implicitly calls the string class constructor. & it gets. 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. s1 cannot be equal to s2. if(s1==s2) System. in case of string object when the constructor is called implicitly. 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. String s2=new String("java"). But. JVM assigns the starting address of the memory chunk that has been allocated to s1. JVM behaves in different way.out. } } Output: no output . s1 & s2 has the same character set in the same sequence.println("hello"). JVM first allocates memory to s1 from heap say 1000 as shown in the figure. In the above program. instead of allocating new memory chunk it uses the existing one. Concept is absolutely correct. So s2 also contains 1000. When s2 is encountered. So instead of allocating new memory chunk. out.println("Believe dear we are different.out. class X { int x."). } } Output: No. d2. if the content is same then it returns true.out.out. if(d1.235 A closer look at equals() & hashCode() method In case of String class. We are different.equals(d2)) System. . We are different.println("Same same dear. X d2=new X().x=9. } class Demo { public static void main(String argts[]) { X d1=new X(). Except String class in all cases equal method checks the content of reference variable.").x=9. else System.println("No.println("Hello! We are same."). d1. if(d1==d2) System. else System. 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."). the equals() method & the hashCode() has been over ridden. JVM allocates memory from heap to d1 & d2. In the above program. I have explicitly invoked the constructor of string class through new operator. if(d1. We are different.out. they are going to contain the starting address of the memory chunk allocated to them.out. Check this program class Demo { public static void main(String argts[]) { String d1=new String("Java").println("Hello! We are same. == . else System. Foxed dear!!! Why different output? Let me explain the program from the very beginning. JVM has allocated two different chunk of memory to d1 & d2. } } Output: Hello! We are same. Since d1 & d2 both are reference variables. else System. == operator & equals method checks the content of reference variables & since the content is different output is quite obvious.equals(d2)) System. Believe dear we are different.println("No.").println("Believe dear we are different.out.out. So the content of d1 & d2 is entirely different. So d1 is not equal to d2. d1 & d2 are the reference variables of String class. if(d1==d2) System.println("Same same dear."). String d2=new String("Java"). But. Definitely d1 & d2 have different address.236 Believe dear we are different. the story is different in case of String objects.")."). println("Hello! We are same.237 operator checks the content of d1 & d2. equls() method checks whether the character sequence & character case (upper or lower) is same or not while invoked by string objects. as I have said behave in a different way in case of String class.out.").out. equals() method returns the same Boolean true value.hashCode()). since the are different out put is as usual.out. else System.hashCode()). There fore hashCode() method returns same value for two objects. We are different.").println(d2. } } Out put: Hello! We are same. If the character sequence & character case is same then equals method returns boolean true else false. if(d1. The hashCode() method returns the same integral value if the equals() method returns boolean true value for two objects. System. in case of equals method. String d2=new String("Java").out.equals(d2)) System. else System.println("Same same dear."). But.").out. System. All these stuffs are only because Strings are immutable.println("Believe dear we are different. 2301506 2301506 See since the character set & character sequence is same in both String objects. See the program below class Demo { public static void main(String argts[]) { String d1=new String("Java").println(d1. Believe dear we are different. .out.println("No. if(d1==d2) System. class Demo{ public static void main(String args[]) { String s1="Hello world". System.println(i).char c[]. public void getChars(int start.238 Some Important Methods of String class with example:y public int length() this method is used to determine the length of the string. char ch=s1. class Demo{ public static void main(String args[]) { String s1="Hello world". }} Upon execution this program throws string out of bound index exception. char ch=s1.out. y y . the last variable index_1 represents the index number of the array from which the characters copied from the string has to be stored.println(ch).println(ch).charAt(2). System.length(). The index supplied must be within the length of the string. For example class Demo{ public static void main(String args[]) { String s1="Hello world". }} 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.charAt(12). 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. int i=s1. }} 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.int end. System.out.out. boolean b=s1.equalsIgnoreCase(s2).getChars(1.239 class Demo{ public static void main(String args[]) { String s1="Hello world".println(b[j]). for(int i=0. y . }} 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.length().out.3.out.getBytes(). byte b[]=new byte[i].i++) System. s1. }} Output: e l y 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".2).println(ch[i]). String s2="hello world". b=s1.j++) System. class Demo{ public static void main(String args[]) { String s1="Hello world".j<i. for(int j=0. int i=s1. char ch[]=new char[5].i<5.ch. println(i). } } Output: 0 class Demo { public static void main(String[]args) { String s1="Java".println(i).println(b). System. .out. this method is used to compare two strings. Lets have an example how this method behaves. int i=s2.println(i). int i=s1. System.out. i>0 means string is greater than the string taken as argument. }} Output:true y public int compareTo(String sobj). System. } } Output: -7 Ok fine now check these two programs class Demo { public static void main(String[]args) { String s1="Java". String s2="C++".out. class Demo { public static void main(String[]args) { String s1="Java".compareTo(s2). int i=s2. } } Output:7 Conclusion is that i<0 means invoking string is less than the string taken as argument.compareTo(s1). i=0 both the string object are same.240 System. String s2="C++".out.compareTo(s2). String s2="C++". See the example below class Demo { public static void main(String[]args) { String s1="Java". int i=s1. System. System. } } Output: -32 y public boolean startsWith(String prefixValue.compareTo(s2). No absolutely not. So you can feel that startsWith method of string class is overloaded.241 Actually how the comparison is made only through the length. } } Output true public boolean endsWith(String suffixValue) y y .out.out.println(i).println(i). System. String s2="java". } } Output: true public boolean startsWith(String prefixValue) checks if the string starts with the specified prefixVlaue. class Demo { public static void main(String[]args) { String s1="Java is cool". boolean i=s1. Comparision is done through dictionary order & upper case letter comes first.println(i).startsWith("Java").out.8). boolean i=s1.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".startsWith("cool". indexOf('l'.4). int b=s1.println(b).indexOf('w').242 checks whether the string ends with the specified suffixVlaue or y not. System.4).indexOf('l'. public int indexOf(int ch) this method is used to return the place value of the specified character in the string. }} Output:6 public int indexOf(int ch. This checking is done with respect to the integer value fromIndex.println(b). class Demo{ public static void main(String args[]) { String s1="Hello world". If the string does not have the character with in the string then -1 is returned. int b=s1. }} Output 9 class Demo{ public static void main(String args[]) { String s1="Hello world".out. int b=s1.int fromIndex) this method returns the place value of the specified character with in the string. System.out.out. y . System. class Demo{ public static void main(String args[]) { String s1="Hello world".println(b). }} Output:2 class Demo{ public static void main(String args[]) { String s1="Hello world". out.indexOf('H'.4).243 int b=s1.out. class Demo{ public static void main(String args[]) { String s1=" Hello World".concat(" World").println(s2). System. y y public String trim() this method is used to eliminate the white space from the beginning of the string.out. System. String s2=s1. class Demo{ public static void main(String args[]) { String s1=" Hello". }} Output: Hello World y y 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. . }} 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. String s2=s1.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.println(b). System.toLowerCase(). class Demo{ public static void main(String args[]) { String s1="Hello World". }} Output: Hello World Hello World y public char[] toCharArray() this method is used to convert the string to character array. System.out.out.println(s1).toCharArray(). System. ch=s1.out. int i=s1. for(int j=0.println(ch[j]). }} Output: H E L L O W O R L D .println(s2).trim().244 String s2=s1. class Demo{ public static void main(String args[]) { String s1=" HELLO WORLD".j++) System.length(). char ch[]=new char[i].j<i. public synchronized void ensureCapacity(int capacity) :This method is used to set the capacity of the StringBuffer.int end. public synchronized void setLength(int length) :This method is used to set the length of the StringBuffer. which is the longest String it can represent without needing to allocate more memory. y y y y .char c[]. StringBuffer is a final class. but can be changed or modified.Object class & implements the interfaces CharSequence.lang.lang package. String class objects are immutable where as a StringBuffer class objects are mutable. StringBuffer object is auto flushed. StringBuffer class in java is a sub class of java. StringBuffer object is like a String. Methods of StringBuffer y y public synchronized int length() : returns the length of the StringBuffer. StringBuffer(String s) This constructs a StringBuffer that initially contains the special String.245 Chapter-15 StringBuffer StringBuffer is a class present in java. public synchronized char charAt(int index) :This method returns a character from the StringBuffer.int index) :This method extract more than one character from the StringBuffer. Serializable. An instance of StringBuffer class represents a String that can be dynamically modified. 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. A StringBuffer has a capacity. public synchronized void getChars(int stat. public synchronized int capacity() : returns the capacity of the StringBuffer. StringBuffer class cannot be inherited as it is a final class. char ch) :This method set a character in the StringBuffer.246 y y y y y y y y y y y public synchronized void setCharAt(int index. public synchronized StringBuffer append(String s) :This method append a String in the StringBuffer. . 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 append(StringBuffer sb) : public synchronized StringBuffer append(char c) : public synchronized StringBuffer delete(int index. public synchronized StringBuffer reverse() :This method is used to reverse the StringBuffer. String s) :This method is used to replace a String in the StringBuffer. String s) :This method is used to insert a String in the StringBuffer. public synchronized StringBuffer replace(int index. public synchronized StringBuffer insert(int index. public synchronized StringBuffer append(Object o) :This method calls toString() on Object o and append the result to the current StringBuffer. int length. public String toString() :This method is used to convert the String to StringBuffer. public int hashCode(): returns the hash value of Character class Object. public char charValue( ): This method is useful to convert character class object into primitive char value. 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. it contains a field and in this field primitive data types are stored.  Wrapper class converts primitive data types into objects. Character Character class object is a wraps around a char.lang package. LinkedList classes present in java. float etc. 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. .247 Chapter-16 Wrapper class: Each java primitive data types has a corresponding wrapper class. hence primitive may be converted into object type using Wrapper classes present in java. When we create an object of the wrapper class.util package cannot handle primitive data type like int. ArrayList. char. public static String toString(boolean b) : This method coverts boolean data types into String. Methods of the Number class are: . Short. Boolean Boolean is wrapper around boolean value. public int hashCode() : returns the hash value of Character class Object. Long and Double. Number Number is an abstract class whose subclass is Byte. 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. 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. Float. public static Boolean valueOf(boolean b): This method converts a boolean value into Boolean object. Integer. Otherwise the Boolean object will hold false vales. The method of the Number class is override in the child classes.248 public static String toString(char c): This method coverts char data types into String. public static Boolean valueOf(String s) :This method convert a String that contains a boolean value into Boolean object. The Byte class object contains byte value. public static Byte valueOf(String s): Converts String to Bye class object. Constructor:Constructor of Byte class is Overloaded y Byte(byte b) Syntax:Byte b1=new Byte ((byte) 12). public static Byte valueOf(byte b): Converts byte value to Byte class object.//when we extract the value from the b3 object then the program is terminated at runtime by throwing an Exception ³NumberFormatException´. public int hashCode(): returns the hash value of Byte class Object public static String toString(byte b): Converts byte value to String . Byte b3=new Byte(³Java´).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. y Byte(String s) Syntax:Byte b2=new Byte (³45´). Methods: public static byte parseByte(String s): Converts String to byte datatype. public int hashCode(): Returns the hash value of Short class Object. Short s3=new Short (³Java´). Constructor:Constructor of Integer class is Overloaded y Integer(int b) . public static Short valueOf(short s): converts short data types to Short class Object. The Integer class object contains int value. public static String toString(short s): Converts short data types to String. public static Short valueOf(String s): Converts String to Short class object. Constructor:Constructor of Short class is Overloaded y Short(short s) Syntax:Short s1=new Short ((short) 12). The Short class object contains short value. Methods: public static short parseShort(String s): converts String to short data types.250 Short class:Short class wraps a value of the primitive type ³short´ in an object. Integer class:Integer class wraps a value of the primitive type ³int´ in an object. y Short(String s) Syntax:Short s2=new Short (³45´).//when we extract the value from the s3 object then the program is terminated at runtime by throwing an Exception ³NumberFormatException´. public int hashCode(): Returns the hash value of Integer class Object. . public static Integer valueOf(String s): Converts String class object into Integer class Object. public static String toString(int s): converts int dada type into String. public static Integer valueOf(int s): converts int data type into Integer class object. y Long(String s) Syntax:Long l2=new Long(³45´).//when we extract the value from the i3 object then the program is terminated at runtime by throwing an Exception ³NumberFormatException´.251 Syntax:Integer i1=new Integer(12). Integer i3=new Integer (³Java´). y Integer(String s) Syntax:Integer i2=new Integer (³45´). The Long class object contains long value. Methods: public static int parseInt(String s): converts String to int data type. Long class:Long class wraps a value of the primitive type ³long´ in an object. Constructor:Constructor of Long class is Overloaded y Long(long l) Syntax:Long l1=new Long (12). //when we extract the value from the l3 object then the program is terminated at runtime by throwing an Exception ³NumberFormatException´. public static Long valueOf(String s): Converts String class Object into Long class Object. public int hashCode(): Returns the hash value of Long class Object.//when we extract the value from the f3 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. The Float class object contains float value. Float f3=new Float(³Java´). public static String toString(long s): Converts long data types into String. . public static Long valueOf(short s): Converts long data types into Long class object. y Float(String s) Syntax:Float f2=new Float (³45´).252 Long l3=new Long (³Java´). Float class:Float class wraps a value of the primitive type ³float´ in an object. Constructor:Constructor of Float class is Overloaded y Float(float b) Syntax: Float f1=new Float ((float) 12.5). public static Float valueOf(String s): Converts String class object into 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. public int hashCode(): Returns the hash value of Float class Object. public static String toString(float s): Converts float data types into String.09). public static Float valueOf(float s): Converts float data types into Float class Object. . Double d3=new Double (³Java´).253 Method: public static Float parseFloat(String s): Converts String class object to float data type.//when we extract the value from the d3 object then the program is terminated at runtime by throwing an Exception ³NumberFormatException´. y Double(String s) Syntax:- Double d2=new Double (³5.9´). Constructor:- Constructor of Double class is Overloaded y Double(double b) Syntax:- Double s1=new Double (23. System.println(d). public static Double valueOf(double s): Converts double data types into Double class object. s1+=10. d+=5.out. public int hashCode(): Returns the hash value of Double class object.println(i). Example-1 public class Wrap1 { public static void main(String rs[]) { String s="22".parseDouble(s).out.out. i++. int i=Integer.parseInt(s). double d=Double. System. short s1=Short. public static Double valueOf(String s): Converts String class object into Double class Object.println(s1).parseShort(s).254 Method: public static double parseDouble(String s): Converts String class object to double data type. System. . public static String toString(double s): Converts double data types into String. println(s).out.out. Whereas unboxing is required to convert Wrapper class Object into subsequent primitive data types. System.println(s). System. s+=12. } } 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. s+=1. System. There is no need to explicitly construct a wrapper class object. s=Double.out. In general.toString(s1).toString(i).println(s).255 s=Integer. . s=Short.toString(d). This technique is popularly known as autoboxing in java. s+=2. 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").out. a.show(). } } Output: . void show() { if(b){ System. }else{ System. } } public static void main(String args[]) { Auto a=new Auto().println("You Need Money").out..println("You Need Knowledge"). boolean b=b1. 257 Chapter-17 Taking Input from keyboard In java you can take the input from keyboard in three ways. } } Compile this program by javac Demo1.out. This can be done by java Demo1 Hello & the out put will be Hello. always remember that the arguments or the input supplied to the java program .println(args[0]). In java the zeroth argument is the string supplied by the user as in this case Hello is the zeroth argument. 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.java class Demo1{ public static void main(String args[]) { System.java During the execution phase you are going to provide the command line argument which is of string type. 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. But. Lets have an example Demo1. So you have to use different method & techniques to get it converted to desired type.java class Demo2 { public static void main (String args[]) { String s=args[0]+args[1]. When we extract the element then we extract the element through the array indexes.258 from the command prompt are always in the form of string. public class Demo3 { public static void main(String args[]) . If the array index cross the range then the program is terminated at the runtime by generating ArrayIndexOutOfBoundsException.println(s).g. e. e. Demo2.g. } } 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. To access the 1st argument you to use args[1] & so on. And one thing strings are objects in java.out. System. In command line 1st argument 0th argument is separated by space. As the method return type is String then the given input is in the string format.out.ArrayIndexOutOfBoundsException. Both the class present in java.io package. So you have to import that package.lang. But the programmer is bound to .io package. 2nd: by the use of readLine() method The readLine () method is available in the java.length) { System.println(args[i]). } } } Compile the application by javac Demo3. The syntax of the method is public String readLine()throws IOException { } This method present in BufferedReader and DataInputStream class. while(i++<args.259 { int i=0.java Execute it by java Demo3 A B C Output B C Program is terminated by throwing java. readLine(). Stsring s=br.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.260 handle IOException as the method throws IOException.out.out. throws IOException this phrase is added to main method because signature of readLine () method has throws IOException.*. BufferedReader br=new BufferedReader(is).io. Till now remember that when ever you are going use a method which has signature of throwing any . } } Compile the application by javac Demo. Lets have an example: import java. System.in). class Demo{ public static void main(String args[]) throws IOException { InputStreamReader is=new InputStreamReader(System. System.println(³Output Is ´+s).println(³Enter The Data From Keyboard´). Scanner reads formatted input and converts it into binary form. String s.261 Exception then. class Demo{ public static void main(String args[]) { InputStreamReader is=new InputStreamReader (System. with in which such a method is called. InputStreamReader behaves like a channel connected to it. . BufferedReader br=new BufferedReader(is). String and other types of data from any input sources. Another way is that invoke the method readLine () inside a try catch block.readLine().io. that method must have throws Exception_Object. } Input: Hello World Output: Hello World System.out. 3rd(By using Scanner class) Scanner is a class present in java. }catch(IOException e) { } System.in is the keyboard.println(s).util package.in). try{ s=br. import java. Scanner class is used to read all types of numeric values.*. readLine() method reads the data & store it in the string s. in). Returns true if a byte available to be read. Scanner s1=new Scanner (fr). Returns true if a available to be read. 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.262 Scanner can be used to read input from the console. Scanner s2=new Scanner (System. Scanner s3=new Scanner(s). Returns true if a int value is available to be read. long value is boolean hasNextInt() boolean hasNextFloat() boolean hasNextLong() value is . Returns true if a float available to be read. from a String or any source that implements Readable interface. value is boolean hasNextBoolean() boolean hasNextByte() boolean hasNextShort() Returns true if a short value is available to be read.txt´). Constructor: FileReader fr=new FileReader (³a. String s=´Interface Software´. from a file. read it by calling one of Scanner¶s next() method. Returns the next token as a boolean value. Returns the next token as a float value. Returns the next token of any type from the input source. Returns the next token as a double value. Returns the next token as a short value. Repeat the process until the input is exhausted. 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 Scanner¶s hasNextXXX method. Returns the next token as a byte value. Returns the value. Returns the next line of input as a String. How to take an integer from key board . 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.263 boolean hasNextDouble() Returns true if a double value is available to be read. Returns true if a line of input is available. If input is available. 123 To use the Scanner class & the methods those belongs to scanner class you have to import the java. After . int i=sc.util package.*. sc. System.nextFloat(). class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in represents keyboard.util. class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.println(³Enter A Number´).close().nextInt(). sc. } } Enter A Number 5 Output Is :5 How to take a float variable import java.in).out.123 Output Is: 10. System.264 import java.close().out. float i=sc. System.out.*.out. System.in). System.println(³Output Is :´+i).util. } } Enter A Floating point value 10.println(³Enter A Floating point value´).println(³Output Is: ´+i). println(³Enter a boolean value´).in). boolean i=sc.nextBoolean().println(³Enter A Byte´).nextByte().util.println(³Output Is :´+i). System.265 taking the input you have to close the scanner by the invocation of close method. sc. sc.*. System. class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System. class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System. To take boolean value as input import java.out.close().out. System.out.println(³Output Is :´+i). System. } } Enter a boolean value true Output Is :true To take byte from key board import java.out.util. } } Enter A Byte 23 Output Is :23 .in).*.close(). byte i=sc. 266 To read a string from keyboard import java. System.println(³Output Is ´+i). System.nextLine(). class Demo { public static void main(String[] args) { Scanner sc=new Scanner(System.out.in). sc. String i=sc. } } Enter The Text hello world Output:hello world .println(³Enter The Text´).*.util.close().out. This is one of the vital importance of JNI. and update Java objects.However it is rare for applet and application programmers to use the native codes. 1: If client requires platform dependent features in java but the standard java class library supports the platform independent feature. native indicates that the body of a method is to be found elsewhere. 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. People who port java to new platform implement extensive native code to support GUI components. inspect. JNI never imposes any restriction to the JVM. network communication and a broad range of platform specific functionalities . In this situation programmer required JNI for supporting platform dependent feature in java. Java VM vendors can add support for the JNI without affecting other parts of the VM. Therefore. The native modifier can refer only to methods. Load classes and collects class information. in a library. catch and throw Exception. Perform runtime type checking. Like the abstract keyword. .267 Chapter-18 JAVA NATIVE INTRFACE Overview: In JAVA native is a modifier. Call Java methods. By programming through the JNI. In the case of the abstract methods. Programmer use native methods to: y y y y y Create. the body lies entirely outside the java virtual machine. Now let¶s discuss what are the situations when java programmer needs the native method. the body is in a subclass but in case of native methods. 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. hence increases the performance. An interface pointer is a pointer to a pointer to a structure. Java native interface allows java byte-codes to communicate with foreign methods like C/C++. Drawback of native code is that it violates java¶s platform independent features and since binary files are generated during native implementation therefore this procedure has less security.println(x. JAVA .fun(). System. In java native code or native method accesses JVM features by calling JNI functions.out. x.i). In java JNI functions are available by using an interface pointer. . 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. //Native method calling.println(x. } public native void fun().C Communication public class p { int i.i). x. Advantage of such a technique is that byte-codes can able to communicate with executable files which execute faster.i=10.268 JNI can be used with Invocation API to embed any native application in JVM.out. System. public static void main(String args[]) { p x=new p().C COMMUNICATION //Java . java This will generate the class file as p. p. } } Step 1: Compile it with javac p.it is machine generated */ #include <jni.loadLibrary("p").269 //Native method declaration. jobject).class Step 2: Create the header file by the command javah p This will generate the header file p. #ifdef __cplusplus } #endif #endif The above two steps are same for WINDOWS and LINUX .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 *.h /* DO NOT EDIT THIS FILE . static{ System.h . jint i.C file p.h´ #include"stdio.h" JNIEXPORT void JNICALL Java_p_fun (JNIEnv *env.270 For LINUX: Step 3: create the .obj.c Note that: For LINUX the . printf("%d".fid). cls=(*env)->GetObjectClass(env.cls. } . p."I"). fid=(*env)->GetFieldID(env."i". printf("Hello").obj).i). jobject obj) { jclass cls. i=(*env)-> GetIntField(env.C file name should be same as that of the java file name otherwise run time error will arise. jfieldID fid.h" #include´jni.c #include"p. 271 Step 4: create the object file by gcc ±O ±fpic -c p.c Step 5: create the libp.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.c To create dynamic linking library java p to execute java program p. Header file p.path=.o Step 6: get the output by java ±Djava. p On windows platform: Step 3: CL/LD p.so(shared library) file by gcc -shared -o libp.so p. public static void loadLibrary() . Native methods are loaded when the programmer call a static method of System class.library. it contains the prototype declaration of the native method. gcc -O -D_REENTRANT -fpic -c p.h is generated by JVM.java file is a usual java file. It takes the argument JNIEnv *env & jobject obj. Lets understand the concept through an example. fully-qualified-class [ type ( arg-types ) ret-type type[ ] method type Consider the p. Consider the C program below void fun() { .c file.272 JNIEXPORT void JNICALL Java_p_fun (JNIEnv *. 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 . typedef const struct JNINativeInterface *JNIEnv. jobject) Signature: V() inside the comment line indicates that the return type of native method is void. JNIEnv is a pointer to the structure JNINativeInterface which contains function pointers. jobject). ptr1=&a. } The out put will be Hello World. While java is communicating with C jobject & jclass both are same. jclass is typedef as jobject(typedef jobject jclass). (*pointer)->p(). }. is a function pointer inside the structure JNINativeInterface. GetObjectClass(JNIEnv *. pointer=&ptr1.p=&fun. } struct xxx { void(* p)(). obj holds the value of the this pointer that points to the current object that is x here. a. GetOBjectClass returns the reference of the current object which is stored in . You can see that JNIEnv *env is similar to that of struct_ptr *pointer & struct xxx is similar to that of JNINativeInterface .273 printf(³Hello World´). struct xxx a. int main() { struct_ptr *pointer . Now consider the second argument jobject obj. typedef struct xxx *struct_ptr .*ptr1. 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. 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.274 cls. signature of µi¶ to indicate that i is of integer type.obj.h /* DO NOT EDIT THIS FILE . public static void main(String args[]) { new p1(). GetIntField(env.h> /* Header for class p1 */ #ifndef _Included_p1 #define _Included_p1 #ifdef __cplusplus extern "C" { #endif /* .obj.fun().java //Get Your Native Interface Version. In the program. µname¶ holds the name of the class element that is µi¶ & µsig¶ holds I. Similarly if the class contains a float variable then to access that variable the function will be GetIFloatField(env. } static{ System. class p1{ public native void fun().loadLibrary("p1").it is machine generated */ #include <jni. Both these parameter are pointer to character constant. jclass clazz. Example 2: p1. } } p1.fid). const char *sig). const char *name. rturns the value of i.fid). #ifdef __cplusplus } #endif #endif p1. printf("%x".i). Similarly the typedef version of other java data types are listed below.275 * Class: p1 * Method: fun * Signature: ()V */ JNIEXPORT void JNICALL Java_p1_fun (JNIEnv *.h" JNIEXPORT void JNICALL Java_p1_fun (JNIEnv *a. jobject b) { jint i=(*a)->GetVersion(a).h" #include"stdio. jobject). In JNI int is typedef as jint. 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 .c #include"p1. } Both these examples have i¶s data type as jint. loadLibrary("p2").java class p2{ public native static void fun(). }} p2.276 Java Type Native Type Description float double void jfloat jdouble void 32 bits 64 bits N/A Example 3: //Static native method 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 . static{ System. } public static void main(String aegs[]) { p2.fun(). c #include"stdio. From JAVA"). I have already told that when java communicate with C. } Since the native method is static therefore second argument to the function JNIEXPORT void JNICALL Java_p2_fun (JNIEnv * a. #ifdef __cplusplus } #endif #endif p2.h" #include"p2. jclass b) { printf("Hello C. jclass & jobject are exactly the same thing so you can replace jclass with jobject. . jclass).h" JNIEXPORT void JNICALL Java_p2_fun (JNIEnv * a.277 extern "C" { #endif /* * Class: p2 * Method: fun * Signature: ()V */ JNIEXPORT void JNICALL Java_p2_fun (JNIEnv *. jclass b) is of jclass type. 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 let¶s 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 let¶s 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 thread¶s priority, call the setPriority() method, passing in the desired new priority. The getPriority() method returns a thread¶s 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(); main] Insufficient Thread[job2. Then the run() method is called. . the thread does not start running immediately. it to the running state."job1").n)."job2"). } } Output: Fund is available Fund is available Got it!!Thread[job1. Thread t1=new Thread(job1. t2.1000. But by the use of synchronized key word in the second program job1 is not suffered. This is because of various reasons it may goes to a sleep or it is waiting for some event to be happened.0.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. Finally when the thread completes its execution it goes to dead state.5. From the blocked state thread goes to ready state when it wakes up or by the invocation of resume method. When a thread starts execution. X job2=new X(80. This is known as blocked state. I have always given priority to use synchronized block rather than synchronized method because the prior one improves performance due to atomic level synchronization.n). It goes into a ready state and stays there until the task scheduler or you may say thread scheduler select it for execution. 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. During its execution state.start().start(). Thread t2=new Thread(job2. the thread may temporarily give up the CPU.293 X job1=new X(50.5. t1. the thread has finished its task and is considered as dead.println(Thread. class X implements Runnable{ public void run() { System.out. It cannot be started again. When thread is dead When the execution of codes in side run() method is completed. Once a thread become dead it can not go to any other state. } } .currentThread()+"Hello X").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. if you invoke the start method then time exception is thrown by JVM. t1.lang.start(Unknown Source) at demo. Thread t1=new Thread(o. Always remember that You can¶t restart a dead thread.main]Hello X The dead thread is an object of Thread class & therefore it is possible to access its data and call its methods.Thread.295 class Demo { public static void main(String[] args){ X o=new X().Demo.main(Demo.lang. } } Output Exception in thread "main" java.java:20) Thread[1st. That¶s all about threading in java folks .start().IllegalThreadStateException at java."1st").5. You can call the methods of a dead thread. t1.start(). 296 Chapter-20 GENERICS INTRODUCTION Generics is a powerful feature of java.then apply the same algorithm for various data types without any changes. It is introduced by JDK 5. Previously we do this things using Object class. in generics all type casts are done implicitly. A simple example // Defination of the generic class Gener class Gener<S> { S obj. and methods that will work for various types of data in a type safe manner. interfaces and methods which are type independent. Using generics we can define a single algorithm which is independent of data . interfaces . Generics overcomes this overhead. 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. interfaces and methods which are type specific but using generics it is possible create classes . Why we need Generics? We generally create classes . It is said to be powerful because using it we can create classes . This makes the use of generics more secure. because Object class is the super class of other classes. . Gener(S o) { obj =o. getClass().println("Type of S is "+ obj.out. // prints the type of data hold by it ob1.println("Data is "+obj).297 } void showClass() { System. } void showData() { System.out. .showClass().getName()). } } public class GenericDemo { public static void main(String[] args) { // Create a Gener reference for Integer Gener<Integer> ob1 = new Gener<Integer>(100). // Create a Gener reference for Sting Gener<String> ob2 = new Gener<String>("SAMITA .lang.showData(). S holds the type parameter of which the Gener class object is created. LORY In the above example S is the name of a type parameter.lang.showClass(). } } Output : Type of S is java. S is written inside . // prints the type of data hold by it ob2.298 // prints the data hold by it ob1. LORY").showData() . // prints the data hold by it ob2.Integer Data is 100 Type of S is java.String Data is SAMITA . . Whenever we specify the type of class object we want to create we specify it inside <>. So we have passed the argument according to the type. So we have passed the argument according to the type. char.299 <>. Here S holds String . We also have specify the type inside <> while calling the constructor. Here we created the object of Gener class . so for ob1 S behaves as Integer. LORY"). Gener<Integer> ob1 = new Gener<Integer>(100). Here the S holds Integer . That means the type argument passed to type parameter must be a class type but it cannot be any primitive type. 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. And everywhere in the class definition S behaves like the type specified for that object.. y Generics works only on objects. . Here we created the object of Gener class. e. of Integer type. e. // Error The above example will result in an error because primitive type ( int . so for ob2 S behaves as String. etc) cannot be used . Gener<String> ob2 = new Gener<String>("SAMITA . // 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.g ob1 = ob2 ..g Gener<int> ob1 = new Gener<int>(100).of String type. getClass(). } void showData() { System.out.300 A Generic class with two type parameters We can use more than one type parameter in a generic type.B o2 ) { ob1 =o1. B>{ A ob1. Gener(A o1 . } void showClass() { System.getClass().println("Data in ob2 "+ ob2). we just have to separate them with commas.println("Type of B is "+ ob2.println("Data in ob1 "+ ob1). System.getName()). ob2 =o2. If we want specify two or more type parameters . B ob2.println("Type of A is "+ ob1.out. Let¶s consider the example below. // Defination of the generic class Gener class Gener<A .getName()).out. System.out. . LORY .Integer Type of B is java. } } Output : Type of A is java.String>(100.String Data in ob1 100 Data in ob2 SAMITA .String> obj1 = new Gener<Integer."SAMITA .301 } } public class GenericDemo { public static void main(String[] args) { // Create a Gener reference for Integer and String Gener<Integer. LORY"). // prints the type of data hold by it obj1. // prints the data hold by it obj1.showClass().lang.lang.showData(). Let.out. Gener(A o1 ) { ob1 =o1. 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.println("Data in ob1 "+ ob1).getName()).out. } void showData() { System.302 Here two type parameters T and V are separated by comma . } .see the example below. so now if we want to create a refrence of Gener we have to pass two type arguments.println("Type of A is "+ ob1. } void showClass() { System.getClass(). // Defination of the generic class Gener class Gener<A extends Integer >{ A ob1. showData(). let¶s see .303 } public class GenericDemo { public static void main(String[] args) { // Create a Gener reference for Integer Gener<Integer> obj1 = new Gener<Integer>(100). .lang. } } Output : Type of A is java. // prints the type of data hold by it obj1.Integer Data in ob1 100 The above will work well but not the below program. // prints the data hold by it obj1.showClass(). } } public class GenericDemo { public static void main(String[] args) { .out.out. } void showClass() { System.println("Data in ob1 "+ ob1). Gener(A o1 ) { ob1 =o1.getName()). } void showData() { System.getClass().304 // Defination of the generic class Gener class Gener<A extends Integer >{ A ob1.println("Type of A is "+ ob1. 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. // prints the type of data hold by it obj2. // prints the data hold by it obj2.showData(). Web can also declare one class and multiple interfaces as bound for A.305 // Create a Gener reference for String Gener<String> obj2 = new Gener<String>("SAMITA .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.showClass(). LORY"). } } Output : Exception in thread "main" java.main(GenericDemo. e.lang. y y We can also declare interfaces as bound for A .g class Gener<A extends Myclass & Myinterface> . } // wildcard argument is used void Equalls(Gener<?> o2) { if(ob1 == o2. But using wildcard arguments we can do this.306 here Myclass is a class and Myinterface is a interface and & operator is used to connect them. Gener(T o1 ) { ob1 =o1. // Defination of the generic class Gener class Gener<T>{ T ob1.ob1) . 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. 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. To know about the use of Wildcard arguments let¶s see the example below. Wildcard Arguments Wildcard arguments are a special feature of generics . // Create a Gener reference for String Gener<String> obj3 = new Gener<String>("100"). } } public class GenericDemo { public static void main(String[] args) { // Create a Gener reference for Integer Gener<Integer> obj2 = new Gener<Integer>(100).println("TRUE").307 System. } } Outpurt : False False False .out.0). else System.out.Equalls(obj3).println("False").Equalls(obj1). obj1. obj2. obj2.Equalls(obj3). // Create a Gener reference for Double Gener<Double> obj1 = new Gener<Double>(100. out. A generic method can be created inside a non-generic class which acts on multiple types of data independently. y Wild cards can also be bounded. } Now if we are going to execute the statements obj2. we can see that the Equalls method checks the value of different objects irrespective of their types and prints the result .e it will work irrespective of types.ob1) System. else System.e void Equalls(Gener<? extends Number> o2) { if(ob1 == o2. 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.Equalls(obj3).println("TRUE"). We can also define a generic constructor inside a non-generic class which can act on multiple types independently.Equalls(obj3).println("False"). obj1. Suppose we want that in the above example the Equalls method only execute for Numbers otherwise results in an error. Let¶s see the below example. <?> represents the wildcard argument i. So we just have to change a little bit in the method definition i.out. Creating Generic Method and Generic Constructor Now we will see how to define a generic method and generic class. .308 In the above program we have used the wild card argument . out.println(o2).out. g2. } public static void main(String[] args) { GenericDemo g1 = new GenericDemo(100).309 public class GenericDemo { double db.show(). GenericDemo g2 = new GenericDemo(1025.println(db). } // Generic Method static < V > void Display(V o2) { System.show(). . } void show() { System. GenericDemo g3 = new GenericDemo(103.doubleValue().9F). g1.54). // Generic constructor <T extends Number> GenericDemo(T o1) { db= o1. the following code compiles without error: Gener ob1 . Gener<Integer> ob2 .56 SAMITA . Display(125. Display(100).0 1025. Therefore.310 g3. Because of type erasure.56). Display("SAMITA . The official term given to the stripping of parameters is type erasure. ob1=ob2. LORY").show(). Erasure or Raw Types A raw type is a parameterized type stripped of its parameters. } } Output : 100.9000015258789 100 125.like that the Display method is taking different type of arguments as type parameters and displaying the value. LORY From the above example we can observe the output. Raw types are necessary to support legacy code that uses non-generic versions of classes . // valid .54 103. it is possible to assign a generic class reference to a reference of its nongeneric (legacy) version. The Generic constructor is taking the numbers of different type of argument as type parameters and storing it¶s double value in the variable db of each reference. // Defination of the generic class Gener class Gener<T>{ T obj. } void showData() { System.out.getClass(). Gener(T o) { obj =o.println("Type of T is "+ obj.311 ob2=ob1 . } void showClass() { System. } } public class GenericDemo { public static void main(String[] args) { .println("Data is "+obj). // will cause a unchecked warning Remember during compilation all types parameters are erased only raw types actually exists.out.getName()). showClass().Integer Data is 100 Type of ob2 is Gener .312 // Create a Gener reference for Integer Gener ob1 = new Gener(100). LORY").showClass(). System. // prints the type of data hold by it ob1.getClass().showData().lang. System.out.println("Type of ob2 is "+ ob2.getClass().showData().out.getName()).println("Type of ob1 is "+ ob1.getName()). // prints the data hold by it ob2. } } Output : Type of ob1 is Gener Type of T is java. // prints the data hold by it ob1. // prints the type of data hold by it ob2. // Create a Gener reference for Sting Gener<String> ob2 = new Gener<String>("SAMITA . y Restrictions on Static Members : Below are some facts we should care of while using static keyword. . But according to the parameters the variables inside ob1 and ob2 are type casted accordingly. LORY From above example we can see that ob1 and ob2 are both of Gener class.lang.obj. Gener(T o) { obj =newT(). it is compiled as if it is written like this : Gener ob1 = new Gener(100). Some Restrictions While Using Generics y Type parameters cannot be instanciated : class Gener<T>{ T obj. they are not of Integer class or String class. int i = ob1. When we write the below code Gener<Integer> ob1 = new Gener<Integer>(100).String Data is SAMITA .313 Type of T is java.t exist at runtime so how compiler will know what type of object to create.obj. int i = (Integer)ob1. // error } } The above code will result in an error because T doesn. The main difference is encapsulation: errors are flagged where they occur and not later at some use site. it is important to note that they are not the same. cannot make a static reference to a nonstatic type static T obj .314 class Gener<T>{ // error . no static method can acces T type object System. Generics simply provide compile-time type safety and eliminate the need for casts. Generics use a technique known as type erasure as described above.println(obj). .out. and source code is not exposed to clients. } } Java Generics vs. A C++ template on the other hand is just a fancy macro processor. // error. C++ Templates While generics look like the C++ templates. and all instances use the same class file at compile/run time. whenever a template class is instantiated with a new class. no static method can use T Static T show() { // error . and the compiler keeps track of the generics internally. the entire code for the class is reproduced and recompiled for the new class. One through various streams provided in java. Sometimes it is required to read the data from files rather than standard input device like keyboard. Then. File class constructors are used for the creation of the object of the File class. Here I have shown how to open the existing file in window platform. The File class By the use of File class you can directly deal with the files. using those objects programmer can perform manipulation with the files & directory. If you are dealing with directory.315 Chapter-21 Files and Streams Files are located in the secondary storage of the system. Files are normally of two types. When it is opened for any purpose first it is loaded in to the primary memory. Java provides two ways to handle files. Programmer has to create the file object through the constructors provided by File class. then you have to use the list () method provided by java to list out all the files residing in the directory. Another thing I want to say is that in java. File f1 = new File (³c: / Minerva / ravenX´). File f3 = new File (³java´. directory & file system of the platform.io package & other through File class which does not required streams to operate. ³rian´ ). Here the first parameter is a directory name in which the existing file temp has to be opened. directories are also treated as files. After any write operation the changes are reflected according to the implementation of either write through or write back protocol. Actually java does not provide crystal clear view of how the things are done in background when the programmer uses the File class. ³temp´). then the operation is performed. Here 1st parameter is the absolute path & the second parameter is the file that has to be opened. . Various forms of these constructors are given below. binary file & text file. 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. These constructors are overloaded. File f2 = new File (³c: / Minerva ³. If you are quite loyal to Microsoft & want to use \ then. In windows you can use both /. boolean exists ( ) method this methods checks whether the file exists or not 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. 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. class Demo { public static void main(String args[]) { . you have to use the escape sequence \\. Methods of the File Class By the help of the predefined methods of File class programmer can retrieve the properties of a file.io.File.316 Java is quite smart when it comes to deal with path separator. 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. In UNIX & Linux you can use /. import java. //you need to import this package to have various methods to deal with file object. println(³file is not readable´). if(myfile.println(³Name: ´+myfile. System. else System. else System.println(³Name: ´+myfile.out.out. System.out.out.317 File myfile=new File(³/dir1/pex´).out.exists()) System. if(myfile.println(³It is a normal file´).println(³It is not a normal file might be system file like device driver. System.println(³file is readable ´).out.canRead()) System. if(myfile.´).out.println(³File was last modified´+myfile. if(myfile. else System. System. System.getAbsolutePath()).out.out. else System.out.println(³file is not writeable´).getPath()).lastModified()).println(³My absolute path: ´+myfile.getName()).isFile()) System.println(³Path: ´+myfile.getName()).println(³File does not exists´). System.getParent()).println(³file do exists!!!´).out.println(³My parent : ´+myfile.out.out.println(³file is writeable ´).out.canWrite()) System. . out. else System. if(f1."abc.println("we cannot write to this file").318 System.out.io. .println(³size of the file is in bytes´+myfile.println ("we can read from this file") .println ("we cannot read from this file" ) .canWrite()) System. if(f1.out.*.out.out. public class File2 { public static void main(String args[]) { File f1 = new File ("c:/java". } } 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. else System. These methods return a boolean value depending on their readability/ writability.canRead()) System.txt"). Use of long lastModified( ). canWrite() & canRead() methods This method returns the modification time the file.println("we can write to this file"). Example 3 import java.length()). } } renameTo() method returns boolean true value upon if rename is done successfully otherwise false is returned. Example 4 class Demo { public static void main(String[] args) { File myFile=new File (³/dir1/pex´). Therefore that is the output.println(³File cannot be renamed´). } } last modified The file I have used has both read & write option. if(b1) System.out. 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. .println(³Rename operation is success full´).lastModified()+"seconds after January 1 1980").renameTo(³Minarva´).319 System.out. boolean b1=myFile.println("The file was at"+f1.out. But. the interesting one is the output of lastModified() method. else System. *. boolean b1=myFile.println(³File cannot be deleted ´).320 Deleting an existing file Example 5 class Demo{ public static void main(String[] args) { File myFile=new File(³/dir1/pex´).println(³file is deleted´). public class File3 .io.delete(). if(b1) System. File class also provides some other useful methods like: public long length( ) This method is used to know the file size in bytes. } } delete() method returns true if file is deleted successfully else it will return false. else System.out. There is another method dleteOnExit() deletes the file when you complete the operation exit from the execution phase of the program.out. Example 6 import java. Let¶s have another example to fix ideas concretely. println ("= = = = = = = = = =").delete().i++) { f=new File("c:/java".321 { public static void main(String args[]) { File f=null.length. System.out.out. for(int i=0.out.println(f+" exists"). f.println(f+" does not exist"). if(f. System.println("deleting the file "+f). } File f1=new File("c:/java/renfile").i<args. } } } .args[i]).out.exists()) { System. System. f. }else{ System.length()+" bytes").println("its size is "+f.out.println("Renamed file name :"+f1).renameTo(f1).out. System. out. See the example blow Example 7 class Demo{ public static void main(String[] args) { File myFile=new File(³/dir1/pex´). .getTotalSpace(). System. } long x=myFile. return .out. System. x=x/1000. if(myFile.println(³The specified file does not exist´).getfreeSpace(). x=x/1000.exist()==false) { System.println(³Amount of space available in MB: ´+x).out.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. x=myFile.println(³total space in MB: ´+x). easily you can guess. if(b1) System.println(³file doe snot exist´).323 } } Output. else System. if(myFile. .println(³Operation failed´). How to make a file read only Example 8 class Demo{ public static void main(String[]args) { File myFile=new File(³/dir1/pex´).out.println(³Operation is success full´). } } setReadOnly() method is used to make a file readonly.setReadOnly(). then it checks the free space available & total space available respectively in terms of bytes.exist()==false) { System. Methods like getFreeSpace() & getTotalspace() when invoked on the specific file. } boolean b1=myFile.out. return.out. I have divided the returned value of these two methods by 1000 to get the things in MBs. File myFile = new File(directory_name). One of them is String [ ] list( ). if (myFile. If you wish to deal with the directories then you can use the list() method.324 Dealing with directories A directory is a collection of files and directories. if (f1. i < s1.out.isDirectory()) { System. } else .isDirectory()==true) { System. Let¶s have program! Example 9 import java. for (int i=0.io. i++) { File f1 = new File(directory_name + "/" + s1[i]). This method is over loaded.File.length.println ("Directory of´ + directory_name).println(s1[i] + " is a directory"). String s1[] = myFile.out.list (). class DirectoryList { public static void main(String args[]) { String directory_name = "/Minerva". In java directories are also treated as files. When list() method is invoked by the directory object(created through File class constructor) then list of other files and directories extracted from it. } } } Output is straight forward.io.println("created a directory").out. if(myFile. Example 10 import java.325 { LIBRARY } } } else { System. Method names clearly indicate what are their task. System. The following example the usage of this method.println ("Unable to create a directory").mkdir()==true) System.println(s1[i] + " is simply a file!!").*.println(directory_name + " is not a directory"). .out.out. else System.out. public class File5 { public static void main(String args[]) throws IOException { File myFile=new File("c:/Alice/wondeLand"). boolean mkdir ( ) Method This method is used to create a directory and returns a boolean indicating the success of the creation. String name) { return name. it is used to filter out the required files from a directory. Example-11 import java. public File4(String w) { this. public class File4 implements FilenameFilter { String w."+w. 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.*. The other over loaded form of public String[ ] list(FienameFilter FilterObj) method In this form of list() method. } public static void main(String args[])throws IOException . } public boolean accept(File dir.w=".326 } } If the mkdir() method is executed successfully the boolean true value is returned else the method is going to return false.io.endsWith(w). filter out the required files. In side accept() method endsWith() method is invoked.327 { for (int p=0.list(only) .println ("printing files with "+args[p]+" extesion in the "+f1. System. data flows from source to destination through the channels in java.println(s[i]).out. this method implicitly invoke the accept() method. FilenameFilter only=new File4(args[p]).getPath()+" directory") . Like water flow in a pipe. Diagram 1 .i<s. Use of Streams What is a stream? Stream means a channel or pipe.out. for(int i=0. String s[]=f1.p++) { File f1 = new File("e:/cobra/applet"). } } } In this program when I have invoked the overloaded list() method.p<args.e.length.length. Entire operation performs only one thing i.i++) System. 328 . Reader class objects reads and Writer class writes the data in the form of characters.329 These channels are the object of various stream classes provided by Java. Let¶s have a hierarchy structure of stream class. Java provides two types of streams input stream & output stream. Java provides two ways to perform read & write operations. . 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. 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. an interface for useful mark( ). markSupported( functionality to the ). read( ). read( ). memory to be used as mark Supported( ). from a file. insert( ). By the help of these InputStream system directly read the data from file and buffer in byte format. close( ).finalize(). close(). reset( ). read( an Input Streams ). Class ByteArrayInputStream Function Supported methods Allows a buffer in available( ). mark( ). skip( ) For reading information available( ).330 With the help of the table you see various InputStream and their functions. FileInputStream FilterInputStream . skip() Abstract class providing available ( ). skip( ) other Input Stream classes. The first constructer takes the name of the file as a String argument FileInputStream f = new FileInputStream( ³c:/java/temp. an interface for useful write( ) functionality to the other Output Streams classes write( flush( ). ). Class ByteArrayOutputStream Function Creates memory a buffer Supported methods in reset( ). 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. FileInputStream FileInputStream is a class that helps to read the data from a file. ). size( ). the streams is placed in writeTo( ) this buffer. . FileOutputStream Abstract class providing close( ). Whereas Low-level output streams have methods that are passed bytes and write the bytes as output. Low-Level Stream Low-level input streams have methods that read input and return the input as bytes. There are two types of constructors available with this class.exe´ ).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. toByteArray( All the data we send to toString( ). The two types of constructors are applicable to this class. Example -12 import java.exe´).exe´ ). FileOutputStream The FileOutputStream class helps to create a new file and write data into in byte format. The second constructor takes File class object as an argument File f = new File ( ³c:/java/temp. FileOutputStream f1=new FileOutputStream(f). FileInputStream f1=new FileInputStream(f). In case of FileOutputStream if the programmer writes the data into a read-only file then the program generates IOException.*.exe´). The first constructer takes the filename as a string argument FileOutputStream f = new FileOutputStream( ³c:/java/temp.332 The second constructor takes the File class object as an argument File f = new File ( ³c:/java/temp. public class ReadWriteFile { public static byte get( )[] throws Exception { .io. i<size."). for (int i=0. System.out.println("enter the text. } f.close ( ) .out. } return in.i<50.out.in.write(input[i]). int size.i++) { f.out.i++) { in[i]=(byte)System. for(int i=0.println("only 50 bytes of data is stored in the array ").available ( ) .println("reading contants of file write.println ("press enter after each line to get input into the program").333 byte in[]=new byte[50].read( ). System.i<50. FileOutputStream f=new FileOutputStream("c:/java/write. System.txt").i++) { .txt"). Text"). for (int i=0. size=fl. FileInputStream fl=new FileInputStream("c:/java/write. } public static void main(String args[])throws Exception { byte input []=get( ) . System. 334 System. ByteArrayOutputStream ByteArrayOutputStream class implements a buffer. int off.out. It has two types of constructors. The size of the buffer increases as data is written into the stream. 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. } } ByteArrayInputStream This class uses a byte array as its input source.print((char)fl. . which can be used as an OutputStream. } f. The first one takes a byte array as its parameter.read ( )) .close( ) . constructor programmer takes the input from the specified array of ByteArrayInputStream b=new ByteArrayInputStream (byte buf []. ByteArrayInputStream b = new ByteArrayInputStream(byte buf[]) through this bytes. println("Accepted characters in the array"). public class ByteArray { public static void main(String args[])throws Exception { ByteArrayOutputStream f=new ByteArrayOutputStream(12).out. Two types of constructors exist. These methods return void and throw an IOException on error conditions. byte b[]=f. } System.out. They are given below: ByteArrayOutputStream o = new ByteArrayOutputStream () This creates a buffer of 32 bytes to stroke the data. System.out.length. i<b. System.println("displaying characters in the array").i++) { .read( )).*.println("enter 10 characters and press the enter key"). for(int i=0.in.out.toByteArray( ).write(System.io.size( )!=10) { f. while(f. ByteArrayOutputStream o=new ByteArrayOutputStream (int size) The above constructor creates a buffer of size int. System.335 The data is retrieved using the methods toByteArray() and toString(). Example-13 import java.println("These will be converted to uppercase and displayed"). print(Character.i++) { while ((c =inp. int c.336 System.out.println("Converted to upper case characters").out.println().i<1.out. for (int i=0. System. } } } .read( )) != -1) { System.println((char)b[i]).toUpperCase ((char)c)). inp.out. } System.reset(). } ByteArrayInputStream inp=new ByteArrayInputStream (b). txt"). This class is used to sequentially read the data from two input sources.txt").int buffer.*. SequenceInputStream int ch.fis2). new InputStream) Methods available:public int read()throws IOException public int read(byte b[].io.337 SequenceInputStream SequenceInputStream is the child class of InputStream. public class Sequence { public static void main(String args[]) { try{ FileInputStream fis1=new FileInputStream("c:/a. int size)throws IOException public void close()throws IOException public int available()throws IOException final void nextStream()throws IOException . .read())!=-1) { s =newSequenceInputStream(fis1. FileInputStream fis2=new FileInputStream("c:/b. while((ch=s. Constructor:SequenceInputStream (new InputStream. Example:-14 import java. printStackTrace().printStackTrace(). fis2.close().print((char)ch). s.close(). } catch(IOException ie) { ie.out. }catch(FileNotFoundException fe) { fe.338 System.close(). } } } Output:- . } fis1. DataInputStream. named as:- Class DataInputStream Function Supported Methods Used in context with read(). readShort( ). write( ). writeFloat(float f ). readLong ( ). PushbackInputStream Has a one-byte pushback available( ). writeInt(int i ). mark( ). Hence we can write primitives (int. Hence readByte( ). readFloat ( we can read ). long. skipBytes( ) BufferedInputStream Use this to prevent a available( ). FilteredOutputStream class having the child classes BufferedOutputStream. DataouputStream. writeDouble(double d). readLine ( ). read( more data is needed ). reset( ). readBoolean(). Primitives (int.) from a stream in a ). . unread( character read can be ). char.339 FilterInputStream class having the child classes named as :-BufferedInputStream. mark( ).) to a stream Supported Methods flush( ). PrintStream . physial read every time markSupported( ). writeBoolean(boolean b). buffer. so the last reset( ). etc. size( ). readInt( etc. Class DataOutputStream Function Used in context with DataInputStream. read( ). readFully ( ). char. long. PushbackInputStream. markSupported( ) pushed back. portable fashion. DataOutputStream. writeLong( long l). skip( ). 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. setError( ). PrintStream etc.340 in portable fashion. write( ) physical write every time we send a piece of data. This is used to prevent a flush( ). This class Constructor is overloaded. PrintStream handles display. println ( ). . ObjectOutputStream. DataInputStream and ObjectInputStream etc. close( ). print( ). BufferedOutputStream. write( ).int bufsize). BufferedInputStream bis = new BufferedInputStream (InputStream is). Creates a buffered input stream with a 2048 byte buffer. High-level input streams are BufferedInputStream. The default size of the buffer is 2048 bytes. The BufferedInputStream class maintains an internal array of characters in which it buffers the data it reads from its source. High-level output streams are DataOutputStream. DataOutputStram handles the storage 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. BufferedInputStream bis=new BufferedInputStream(InputStream is. output. Chunks of bytes from the buffered array can be chosen and read. 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. While flush( ). PrintStream writeShort( short s) For producing formatted checkError( ). int Creates a buffered output stream with a buffer of bufsize bytes. 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). This class Constructor is overloaded.341 Creates a buffered input stream with an internal buffer of bufsize bytes. If the bufsize is less than 0 then it throw IllegalArgumentException. If the bufsize is less than 0 then the program is terminated by throwing IllegalArgumentException. char array and String by the help of some predefined methods. Creates a buffered output stream with a default 512 byte buffer. which acts as a cache for writing. . Data written in the buffered output stream will continue until unless the buffer is full. BufferedOutputStream b= new BufferedOutputStream (OutputStream os). BufferedOutputStream The output is stored in a buffered array of bytes. BufferedOutputStream bufsize). b=new BufferedOutputStream(OutputStream os. DataInputStream The DataInputStream class reads bytes from another stream and translate them into java primitives. A set of methods exists in this class to write the data to the output source in any primitive data types format. class Demo{ public static void main(String[]args)throws IOException { DataInputsteream din=new FileOutputStream fout=new DataInputsteream (System.txt´). . See the example Example 15 import java. 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.342 DataOutputStream DataOutputStream class supports the writing of java¶s primitive data types to an output sources.io.*.in). FileOutputStream(³myFile. write(ch).txt´. . } } System.out.println(³Press # to save & quit the file´). Next fout is an object of FileOutputStream class. fout. Next the write() method is invoked & the stored value in ch is moved to myfile.in represents the standard input device i. It is connected to the output file myFile.true).out println(³Press # to save & quit the file´). It also behaves like a channel.in). read() method reads the data from keyboard through the channel named din & the returned character value is saved in the character variable ch. So I have to make some change in the above program to append a file. System. All these operation continues till # is pressed by the user.txt through the out put channel object fout. This is what we call a channel or stream. din is an object of DataInputStream class. while((ch=(char)din.txt to write something more at the end then the previous data will be lost. char ch.*.close(). Then finally close() method is invoked to close the operation & save the file.343 System. Now din is connected to keyboard. Inside while loop read() method is invoked through the object din.e. If I am again use the file myFile.read())!=¶#¶) fout. FileOutputStream(³myFile.txt. class Demo{ public static void main(String[]args)throws IOException { DataInputsteream dIn=new FileOutputStream fout=new DataInputsteream(System. Example 16 import java. How to append a file. is key board.io. char ch. class Demo{ public static void main(String[]args)throws IOException { DataInputsteream dIn=new FileOutputStream fout=new DataInputsteream(System. Example 17 import java. is written to the file & each time in the back ground appropriate system call is made to do the operation. System. 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. while((ch=(char)din. BufferedOutputStream br= new BufferedOutputStream(fout).*.read())!=#) .344 char ch.e.txt´).close(). This boolean true value opens the file in the append mode.out println(³Press # to save & quit the file´). fout.io. } } See the extra parameter passed in the constructor of FileOutputStream. Use of BufferedOutputStream: To improve the performance we have to use the buffered output stream. This involves a lot of over head.in). the question how the performance is going to be improved? In the above program each time when a character is read from keyboard. But.read())!=#) fout. FileOutputStream(³myFile.write(ch). while((ch=(char)din. What else we can do? We can create a buffer i. 3: create a buffer & attach it to output stream BufferedOutputStream br= new BufferedOutputStream(fout) 4: read from key board by the din. then IOException will be generated.write(ch).io. Reading a file Data stored in a file can be read by the use of FileInputStream object. class Demo{ public static void main(String[]args)throws IOException { . bout.*.read() method. } } br is an object of BufferedOutputStream. Steps to be remembered: 1:Create an input stream object & connect it to keyboard by DataInputsteream dIn=new DataInputsteream(System.in).txt´).345 bout. so the characters entered from keyboard is store in the temporary buffer br until the buffer is filled or # is pressed. Once input operation is completed then write() method is invoked by bout to write the entire data in to the file at once. one thing if the programmer does not mention the size of the buffer explicitly then the default size id 512 bytes. 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. Yes. 5:write to the file by bout. Now the read method is invoked through the br.close(). It is buffer or a chunk of memory attached with fout. If the buffer is full & user still entering the data. object by Example 18 import java.write() method. . } } FileInputsteream(³myFile1.txt´). class Demo{ public static void main(String[]args)throws IOException { FileInputsteream dIn=new FileOutputStream fout=new int ch. Example 19 import java.io. fout. fin is an object of FileInputStream.print((char)ch). while((ch=(char)fin.txt´). while((ch=fin.close().out. FileInputStream(³myFile. fin.*.346 FileInputStream fin=new int ch.write((char)ch).read())!=-1) System. Coping the content of one file to another. It is simply an input channel connected to myFile. } } Java detects the end of file when it encounters -1. stored it in ch & then displayed on the monitor. data is read from the file through the channel fin. FileOutputStream(³myFile2.txt´).close(). This process continues till -1 is encountered. When read method() is invoked by fin.txt. At the end of every file to indicate the end of file OS stores -1.read())!=-1) fout. Use of BufferedReader to improve performance Example-20 import java.out. } BufferedReader br=new BufferedReader(fin).print((char)ch).read())!=-1) System. . }catch(FileNotFoundException e){ System.txt´).txt 7 through fout data is written in to myFile2.out.´) return.io.close ().347 Codes are straight forward through fin data is read from myFile1. while((ch=br. int ch. } } Here in this program I have used the BufferedReader to improve the performance. class Demo{ public static void main(String[]args)throws IOException { try{ FileInputStream fin=new FileInputStream(³myFile.println(³file does not exists.*. fin.txt. toUpperCase ( )).txt"))).close(). o. String line. System.348 Example-21 import java.txt")). DataOutputStream o=new FileOutputStream("C:/temp1.*. } d. o. The output appears as shown below: DataOutputStream (new .readLine())!=null) { String a =(line. while ((line = d.writeBytes(a+"\r\n").close(). public class DataStream { public static void main(String args[])throws IOException { BufferedReader d=new BufferedReader(new InputStreamReader(new FileInputStream("c:/temp.out.txt´ file contains the line ³Learn java as it is an object oriented language´ as its content.println(a).io. } } Suppose the ³temp. Serialization is a technique that is required when the programmer want to save the state of the object in a persistent storage area. In other wors serialization is a technique of storing object contents into a file. By the help of the ObjectInputStram programmer read the object from a stream.out. Static and transient variables are not serialized.Serializable interface is an empty or marker interface without any members in it. This is done without disturbing the InputStream.349 PushbackInputStream This class is used to read a character from the InputStream and return the same. Constructor:PrintStream(String s) PrintStream(OutputStream os) PrintStream(OutputStream os. The two methods that are very familiar to us system. as if it had not yet been read. Marking interface is useful to mark the object of a class for special purposes.println( ) and system. Later on programmer restore the objects by using the process deserialization. . This methods of this class are widely used in Java applications.print ( ). This class allows the most recently read byte to be put back into the stream. Deserialization is the process of reading back the object from the file. Primitives are converted to character representation.out. Constructor:- PushbackInputStream(InputStream is) PushbackInputStream(InputStream is.int size) PrintStream This class is used to write text or primitive data types.boolean b) Serializalization Serialization is the process of writing the state of an object to a byte stream. Constructor is ObjectOutputStream(OutputStream out)throws IOException Through the out object the serializable objects are written in the Output sources. void close() int read() Object readObject() long skip(long n) ObjectOutputStream class is used to write objects to a stream. Returns the Object from the invoking Stream. Closes the invoking String. . Methods int available() Description Returns the number of bytes that are available in the input sources. Skip n number of bytes from the input sources. Return the integer representation of the next available byte of input.350 Constructor is ObjectInputStream(InputStream in) throws IOException Through the object in the serialized objects should be read. this. transient int k. void writeObject(Object obj) Example-22 import java.i=i. this.int j.io. } } public class Serial { public static void main(String args[]) .*. Writes an array of bytes to the invoking Stream Writes Object obj to the invoking stream. class Ex1 implements Serializable { int i.j=j.j.351 Method void close() Description Closes the invoking stream.k=k.int k) { this. void show(int i. void flush() void write(byte b[]) Finalizes the output sources. FileOutputStream fos= new FileOutputStream("c:/s1.352 { try{ Ex1 e1=new Ex1(). e1. oos.println("Data Is "+e2.j+"\t"+e2. }catch(Exception e) { e.txt").show(20. System.readObject(). FileInputStream fis=new FileInputStream("c:/s1.40).k).printStackTrace().out.30.txt") ObjectInputStream ois=new ObjectInputStream(fis) .i+"\t"+e2. Ex1 e2=(Ex1)ois. Output:- .writeObject(e1). } } } . ObjectOutputStream oos= new ObjectOutputStream(fos). TT_EOF) { if(tok==input.nextToken())!=input. count++.txt"). } System.println ("found "+count + " words in temp. while((tok=input. 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.out. StreamTokenizer input=new StreamTokenizer(fr).txt").*.println("word found :" +input.TT_WORD) System.out. int tok. } } .io.353 StreamTokenizer Java provides in built method for pattern matching from the data those extracted from input stream.sval). int count=0. public class wordcounter { public static void main(String args []) throws IOException { FileReader fr=new FileReader("c:/temp. Reader Class Some of the subclasses of reader class are: . If the token is a simple character then ttype contains the value of that character. Japanese. If the element is end of line then ttype is equal to TT_EOL. Ttype is equal to TT_WORD if nextToken() method recognizes the element as word. Reader and Writer Classes The difference between readers and input stream is that while readers are able to read characters. Similarly when end of file is reached ttype is equal to TT_EOF. it is possible to write Java programs in languages like German.354 StringTokenizr define four integer fields named TT_EOF. There exists another variable ttype. If the element is a nuber then ttype is equal to TT_NUMBER. Following section deals with a few subclasses of reader and writer classes. Input streams read bytes. TT_EOL. French. the token recognizing variable. This increases the power of the java iosteream classes by being able to read any character and thus enabling internalization. etc. TT_NUMBER & TT_WORD. 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. To say it in simple terms. 355 Reader BufferedReader CharArrayReader FilterReader InputStreamReader PipedReader LineNumberReader StringReader FileReader PushbackReader FileReader The FileReaer class enables reading character files. CharArrayReader The CharArrayReader Allows the usage of a character array as an InputStream. The constructor is given below. The constructor is given below: public InputStreamReader (InputStream istream) FilterReader . int num) InputStreamReader The InputStreamReader class reads bytes from an input stream and converts them to characters according to a mapping algorithm. The usage of CharArrayReader class is similar to ByteArrayInputStream. public FileReader(File f) This constructor can throw a FileNotFoundException. It uses default character encoding. The default mapping identifies bytes as common ASCII characters and converts them to Java¶s Unicode characters. The constructor is below: CharArrayReader(char c[]) CharArrayReader(char c[]. The constructors are identical to those of FileInputStream class. FileReader class usage is similar to FileInputStream class and its constructors are identical to those of FileInputStream class. int start. The constructor is given below and it can throw an IOExeception. which is a protected reference to the reader that is being filtered. 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. The usage of FileWriter class is similar to that of FileOutputStream class.*. Protected FilterReader (Reader r) BufferedReader BufferedReader class accepts a Reader object as its parameter and adds a buffer of characters to it.356 The FilterReader class allows the reading of filtered character streams. designed for Unicode: FileWriter The FileWriter allows wrting character files. There is one instance variable in. public FileWriter (File f) Example-24 import java. It uses the default character encoding and buffer size. This class is mainly useful because of its readLine ( ) method. public class FileRead { public static void main(String ars[]) .io. FileWriter fw=new FileWriter("File1.write(c). } } } Output:- CharArrayWriter This class uses character array as the OutputSource.println("Read The Data From The File").close(). CharArrayWriter() CharArrayWriter(int num) PrintWriter .out. String s=br.readLine(). } fr.print((char)ch).toCharArray(). fw. System.out. System.close().read())!=-1) { System.in)). }catch(Exception e) { e. int ch. FileReader fr=new FileReader("File1.println("Enter The Text").txt").printStackTrace().txt"). char c[]=s. The constructor of the class is overloaded. fw.357 { try{ BufferedReader br=new BufferedReader( new InputStreamReader(System. while((ch=fr.out. while((s1=in. protected Filter(Writer w) BufferedWriter The BufferedWriter class buffers data to the character output stream. String s1="". FilterWriter The FilterWriter class is used to Write filtered character streams. int c. public class ReadWrite { public static void main (String arge []) { try { BufferedReader in=new BufferedReader(new FileReader(arge[0])). BufferedWriter class functionality is the same as BufferedOutputStream class The constructor is: public Buffered (Writer w) Example-25 import java.print((char)c).out. which is a protected reference to the Writer that is being filtered.out.println("printing individual1 charcters of the File"+arge[0]).readLine())!=null) . The constructor is: public PrintWriter ( OutputStream ostream ) The stream is not flushed each time the printIn( ) method is called.readLine())!=null) System.read())!=-1) System. StringReader in2=new StringReader(s2). while((s1=ind. System. It can be used instead of PrintStream. while((c=in2.io.txt"))).out.println(s1). PrintWriter p=new PrintWriter(new BufferedWriter(new FileWriter("demo. String s2="Learn Java".*. It has one instance variable out.358 The PrintWriter class contains methods that makes the generation of formatted output simple. BufferedReader ind=new BufferedReader(new StringReader(s2)). *. ind.io. }catch(Exception e) { e.println("output "+s1). class Demo{ public static void main(String[]args)throws IOException { String data=´On this planet\n Life is like ships in the harbor!!! ´ . FileReader & FileWriter class is performs the read & write operation by characters. in.close().close(). in2.close(). Example-26 import java.close().359 p. Program to write something in to a file. p.printStackTrace(). } } } Use of FileReader & FileWriter class. close(). }} - .360 FileWriter fw1=new FileWriter(³myFile.charAt(i)).out.println(³file does not exist´).txt´).out.*.i<data.close().io.read())!=-1) System. } } Reading from a file by FileReader Example-27 import java. class Demo{ public static void main(String[]args)throws IOException { try{ FileReader fr1=new Filereader(³myFile. for(int i=0. }catch(FileNotFoundexception e) { System. fw1. } int ch.txt´).length().write(data. return. while((ch=fr1.println((char)ch).i++) fw1. fr1. I am going to explain the most frequently used & important classes their methods present in this package. ProcessBuilder. This class is used to create the object of primitive data-type boolean. Process. interfaces & methods available in this package. InheritableThreadLocal.361 Chapter-22 Exploring The java.lang Appendable. ThreadLocal. Throwable.lang package has following classes: Boolean. CharSequence.Subset. Compiler. Math. Float. Thread. This class is enclosed by the Wrapper class Character. Character. Character. Character. Various classes present in java. Readable. You do not import this package to use the classes. Byte. SecurityManager. Enum. Cloneable. Number. ThreadGroup. This class is used to create the object of primitive data-type byte. Package. Short. ClassLoader. StringBuffer. This class is used to create the object of primitive data-type byte.lang package & it is also beyond the scope of this book.Subset extends Object. In fact this is the package that is widely used all java programmer.Subset This class is static inner class. StringBuilder. This class is explained in the chapter Wrapper class. RuntimePermission. Integer. This class is explained in the chapter Wrapper class.lang Package java. The signature of this class is public static class Charcter. Long. Interfaces present in java. This class is explained in the chapter Wrapper class.UnicodeBlock. Boolean This is a wrapper class. Iterable. StrictMath. Void.Unicode . Comprable. Double. It is not possible to explain each class & methods present in java.lang package Java. Charcter. Runtime. This class extends the Object class. StackTraceElement. System. String. Runnable. Character. Character This is another Wrapper class.. Object. Class. Byte This is another Wrapper class.lang is the fundamental package that is available to the programmer by default. Class The class Class extends the object class & implements the Serializable interface.getName()). just like creation of object. This method getClass() originally belongs to the Object class & is over-ridden in this class Class.getClass(). There is another method getSuperClass().out. This class extends the Character. Let¶s have an example class Demo { public static void main(String[]args) { Class cl="Hello World". whose object has invoked it.getClass(). Its outer class is Character. This class is a final class. System. System. Actually java implements these arrays as the reflection of the object of class Class.362 This class is also a static inner class. The getClass() method returns the name the class. First the getClass() method is invoked by he String object. In java all the arrays including arrays of primitive data types are created by the invocation of the new operator.String out is an object of java. You can create the object of this class by the invocation of getClass() method. Hence cl holds the String class.println("out is an object of "+cl.io.out. This class can not be extended since it is declared with final keyword. This class is instantiated only by Java Virtual Machine during the process of class loading by the invocation of the defineClass() method.out.Subset class. This class is generic in nature. now getName() method simply shows the name of the class that is held by cl. It does not contain any public constructor. The getClass() & getName() methods: the two methods are invoked together to determine the class name of an object. hence can not be extended. As I have said object of the class Class can not be created directly. cl=System. } } Output: The string is an object of java. Now lets find out what is the class name to which arrays of primitive data types in java belongs to class Demo { . which is used to determine the current super class of the class held by the reference variable of class Class.getName()).lang.PrintStream In this above program cl is a refernce of class Class.println("The string is an object of "+cl. Next symbol µF¶ indicates mak is an array of float of single dimension.newInstance(). public static void main(String[]args) throws InstantiationException. Class cl=mak. } } Output: 10 forName() method is a static method.ClassNotFoundException { X b=new X(). X a=(X)cl.println(cl. If mak would be two dimensional array then initial symbol would be ¶[[µ. } } Output: [F Foxed! With the out put.forName("demo.println(a.X"). It¶s signature is . there fore it has to be invoked by it¶s class name Class. 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.out. System.i).getClass().IllegalAccessException. package demo. System.out. The µ[µ indicates that mak is an array. class X{ int i=10. Class cl=Class.getName()).363 public static void main(String[]args) { float mak[]=new float[8]. } class Demo { int i=10. ClassLoader ClassLoader is a abstract class which extends the Object class. IllegalAccessException Therefore this method has to be invoked inside a try block followed by a catch block or by the use throws keyword. This class is explained in the chapter Wrapper class. The class ClassLoader is used to create the user defined class loader. This class is used to create the object of primitive data-type byte. This class can not be extended. Enum class This class is used to create the Enum object.class file is created. This class is used to create the object of primitive data-type byte. This class is used to create the object of primitive data-type byte. Float This is another Wrapper class. This class is explained in the chapter Wrapper class. Integer This is another Wrapper class. the method newInstance() can invoked to create the object of the class that is held by cl. the boot strap class loader is responsible for loading the class in to the memory. Enum members are simple constants. 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. Boot strap class loader is an component of Java Virtual Machine. Double This is another Wrapper class. Compiler class When you compile a java source file . This class is explained in the chapter Wrapper class. Process class & Runtime class These two classes are closely entangled with each other. in java a class is loaded in to the memory either by boot strap class loader or by user defined class loader.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 class is used to create the object of primitive data-type byte. This class extends the Object class. Long This is another Wrapper class. Rarely a java programmer requires an user defined class loader. This class is explained in the chapter Wrapper class. But. By the use compiler class native executable files can be generated from java source file. This method returns the Class object that holds the class supplied as a string argument to this method. Java programmer use these two classes frequently to develop system level applications. When a class file is executed by javac command. This cass is rarely used by the java programmer. The signature of newInstance() method is public Object newInstance() throws InstantiationException. The object of a Runtime class contains the current system environment.freeMemory(). long Initial. For this purpose normally the exec() method of Runtime is used. //This method retuns the amount of free memory available. } class Demo { public static void main(String[]args) { Runtime rt=Runtime. All the methods present in this class is abstract class. System. A Process object embeds a process in to it. It is a static method.println("Available memory after the creation of object: "+Final). they do miss the sizeof operator quite a lot. Java does not provide the sizeof operator but.println("Available free memory: "+s).println("Available memory initially: "+Initial). Final=rt. Since they all are migrated from C/C++. Since it is an abstract class you can not directly create the object of Process class.Final. System.freeMemory().out.freeMemory()).365 First of all Process is an abstract class. The signature of the Process class is : public abstract class Process extends Object.gc(). X mak[]=new X[10000].out. package demo. rt. Initial=rt. Normally while training new comers in java a usual question from their side is how to measure the size of an object in java. System. Hence it is invoked by the class name Runtime.getRuntime().out. System. } } 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. Determining the size of primritive data type char . long s=(Initial-Final)/10000. you can determine the size of an object through various methods available in Runtime class.println("Available free memory:"+rt. //gc () method is used to invoke the garbage collector. class X{ int i.out. To instantiate Runtime class you have to invoke the getRuntime() method. Initial=rt. System. . Final=rt.Final.out. long Initial.Final. Final=rt.366 class Demo { public static void main(String[]args) { Runtime rt=Runtime.freeMemory(). Initial=rt. } } Output: Size of the object is 8 Use of exec() method to execute system dependent application. } } Output: Size of the object is 4 To get the size of double class Demo { public static void main(String[]args) { Runtime rt=Runtime.println("Size of the object is "+s).freeMemory().getRuntime(). long s=(Initial-Final)/10000. long s=(Initial-Final)/10000. int mak[]=new int[10000]. } } 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. long s=(Initial-Final)/10000. System. char mak[]=new char[10000].println("Size of the object is "+s). Final=rt. Initial=rt.freeMemory(). Suppose we are in a window system then the bellow codes will open ms paint for you.out.freeMemory(). long Initial.Final. long Initial.println("Size of the object is "+s).freeMemory(). package demo. double mak[]=new double[10000].freeMemory().getRuntime(). System.getRuntime().out. } } Output: The System class .getRuntime(). Process p=rt.367 class Demo { public static void main(String[]args)throws Exception { Runtime rt=Runtime.exec("mspaint"). name")). This method is a static method. } if(s.lang package.println(S). class Demo { public static void main(String[]args) { String S=System. public class Os { public static void main(String args[]) { String s=new String( System. } } Output: Windows XP This particular method can be used to create single class file which will operate in different plat form differently.equals(³Windows XP´)) { p=r.getProperty("os.equals("Linux")) { p=r. Some of the examples will fix your idea. I have run this program in windows platform see the output: . System. Runtime r=Runtime. The getProperty() method This method takes various types of environment properties defined by the java. it will open the note pad & if in Linux platform it will open the gedit.368 This class contains a large number static methods & variables.out.exec("notepad"). try { if(s. You can not create the sub class of System class. Hence can only be invoked through class name Determining the Os in which you are working package demo. Process p=null. } } catch(Exception ie) {} } } If you run this program in windows plat form. You can not crate the object of System class.exec("gedit").name").getProperty("os.getRuntime(). you do it by loop. mak.'t'.'o'.'e'. package demo.i++) System. 0.'s'.'g'. class Demo { public static void main(String args[]) { char mak[]={'r'.arr. .length. This process can be completed by the use of arrayCopy() method in a more efficient way.369 The arrayCopy() method When you copy an array.'l'.'r'. char arr[]=new char[mak. 0.'o'.length).'n'}.'o'.'g'.out.i<arr.' '.arraycopy(mak.'s'.'a'.'i'.'s'.'e'. System.print(arr[i]).length]. for(int i=0.' '.'s'. 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 . whenever we access the variable with the get() method for the first time the initialValue() method is called implicitly. then ThreadLocal variables are used. It is not going to reflect in any other thread. 3rd one is the name of the destination array. Below given is the structure of ThreadLocal<T> class defined in java. Whenever programmer feels that some data should be unique for the thread and the data should not be shared. 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. public void set(T value) .370 }} Output: root less aggression this method takes the source array as its 1st argument. public T get( ). } protected T initialValue() it returns the intial value for the ThreadLocal variable of the current thread . public void remove( ). public T get() it returns the value of the copy of the thread-local variable present in the current thread.lang public class ThreadLocal<T> { protected T initialValue( ). public void set(T value). 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. next argument is the position from which the source has to be copied. The ThreadLocal class The ThreadLocal variables are typically declared as private and static. If the set() method is invoked prior to the get() method then the initial value method will not invoked. out. System. System.getName() + " has thread number " + threadnumber. threadnumber.currentThread().get()).currentThread().out.get()). System.get()).getName() + " has thread number " + threadnumber.get()). class ThreadLocalDemo1 extends Thread { private static int number = 0.currentThread().out.out. } }.println("Thread " + Thread.set(5).out.println("Thread " + Thread.getName() + " has thread number " + threadnumber. private static ThreadLocal threadnumber = new ThreadLocal() { protected synchronized Object initialValue() { return number++.get()).getName() + " has thread number " + threadnumber.currentThread(). threadnumber. } public static void main(String[] args) { .remove().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.println("Thread " + Thread.getName() + " has thread number " + threadnumber.remove().371 it sets the copy of the thread-local variable of the current thread to the specified value. public void run(){ System. System.currentThread(). number++.println("Thread " + Thread. threadnumber.println("Thread " + Thread. public void remove() it removes the value of the ThreadLocal variable. t2.To clone an object.start(). Thread t2 = new ThreadLocalDemo1(). is used to create the clone of an object.lang package. The signature of the clone () method is: protected native Object clone() throws CloneNotSupportedException According to the specification. } } 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.start(). t1. a class must implement the interface Cloneable and then invoke the clone () method of object class. .372 Thread t1 = new ThreadLocalDemo1(). the clone () method returns the reference of the Object class. The signature of Cloneable interface is: public interface Cloneable { } The Cloneable interface does not contain any method of its own. System. String c) { roll=i. name=c.373 Example:- public class LetsClone implements Cloneable { int roll. } public static void main(String ar[]) throws CloneNotSupportedException { F obj=new F(10."pinku").clone().println(ob.out. String name=new String(). F ob=(F)obj.println(ob.out.roll).name). } } Output: 10 pinku . F(int i. System. .EventListener To clone one object.io. 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. Actually implementing the marker interface programmer implicitly let the JVM to know that a specific operationnis going to be performed.e. Many of its methods are over ridden in different java in built classes according to their purpose. a marker interface) to facilitate the class with the ability for cloning it objects.72) and PI (~3. their implementation is a must. But.374 The Cloneable interface is a marker interface.util. The marker interfaces present inside java are:  Java. It contains two double constansts: E(the exponential c constant) (~2.14). But for certain operations.lang. boolean equals(Object eq) this method is explained in detail in String chapter. we need to implement the Cloneable interface (i. A marker interface is an interface.Cloneable  Java. Class getClass() Already explained earlier in this chapter. Methods present in Object class:Object clone() I have used this method in creating clone of an object. This is explained in detail in class fundamental.Serializable  Java. Reader can go through them. Object class:In java Object class is the super class of all the classes. the clone() method of the Object class is needed. This method belongs to Object class. which does not have its own method. void finalize() This method is called before an object is garbage collected from heap. Math class The Math class contains various methods that are usefull scientific & engineering applications. It returns the sine value of the supplied angle public static double cos(double dbl) This method is a static method. This argument is the measurement of an angle in radian. It takes a double variable as its argument. This argument is the measurement of an angle in radian. cos(dbl2) ). hence can only be invoked by class name. It takes a double variable as its argument. } } Output: The angle in radians is : 30.toRadians (dbl1).println(" sine of ³+dbl1+´ is : "+ Math. This argument is the measurement of an angle in radian. hence can only be invoked by class name. hence can only be invoked by class name. It takes a double variable as its argument.375 Methods in Math class:public static double sin(double dbl) This method is a static method. System.out. It takes a double variable as its argument. This argument is the cosine value of an angle.out. It returns the angle in radian. It returns the cosine value of the supplied angle. This argument is the sine value of an angle.println(" The angle in radians is : " + dbl1). public static double tan(double dbl) This method is a static method. System.println(" tangent of ³+dbl1+´ is :"+ Math.0 sine of ³+dbl1+´ is : 0. It returns the tangent value of the supplied angle.out. See the below exapmple public class Arithm1 { public static void main(String arg[]) { double dbl1= 30. System. It takes a double variable as its argument. double dbl2 = Math. 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.49999999999999994 cosine of ³+dbl1+´ is : 0.5773502691896257 public static double asin (double dbl) This method is a static method.println(" cosine of ³+dbl1+´ is : "+ Math. sin(dbl2) ). Range is in between 0 to Ⱥ . System. hence can only be invoked by class name. It returns the angle in radian.8660254037844387 tangent of ³+dbl1+´ is :0.out.tan(dbl2)). toDegrees(1.out.out.5 is :0. atan2(30.println("The angle for which the cosine Value is : " + Math. It returns the angle in radian.5235987755982989 The angle for which the cosine Value is : 1.println("Degree value is:"+Math.out. System.println("the radian value is :"+Math.30. public static double toDegrees(double dbl) This method is a static method. It returns the equivalent angle in degree.5 is :"+Math. System.00)).println("Enter Value is :"+dbl). System. System.asin(dbl)).5. acos(dbl) ).out. It takes a double variable as its argument.376 public static double atan (double dbl) This method is a static method. hence can only be invoked by class name. It returns the equivalent angle in radian.println("Tangent value of two parameters is: "+Math.0)) .00.571)) . It takes a double variable as its argument. System.5 The angle for which the sine value is 0.out. toRadians(90.out. It takes a double variable as its argument.0471975511965979 The angle for which the tangent Value is : 0. This argument is the measurement of an angle in degree. } } Output: Enter Value is :0. This argument is the tangent value of an angle.println("The angle for which the tangent Value is : " + Math. System. hence can only be invoked by class name.atan(dbl) ).println("The angle for which the sine value is 0.out. class Demo { public static void main (String arg[]) { System. hence can only be invoked by class name. . Range is in between 0 to Ⱥ public class Arithm2{ public static void main(String arg[]) { double dbl=0. This argument is the measurement of an angle in degree.4636476090008061 public static double toRadians(double dbl) This method is a static method. This argument is the tangent value of an angle.println(" The log value is :"+Math.e. the result is NaN.¶ dbl¶ as the parameter.out.0)).01166961505233 Tangent value of two parameters is: 0. the sqrt method has only one double value ¶dbl¶ as the parameter and it returns the square root of the given value µdbl¶. double dbl2) This method used to calculate the remainder operation on two arguments.e. When the argument is NaN or less than zero .00)).5553480614894135 The Exponent value is :1.  public static double floor(double dbl) .7853981633974483 The log value is :3.out.377 System.  public static double ceil(double dbl) This ceil method has only one double value i. dbl1(the dividend) and dbl2(the divisor). Range is in between 0 to Ⱥ  public static double log (double dbl) The log method has only one double value i.println("The Exponent value is :"+Math.  public static double sqrt (double dbl) Here. 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. This method having two parameters i. hence can only be invoked by class name.¶dbl¶ which is taken as parameter.0686474581524463E13 public static double exp(double dbl) This method is a static method.e. log(35. } }output: the radian value is :1.5707963267948966 Degree value is:90. This method returns the natural logarithm (base e) of a double value.  public static double IEEEremainder(double dbl1. It takes a double variable as its argument.Here it returns the remainder when dbl1 is divided by dbl2. System. It returns the angle in radian.exp(30. 0. System. This method returns the value of the first argument which is raised to the power of the second argument.lang provides quite a lot utility tools to the programmer.378 This floor method having only one double value µdbl¶ as the parameter. If two double values that are equally close to the value of the argument. }} Most of the methods of math class is static in nature.println("\ n"+"The rint value is :"+Math.  public static double atan2 (double dbl1.rint(30.0. This package is going to be the premier package of java programming language forever. theta) by this method. It returns the closest double value to that µdbl¶ and is equal to a mathematical integer.lang package is the only package that is available to the programmer by default.0) . .IEEEremainder(5.6)). System. dbl1) is converted to polar (r. Recently added interfaces like Instrumentation has increased the scope of this package.2.out.then dbl2 must be greater than 0.out. The given rectangular coordinates (dbl2.0) .println("\ nThe remainder of 5 divided by 2 is:"+Math. This method returns the largest double value which is not greater than the argument and is equal to a mathematical integer. ceil(5. System. An exception can also arise if(dbl1<=0. floor(5.out. dbl2 not equals to a whole number.out.out. if (dbl1==0. it returns the integer value that is even. Conclusion: Java.These are the parameters for this method. System. This method also computes the phase theta by computing an arc tangent of dbl1/dbl2 in the range of ±pi to pi.println("\ n The power value is :"+Math. Their name clearly indicates their task.6)). Otherwise it throws an exception .println("\ n The ceil value is : "+Math. System.  public static double rint(double dbl) This rint method containing only one double value µdbl¶ as the parameter.println("The square root value is :"+Math. I hope reader can google through them & can get them quite easily.  public static double pow(double dbl1.2)).println("\ n The floor value is:"+Math. java.double dbl2) Here two double values dbl1 and dbl2 which are taken as the parameters for this method. class Arithm4 { public static void main (String arg[] ) { System.0)).out.sqrt( 25)). pow (5.6)). double dbl2) Here there are two double values dbl1 and dbl2. Java Collection Frame Work is quite rich. manipulate & retrieve objects by the implementation of various data structures like normal array.  By the help of the aforesaid interfaces we can manipulate the collections independently irrespective of their underlying representations.379 Chapter-23 The collection frame work Introduction I must say this is the most important package developer. as you can feel that Collection Frame work of java Standard Template Library (STL) of C++. queue. Here in most of the programs I have used the generic constructor of the corresponding class since generic provides type safety. But same. This loop is particularly use full when you deal with arrays or in general you might say when you deal with collection of object.  Encourage software reuse since the Interfaces and algorithms are reusable. hash-table etc. linked list.  It reduces the effort in designing new APIs. The for-each loop Before starting our voyage in to the util package it¶s the time now to explain another version of looping the for each loop.  It allows inter operability among unrelated APIs. If you are familiar with C++.  Increases program speed and quality since the implementation of each interface are interchangeable. trees. stack. & 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. 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. Lets have a simple program: .  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.  Extending or adapting a collection is easy. Set interface The Set interface extends the Collection interface. It adds restriction on the add ( ) method since it . You can try this for an array of user defined class.i<8. } for(int j:mak) { System. mak is the array name & the array is the array of integers. for(int i=0.println(j). the Set interface never gives permit to have duplicate element with in the set object.out. This loop maintains a higher level of abstraction. when 1st time the statement int j:mak is encountered in side for loop. java assigns the 1st element present in mak to j.out.i++) { mak[i]=i. Each element stored in mak is of primitive data type int.380 class Demo { public static void main (String arg[]) { int mak[]=new int[8]. this process continues until the last element assigned to j. } Let me explain. But. 2nd time when the same statement is encountered in side for loop 2nd element is assigned to j. The set interface does not define any method of its own.println(j). after that the loop automatically terminates. } } } Output: 0 1 2 3 4 5 6 7 The statement that troubles you for(int j:mak) { System. It uses only the methods of the Collection interface. If any object is not compatible with the elements that are present in Set then an exception known as ClassCastException is thrown. Object ss2 ):The job of this method is to return a SortedSet reference consisting of elements between the object ss1 and the object ss2.If the current set does not contain any element.  Object last ( ):The purpose of using this method is to return the last element of the current SortedSet to the caller. This method returns null if the set using the default ordering principle of Java. SortedSet Interface The SortedSet interface extends to the Set interface.  SortedSet headSet(Object ss ):This method returns a SortedSet that contains elements less than the object ss from the current SortedSet. Including the methods of Collection interface.  Object first( ):This method is used to return the first element of the current SortedSet to the caller of the method. then most of the methods present in this interface throws the NoSuchElementException. It is an ordered Collection. Null object can not be used in this interface other wise NullPointerException will be generated. which behave like two end points.381 returns false if the user tries to include duplicate elements added to a Set. This Collection has the permission to contain duplicate elements. 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. Brief descriptions of the methods are given below: . It also adds restriction on the equals( ) and hashcode( ) methods.  SortedSet subSet(Object ss1. the List interface has some of its own methods.  SortedSet tailSet(Object element):This method is used to return a SortedSet reference. Elements can be inserted into the list or accessed from it through their integer index in the list. Java defines a natural ascending order principle for this interface.  Comparator comparator():This method returns the comparator of the current SortedSet. The two listIterator methods are used for iteration. The get(). The preceding elements(if any) are shifted up in the list. If the object is not found in the concerned list. The indexOf and lastindexOf methods are used for search.  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. then -1 is returned to the caller.  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. List Iteration and Range-view.  ListIterator listIterator( int index):By the help of this method an iterator for current list is returned. remove() and addAll() methods are the methods used for Positional Access. Search.  Object set(int index. Object l):This method inserts the Object l into the current list at the position specified by index. within the current collection.Object a):It assign a to the position specified by index in the current list.  ListIterator listIterator( ):It returns an iterator to the start of the current list.  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.  Object get(int index):This method is used to return the object stored at the position specified by the index.  boolean addAll(int index.  Object remove(int index):This method is used to erase the element found at the position as specified by 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 sublist method is the Range-view method. If the object li is not found to be an element of the concerned list. The preceding elements(if any) are shifted up in he list. then -1 is returned. from the current list. that begins at the position specified by the given index. add().382  void add(int index. The methods of the interface can be categorized into methods used for Positional Access. Implementations . set(). AbstaractList : The AbstaractList class extends the AbstractCollection class and provides a skeletal implementation of the List interface. The important standard collection classes are as follows:AbstractCollection : AbstractCollection is a class which helps to provide a skeletal implementation of the Collection interface. the add() method has to be overridden. To implement a modifiable list. whereas. In this case. In order to implement an un-modifiable collection. similar named methods have been provided for the operations like get. For the implementation of the List interface. we have to extend the AbstractSequentialList class and define the implementations for the listIterator() and size() methods. the others are abstract and are used as starting points for creating concrete collections. ArrayList: . Some of these classes provide the full implementation and can be used right away. if we need to implement a modifiable collection. remove and insert an element at the beginning and at the end of the list. In order to implement a list. the remove method is implemented by the Iterator returned by the iterator() method.383 Implementation (or classes) is the actual objects used to store the collections. By the help of this class a sequential access can be carried over the collection elements. we have to extend the AbstractCollection class and provide the implementation logic for the methods like Iterator() and size(). It is an implementation of the List interface. All the optional list operations are to be implemented by this class. 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. the set and remove methods are to be overridden. LinkedList : LinkedList is a class which extends the AbstractSequentialList class and implements the interface List. On the other hand. AbstractSequentialList :AbstractSequentialList is a class which extends to the AbstractList class. 384 ArrayList is a class which extends the AbstractList class and implements the List interface.out.println("Initially size of the array:"+arrX. 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 implementations from the AbstractColllection class are not overridden in this class. for (int j=0.util. AbstractSet : AbstractSet is a class which extends the AbstractCollection class and provides the skeletal implementation of the Set interface. 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. The time complexity for various operations to be performed on the HashSet is almost constant. package demo. In addition to that.j<5. class X{ int i. It only used to add implementations for equals and hashcode methods.j++) . This class is a generic class. } class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>().*.size()). System. This class implements the List interface & extends the AbstractList class. there are methods with which we can manipulate the size of the array that is used to store the list internally. import java. ArrayList is serializable. the size() method has to be invoked by the corresponding of ArrayList class. Object of ArrayList is some thing like container. In the above program I have supplied the class name X to create the ArrayList of class X. arrX.size()). } System. So . } System.i). for (int j=0. Here arrX is an object which can contain the object of class X. To get the number of elements that is stored in the ArrayList. } } } 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.out.j++) { X a=new X(). Here arrX is an object which can contain the object of class X.out.println(a. a. arrX.println("now size of the array "+arrX.add(a).println("Finally the array size "+arrX.i=j.size()). for(X a:arrX){ System.out. It¶s signature is Class ArrayList<Claass_Nmae>.385 { X a=new X().i=j+5. a.add(a). Programmer specifies the name of the class whose ArrayList has to be created.j<5. out. If add() method is successfully executed then boolean true value is returned else false will be returned. 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. class X{ int i.println(j).j<5.j++) { X a=new X(). import java. Actually this add() method belongs to List interface which is implemented in ArrayList class. which returns the size of ArrayList object.add(a).println("Initially size of the array:"+arrX. hence add() method is over-ridden there. . ArryList constructors are 1:ArrayList()a zero argument constructor to create an empty array & the array grows as you add new element to it. Its return type is integer. arrX.i=j.386 how to add a new element to this container? 1st create an object X. System.*.out.util. call the add() method through the object of ArrayList & pass the object of X to be added. for (int j=0.println(i). a.size()). } } class Y extends X{ int j.out. void show() { System. To determine the length of arraylist the size() method is used. The signature of add() method is boolean add(A object). void show() { System. 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. } } class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>(). util.387 } System.j=j+5.out. package demo.println("now size of the array "+arrX. } System.j++) { Y a=new Y(). for (int j=0. arrX. void show() { .j<5.out.*.println("Finally the array size "+arrX. Just pass the index number of the element that you want to remove from the ArrayList.add(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. class X{ int i. Deletion an Object from ArrayList In order to remove an object from ArrayList you have to invoke the remove() method. a.size()). Program below will fix your idea. for(X a:arrX){ a.size()). import java. j<5. a. for(X a:arrX){ a.add(a).j=j+5. for (int j=0.out.println(i). } } } Output: Initially size of the array:0 now size of the array 5 Finally the array size 9 0 1 .388 System.j<5.j++) { X a=new X().out.i=j. void show() { System.remove(4).j++) { Y a=new Y(). } } class Y extends X{ int j. System.println(j).println("now size of the array "+arrX. } } class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>().out.size()).println("Finally the array size "+arrX. } System.println("Initially size of the array:"+arrX. arrX. arrX.out. a.size()).out. } System. arrX.size()).add(a).show(). for (int j=0. arrX.util. arrX. arrX.add("Dasvidania"). arrX.add("Vendeta").add("Eureca").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. } } Output: Eureca Dasvidania Minerva HitMan Vendeta After deletion Eureca Minerva HitMan Vendeta .out. for(String s:arrX) { System.println(s). } arrX.remove("Dasvidania"). package demo.out.println("After deletion").println(s).add("Minerva").out.add("HitMan").*. for(String s:arrX) { System. import java. see the example below. System. arrX. class Demo { public static void main (String arg[]) { ArrayList<String> arrX=new ArrayList<String>(). linkedL. import java.addFirst(a).println(b. It provides the linked list data structure to store & manipulate the data.390 See that the string object that is to be removed from the ArryList passed as an argument remove() method. class X{ int i.i++) { X a=new X(). } X a=new X().util. for(X b:linkedL) { System. a.out. } } } Output: 100 0 1 2 3 . } class Demo { public static void main (String arg[]) { LinkedList<X> linkedL=new LinkedList<X>().i). a.i<5. linkedL.add(a). package demo. for(int i=0.i=100. The LinkedList Class First of all LinkedList is a generic class.*.i=i. System.util.out. Similar is the job of another method offerFirst(). linkedL.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.add(a). for(int i=0. Retrieving particular element from the LinkedList object. } class Demo { public static void main (String arg[]) { LinkedList<X> linkedL=new LinkedList<X>(). The remove() method discussed in ArrayList class can be invoked in LinkedList to perform the similar task. This method takes index number as its argument & returns the object stored at that postion in the LinkedList object. } for(int i=0. See the use of for each loop to extract the elements present in the LinkedList object. } }} Output: 0 1 2 3 4 . a.i++) { X a=new X(). import java.i). class X{ int i.get(i).println(a. See the for-each loop used here to retrieve the element from LinkedList object.i<5.*. get() method is used to get the stored elements.i++) { X a=linkedL.i<5.i=i. i=100. The position where to insert an element is supplied as the first argument to this method.util. a. for(X b:linkedL) { System.i=i.out.i<5. } }} Output: 0 100 2 3 4 .add(a). class X{ int i.set(1. for(int i=0. linkedL. set() method is used to change an entity stored in the LinkedList object in the specified location.println(b. } class Demo { public static void main (String arg[]) { LinkedList<X> linkedL=new LinkedList<X>(). Some other methods addLast() or offerLast() method is used to add an element at the end of LinkedList object.a).E) method. } X a=new X().*. To add a particular element at a specific location you can use add(int.i++) { X a=new X(). linkedL.392 Here get() method is invoked by the object of LinkedList & returns the object of class X. a.i). Now lets have an example import java. util.393 See the out put.*. The data is retrieved from the hash table by the memory address associated with the key value.add(a).i=i.i<5. for(int i=0. What is a hash table? Hash table is a data structure to store data. the HashMap class do provide the key. The HashSet Class The HashSet class of this util package use has table data structure in back ground to store the data. Just check it out here. } class Demo { public static void main (String arg[]) { HashSet<X> hashS=new HashSet<X>(). package demo.i). When a data is to be retrieved from a hash table the user provides the key value. This key value is unique for each element present in the hash table. which contains key value for each data present in the hash table. } for(X b:hashS) { System. But. HashSet in java extends the AbstractSet & implements the set interface.out. } }} . The key field is closely associated with a pointer or a memory address. class X{ int i.i++) { X a=new X(). a.println(b. import java. the change is reflected there. hashS. 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. The HashSet class does not provide the key value to the programmer to access the objects stored with in it. i=100.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.i<5.i=i. but you cannot determine where the data is going to be added. hashS. for(int i=0. class X{ int i.i). } class Demo { public static void main (String arg[]) { HashSet<X> hashS=new HashSet<X>(). package demo. import java.i++) { X a=new X(). for(X b:hashS) { System. } X z=new X().add(a). } }} Output: 3 100 .*. hashS. z.println(b.util.add(z).out. a. treeS.i<5. for(int i=0. import java. The TreeSet class In a TreeSet class in java uses tree data structure to store the data.*.out.println("Stored element"+b). package demo. j--.395 4 2 1 0 See where 100 is added.i++) { System. Data in TreeSet class always stored in ascending order.add(j). Since this class maintains tree structure to store data.println("Added element:"+j). } }} Output: Added element:5 Added element:4 Added element:3 Added element:2 Added element:1 Stored element1 Stored element2 Stored element3 Stored element4 . } for(Integer b:treeS) { System.out. int j=5. class Demo { public static void main (String arg[]) { TreeSet<Integer> treeS=new TreeSet<Integer>().util. searching is done quite efficiently. Steps to use Iterator: 1: create an Iterator object corresponding to the elements stored in the Collection frame work. from the current collection. else. We can call this method only once per call to the next method. except these two differences. still they are stored in the TreeSet in ascending order. class X{ int i.  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. it returns false.396 Stored element5 See the out put although the elements are supplied in descending order. 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. then it throws the NoSuchElementException  void remove ( ):This method is used to remove the last element returned by the iterator.*.util. The Iterator The Iterator is an interface which is similar to Enumeration interface. Alternative to for-each loop is Iterator. Till now to loop through the various elements stored in Collection object I have used the for-each loop. 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. But. 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. println(a.i).out. while(iteR. steps are same to use the ListIterator object. } class Demo { public static void main (String arg[]) { .j++) { X a=new X(). System.i=j.add(a). HashSet.*. class X{ int i.iterator().397 } class Demo { public static void main (String arg[]) { ArrayList<X> arrX=new ArrayList<X>().next(). TreeSet calss. if not it returns false. arrX.util. each time when it is invoked check whether an element existed in arrX or not in its next place.hasNext()){ X a=iteR. } Iterator<X> iteR=arrX. a. The next() method return the element stored in arrX(). } } Output: 0 1 2 3 4 The hasNext() method. The ListIterator The object ListIterator provides a way to loop through the elements stored in the Collection object bidirectionally. The way the Iterator is used in case of object of ArrayList class can also be used in LinkedList.j<5. for (int j=0. import java. Like Itrator it is also a generic class. Just see the program below package demo. Map interface Map is an interface by the help of which. System.398 ArrayList<X> arrX=new ArrayList<X>(). HashSet. TreeSet to perform the similar to that of ArryList.out. We cannot have any duplicate . arrX. while(LiteR.j<5. for (int j=0. } System.listIterator(). ListIterator object can also be used in LinkedList.hasNext()){ X a=LiteR.out.out.println(a.println("Back ward traversing").add(a).next().println("Fore ward traversing"). } System.hasPrevious()){ X a=LiteR.i).i=j.previous(). we can establish a mapping between keys to the corresponding element. ListIterator<X> LiteR=arrX.out. while(LiteR. } } } 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. System. a.i).j++) { X a=new X().println(a. else it returns false. it returns a boolean false. 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. Then it is removed by the provided mapkey.Object mapvalue ) The job of this method to associate the mapvalue with the mapkey in the current map.  boolean containsValue (Object v ):This method returns a boolean true when the current map maps one or more keys to the value v.  boolean containsKey (Object keyused) This method returns true or false accordingly.else it returns false  Object get(Object keyused) .  Object put(Object mapkey.  void clear ( ) This method removes all the mappings from the current map. containsValue. If the map does not contain any mapping then it returns true. Otherwise. This interface consists of methods for basic operations.  Object remove(Object mapkey) When there is an already existing mapping present for key in the current map. remove. The different operations that can be made on a map are: put.  Set entrySet( ) This method returns a Set interface reference which specifies a view of the mappings established in the current map.399 values in a map. size and isEmpty.  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. get. In the process of mapping each key is mapped to one & only one unique element. whether the current map is mapping one or more keys to the value or not. The bulk operations are putAll and clear methods.  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. containsKey. bulk operations and Collection view. The Collection views are keySet and entrySet methods.object a is equal to the current map.  boolean IsEmpty( ) Checks whether the current map key value mappings. We can avail the value by using this method. The methods of SortedMap interface are  Comparator comparator( ):This method returns the comparator which is associated with the SortedMap. the method returns null.  Object remove(Object keyused) This method removes the mapping which is present in the map for the key keyused.  Object put(Object keyused.  According to a user defined Comparator provided by the programmer explicitly. StoredMap interface SortedMap is an interface which also extends the Map interface. If the SortedMap keys follows default ordering principle provided by Java. else false.Object valueused ) To attach the value valueused with the key keyused in the map.  int hashCode( ) Every map has a hashcode value.  Collection values( ) This method returns a Collection reference which represents the view of the values contained in the map. The elements are maintained in an ascending order in case of StoredMap interface.  According to the default ordering principle provided by Java.400 We can get the available value to which the mapping has been established using the key keyused.  Int size( ) This method is used to get the total number of mappings established inside the Map. If the map does not contain any mapping then it returns true. The sorting may be done in two ways. this method is used.  Set keySet( ) The total no of keys used for mapping inside the Map can be returned using this method. . key1.  Object lastKey( ):From the ascending ordered SortedMap.  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.V>hashM=new HashMap<K.key=i.401  Object firstKey( ) From the ascending ordered SortedMap.  SortedMap subMap(Object sm1. for(int i=0. import java. this method returns the highest key.util.  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.i++) { K key1=new K(). How it is used can be understood through a program. K keyArr[]=new K[5]. package demo. to the key specified by sm2. class K { int key. HashMap does not implement Iterable interface.i<5.V>(). } class V{ int data. the range includes sm1 and excludes sm2. This means programmer can not traverse a HashMap neither by Iterators nor by for-each loop. } class Demo { public static void main (String arg[]) { HashMap<K. It has both key & a value and data associated with the key. . Object sm1 ) It returns a reference of the portion of the SortedMap whose keys are ranging from the key specified by sm1. this method returns the lowest key.*. The entrySet() method HashMap is not a part of collection frame work. } for(int i=0.println(a. } class Demo { public static void main (String arg[]) { . This method returns Set object which contains the element of the HashMap. V val=new V(). hashM. java provides an entrySet() method to have collection format of HashMap. since it does not implement the Collection interface. System.i++){ V a=hashM. How ever.util. Just see the put method.*.val).put(key1. To extract data from HashMap key is required. val.data=i+5.out. The get() method only requires the key to extract the data. it keeps inserting data in the HashMap with the key value. Lets have an example package demo.get(keyArr[i]). Then each key value stored in the array is used to extract data from the HashMap. } } } Output: 5 6 7 8 9 Data is sored in the HashMap along with the key value.402 keyArr[i]=key1.data). } class V{ int data. Therefore I have declare an array to store the key value. import java. class K { int key.i<5. for(int i=0.put(key1. Now the output is straight forward. the programming example I have given used a wrapper class instead of user defined class.V>hashM=new HashMap<K.i<5.i++) { K key1=new K(). V c=x.Entry.Entry in for each loop.data=i+5. Remember that each element present in s is a reference of of Map.key+" Value:").getKey().Entry<K.out.val). The setEntry() method returns the return the object of Set containing all the stored in HashMap. val. } Set<Map. key1. System.V>(). The Comparators You must have noticed while explaining the treeSet. V> x:s) { K z=x. Java defines a natural ordering principle like µB¶ comes after µA¶ or µ2¶ comes after µ1¶ for treeSet & only for . treeSet stores the object in a sorted order. The getKey() method returns the reference of class K & the getValue() method returns the reference of class V. System. } } } 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.print("For key: "+z.key=i. for(Map. V val=new V().println(c. That is why I have created a reference of Map. hashM.out. Entry is a inner class of Map. V>> s=hashM.entrySet().403 HashMap<K.Entry<K.getValue().data). The signature of compare() method is int Compare(genR X. Yes this is a generic interface. 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. } } class Demo { public static void main (String arg[]) { TreeSet<X> treeS=new TreeSet<X>(new userComp()). package demo.add(a). } } } Output: 0 .println(a.i++) { X a=new X().i.*.util.out. } for(X a:treeS) { System.i<5.genR Y).i=i. when it comes to deal with user defined classes. class X { int i. X b){ return a. a. then programmer must explicitly define ordering principle by the use of Comparator interface. import java.X> { public int compare(X a.404 the predefined class.i). The Comparator interface defines two method compare() & equal(). treeS. } class userComp implements Comparator<demo. The signature of the Comparator interface is interface Comparator<genR>. for(int i=0.i-b. class X { int i.util.out. } } class Demo { public static void main (String arg[]) { TreeSet<X> treeS=new TreeSet<X>(new userComp()). The object for which the compare() method returns a positive value is stored next to the previously stored object.i++) { X a=new X().i).*. } for(X a:treeS) { System. X b){ return -a.add(a). import java. How to reverse this user defined comparator package demo.i=i. treeS. a.println(a.i<5. statement tells the compiler to use the user defined comparator rather than default comprator. for(int i=0.i+b. } } } Output: .i.405 1 2 3 4 this TreeSet<X> treeS=new TreeSet<X>(new userComp()).X> { public int compare(X a. Java implicitly invokes the compare() method of userComp class. } class userComp implements Comparator<demo. Collections. linkedL. // creation of a reverse comparator Collections.println(i).revC).out. linkedL. coping the elements & various other operations.406 4 3 2 1 0 The Collection Algorithm Java defines various methods to be operated on Collection objects for repositioning of the elements.add(-99). // shuffling the elements present in the list System. class Demo { public static void main (String arg[]) { LinkedList<Integer>linkedL=new LinkedList<Integer>().println("Minimum element:"+Collections.out.*.reverseOrder().shuffle(linkedL).sort(linkedL. Lets have an example package demo.println("After shuffling"). import java.add(100). for(Integer i:linkedL) System. System.util.out. extracting a particular element say minimum or maximum value.add(-100). // sorting the list according to reverse comparator System. linkedL. These methods in together constructs the collection algorithm.add(99).println(i). for(Integer i:linkedL) System.min(linkedL)).println("Maximum element:"+Collections. } . sorting the elements in the specified manner.out.out. System.println("Descending order:"). Comparator<Integer>revC=Collections. linkedL.out.max(linkedL)). *. a.i++) { X a=new X(). } class Demo { public static void main (String arg[]) { Vector<X> vect=new Vector<X>(). for(int i=0. package demo.util. } X a=new X(). for(X x:vect) System. The Vector class The Vector class is much similar to that of ArrayList class used to generate the dynamic array.out.i=100. vect.println(x.i).addElement(a). class X{ int i. a. } } . vect. All the method names used in this program define their task.add(a). Vector class is synchronized.i<5.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. import java.i=i. } class Demo { public static void main (String arg[]) { Vector<X> vect=new ArrayList<X>(). you can see that Vector is much similar to that of ArrayList. } } 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.add(a).i).println(a.408 Output: 0 1 2 3 4 100 addElement() method behaves similar to that of add() method. while(iteR. just like Iterator.*. } Iterator<X> iteR=vect. . System. This is a legacy interface can only be operated on Vector object. vect.j<5. a. Here you can Iterators to traverse various elemrts present in Vector object package demo.i=j. import java.iterator(). for (int j=0.hasNext()){ X a=iteR.out.next().j++) { X a=new X().util. class X{ int i. util. vect. } class Demo { public static void main (String arg[]) { Vector<X> vect=new Vector<X>(). } Enumeration en=vect.println(a. Vector implements this interface. class X{ int i. The method nextElement() extracts the element that is pointed by the implicit pointer.add(a).i<5. hence proper type casting is required. nextElement().out.*.hasMoreElements()){ X a=(X)en.i).409 package demo. Each invocation of µhasMoreElements()¶ method just fore ward the implicit pointer to point to the next element. a.i++) { X a=new X(). The element() method returns the enumerations of elements present in Vector which is stored in µen¶. } } } Output: 0 1 2 3 4 Enumeration is an interface.i=i. System. for(int i=0. while(en. Then µhasMoreElements()¶ method is invoked by µen¶. . import java. Its return type is object type.elements(). This method returns true until the last element is encountered. empty()){ System. 3] Initially the Stack:[0. 5. 2] Initially the Stack:[0. System. 1. 7. 5. 1. s. 7. 1. 3.out.pop()). 1. 3. 6.out. 3.*. package demo. 2. The principle to retrieve the data from stack class is last in first out principle.println("Initially the Stack:"+s). 4.i<10. 4.i++){ byte b=(byte)i. 1. 6] Initially the Stack:[0. for(int i=0. 4. class Demo { public static void main (String arg[]) { Stack<Byte> s=new Stack<Byte>(). 8] Initially the Stack:[0.println("pooped:"+s.out. 6.println(s). 2. 7. 3. 1. 4] Initially the Stack:[0. 5. 1] Initially the Stack:[0. 3. 2.out. 9] pooped: 9 [0. 3. 5. } while(!s. 1. 1. 6. 8. 2. 4. 1. 2.push(b). System. 6. 5. 7] Initially the Stack:[0. 4. 2. } } } Output: Initially the Stack:[] Initially the Stack:[0] Initially the Stack:[0. This class uses the stack data structure to store various elements. 2. 5] Initially the Stack:[0.println("Initially the Stack:"+s). System.410 The Stack class Stack class extends the Vector class.util. 2. 3. import java. 8] . 4. 3] pooped: 3 [0. 6. 1. Hashtable is synchronized. 5. 4] pooped: 4 [0. 4. 3. 3. pop() method pops the last element present in the stack & decreases the capacity of the stack by 1. 1. 2. 4. 6] pooped: 6 [0. Hashtable Hashtable is another powerful feature of Collection Frame Work. 3. Output clearly shows the performance of these two methods. 2. 7] pooped: 7 [0. } class V{ int data. Actually objects are not stored in fact their reference is stored. 2. 1. 2. 4. 5] pooped: 5 [0. 1] pooped: 1 [0] pooped: 0 [] push() method pushes a new element in to the stack & increases the stack size by 1. This class implements the hash table data structure to store the element with in the hash table object. 5. class K { int key. Hashtable implements the Dictionary. } class Demo { . 3.util. import java.*. 2.411 pooped: 8 [0. 1. package demo. 2] pooped: 2 [0. Lets have a program for the implementation of Hashtable. 1. 1. Hashtable class is much similar to that of HashMap class but. i++){ V a=hashT.data). Otherwise.V>().println(a.  boolean addAll(Object cls):This method is use to add all elements of the Collection which is passed as argument to the existing collection.val).put(key1. } for(int i=0. then this method returns false.key=i. But.out.data=i+5.V>hashT=new Hashtable<K. val. hashT. If the addition of the object is successful. then this method returns true. if the object is already there inside the collection. . Important Methods Of Collection Frame work and their Descriptions  boolean add(Object cls):This method adds the given object to the existing collection. key1. it returns false. for(int i=0. } } } Output: 5 6 7 8 9 See the Hashtable behaves similar to that of Hashmap. This method returns true when the elements are added successfully. System. keyArr[i]=key1. This method invoked by the collection object to which the addition of element has to be performed.412 public static void main (String arg[]) { Hashtable<K.get(keyArr[i]).i<5. K keyArr[]=new K[5]. V val=new V().i<5.i++) { K key1=new K(). If successful. it returns true.413          void clear( ):This method is used to erase all the items from the collection object through which it is invoked. 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. 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.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 it is present. then the method returns true. then the method returns true. 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. If successful. . 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. it returns true. Otherwise it returns false. boolean contains(Object cls) :This method is used to confirm whether the given object cls is present inside the current collection or not. 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. else it returns false. else 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. Apart from them a rich library of methods is available in Collection Frame Work. After having these fundamental ideas. methods are reengineered. Most of the fundamental classes their most frequently used methods are discussed here. It¶s up to the programmer to implement the desired data structure according to the situation. most of the constructors.414 Conclusion: Collection Frame Work is a powerful addition to the java language. By the introduction of generics in java. your navigation through other methods will be bread & butter for you. 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. . This frame work provides various data structures to store & retrieve the data. 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. say java. } } } Output: Past Present & future is nothing special they are just Clock Time!! sTokenizer is a object of StringTokenizer class. What exactly meant by parsing? When you write a program in any high-level language. import java. System. 1st argument is the string .*.out.nextToken(). see the constructor of the StringTokenizer class it takes two argument.println(keyused ). it is the task of the compiler to convert the source to some intermediate language like byte code or directly to machine readable language. while(sTokenizer. Java provides the StringTokenizer class to divide the entered text in to number of sub-string or tokens.util.415 Chapter-24 java. StringTokenizer implements the Enumeration interface for which we can traverse through various sub-strings present in the entered text.".").hasMoreTokens()) { String keyused = sTokenizer. they are just Clock Time!!". package demo. During this process first compiler checks the syntactical correctness of the program.util package part II StringTokenizer Parsing is quite familiar term in Compiler Design. Present & future is nothing special. class Demo { static String str1="Past. public static void main(String arg[]) { StringTokenizer sTokenizer=new StringTokenizer(str1. ".  boolean hasMoreElements ( ):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. The 2nd argument is the string according to which the 1st argument has to be divided in to number of sub-strings. Present & future is nothing special. StringTokenizer (String string."is". String arr[]={"."&".println(keyused ). They are 1. i++. import java. Methods and their Description  int countTokens( ):This method determines the number of tokens left to be parsed and returns the result.  String nextToken (String delimiters):This method returns the next token as a String and sets the delimiters of the string. class Demo { static String str1="Past."}.".out. they are just Clock Time!!". System.  boolean hasMoreTokens ( ):This method returns true if one or more tokens remain in the string and returns false if there are none. int i=0. boolean delim) Lets have another program package demo.nextToken(arr[i]). StringTokenizer (String string) 2. String delimiters.*. StringTokenizer class provides another two constructors. public static void main(String arg[]) { StringTokenizer sTokenizer=new StringTokenizer(str1).util. while(i<4) { String keyused = sTokenizer. } } .416 meant for parsing. 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. BitSet bSet2=new BitSet(32).println(bSet1).e. import java. } System. class Demo { static String str1="Past. they are just Clock Time!!". the array can grows & shrinks according to the given input. if(i%3==0) bSet2. // The OR operation bSet1.out. System.or(bSet2). The array created by BitSet class is dynamic in nature i.out. System.i<=32. //Anding of Bits bSet2.util.i++) { if(i%2==0) bSet1.println("After OR:"+bSet1).set(i). Present & future is nothing special The output here is quite simple & straight forward.println("After ANDING:"+bSet2). System.out.and(bSet1). Present & future is nothing special.*. BitSet Java provides the BitSet class to store the bit values.println(bSet2). public static void main(String arg[]) { BitSet bSet1=new BitSet(32). package demo. .417 } Output: Past .out. for(int i=1.set(i). 14.set(i). 15. 4. 4.out. class X implements Observer{ public void update(Observable obs. 30. Seldom will you ever find a programmer using only one of the classes to develop an application in java. 26. 18. 6. 4th bit. 28. 10. is encountered. 6. 20. 8. 2nd bit. 30} After ANDING:{6. 8th bit & so on of bSet1 is turned on. 14. 24. 16.418 //XOR operation bSet2. 8.print("Object of Y is changed:"). 10. 22. 24. 16.*. 22. 16.xor(bSet1). The Observable class & the Observer interface The Observable class & the Observer interface is closely entangled with each other. 32} set() method sets the particular bit on for the BitSet object through which it is invoked. 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. 30. 14. 12.println("After XOR:"+bSet2). 9. 26. 18. 32} After XOR:{2.out. 12. 27. 12. 20.Object obj) { System. 26. 12. 6th bit. 10. 6. 22. 20. System. For example when this statement if(i%2==0) bSet1. 18. 8. 30} After OR:{2. } } class Y extends Observable { . 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. The and() method performs the µand¶ operation & the result is stored in the invoking object bSet2. A program will fix the ideas package demo. 18.util. } } Output: {2. import java. 24. 32} {3. 28. 21. 4. 24. 28. addObserver(b). notifyObservers(this).fun().println(i).setChanged(). try{ Thread. } } } 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 . void fun() { i++. } void show() { System.i<10.sleep(100). }catch(InterruptedException e){} show().i++) { a. } } class Demo { public static void main(String arg[]) { Y a=new Y().out.419 int i. this. for(int i=0. a. X b=new X(). i). because for a thread to run 1st it must go to ready state. notifyObservers(this.out.println() is dispalyed.out.addObserver(b). registers the object b as observer to observe the changes made in object a. Once the control is transferred. The setChanged() method has to be invoked by the object which is to be observed. It has an instance variable i. } } class Y extends Observable { Integer i . fun method manipulates the object a by performing i++. package demo. this. Class Y extends the Observable interface that means changes made to the object of Y is going to be monitored. The notifyObservers(this) method informs the observer when the object is manipulated.setChanged().util. . void fun() { i++.Object obj) { System. If you do not invoke this method then observer thread is not going to be executed. This tells to JVM that the object of X will behave as observer. Now have a look at class Y. The statement a. inside main method fun method is invoked by the object of Y. This is done by the sleep() method. import java. class X implements Observer{ public void update(Observable obs. 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. One thing the observer object & the object to be observed runs in different threads. Now in side fun method I have invoked the setChanged() method.420 class X implements Observer interface. The setChanged() method made the observer thread in ready state. the change is monitored & the message inside the System.println("Object of Y is changed:"+(Integer)obj).*. This method actually implicitly invoke the update() method & sends the object µa¶ to update() method implicitly. *.sleep(100). }catch(InterruptedException e){} } } class Demo { public static void main(String arg[]) { Y a=new Y().util.i++) { a. } } } 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. class X implements Observer{ public void update(Observable obs. import java. a.Object obj) .i<10. X b=new X().addObserver(b).421 try{ Thread. for(int i=0.fun().i=new Integer("0"). a. Y c=new Y().setChanged(). c. notifyObservers(this.println("Object of Y is changed:"+(Integer)obj).out. } } } Output: Object of Y is changed:1 .addObserver(b). a.i=new Integer("100"). a. for(int i=0.fun().i).422 { System. this. X b=new X(). } } class Y extends Observable { Integer i . try{ Thread.i<10.sleep(100).addObserver(b). c. void fun() { i++.i=new Integer("0").fun(). c.i++) { a. }catch(InterruptedException e){} } } class Demo { public static void main(String arg[]) { Y a=new Y(). Object obj) { System. class X implements Observer{ public void update(Observable obs.util.*.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.Object obj) { System. } } class Z implements Observer{ public void update(Observable obs. import java.out. } } class Y extends Observable { .println("Object of Y is changed:"+(Integer)obj).out.println("Object of Y is changed:"+(Integer)obj). X b=new X().fun(). a. c. } } } 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 .i<10.i++) { a. Y c=new Y().424 Integer i . for(int i=0. this. }catch(InterruptedException e){} } } class Demo { public static void main(String arg[]) { Y a=new Y(). c.i). notifyObservers(this.i=new Integer("0").sleep(100).addObserver(b).addObserver(d). a.fun().setChanged(). try{ Thread. void fun() { i++.i=new Integer("100"). c. Z d=new Z(). 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. try{ Thread.out. All these things can be achieved by the Timer & TimerTask method.*. Timer tm=new Timer(). tm. 1000. } } class Demo { public static void main(String arg[]) { X a=new X().sleep(5000).util. 1st lets have an example then I will explain all in detail package demo.println("Hello World!!!"). }catch(InterruptedException e){} . class X extends TimerTask{ public void run() { System. 250). import java. You can schedule your job at any future time & you can set the time interval after which you want the task to be repeated.scheduleAtFixedRate(a. These classes I have discussed are not part of Collection Frame Work. Task executed as separate thread. which is done by the sleep() method. time at which the task is going to be started & the time interval after which the task is going to be repeated. TimerTask class implements the Runnable interface due to which run() method is available there. 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. TimeZone class is there to play with date. this method takes the task object a. Codes inside the run method is the task to be executed. Calendar class. Almost all of them are simple can easily be understood by the reader.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.426 tm. . My aim is to made reader comfortable with the things like observer & task scheduling. As long as main thread is sleeping the task is done at a particular interval of time. this statement. month & year. Next scheduler invokes the scheduleAtFixedRate method. Conclusion: Apart from the discussed classes & interfaces util package contains a huge number of collections of classes. When the main thread resumes tm. Something like Date class. So to transfer the control context switch is required.cancel() is invoked to terminate the task. Timer or you can say scheduler is created by Timer tm=new Timer(). Some of these are wriiten below. j Applets can communicate with the server in which they were stored originally but not with the others. The program structure of applets differs from the other java applications we have done till now. 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. j Applets can͛t execute any programs on the system. Applets has added advantages such as frame. event-handing facility. They can be created like any normal programming language programs.applet package. Applet is a class present in java. 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. . Java applets have some restrictions to ensure full security and to make them virus free . j Applets have no read or write permisson to the file system.427 Chapter-25 java. it is present in the jdk. graphics context and surrounding user interfaces. Java applications do not require a browser to run.applet package Applet Generally java programs can be classified into two groups namely applications and applets. Unlike applets. A special HTML tag is embedded in the applet to make it run on the web browser .so we can compile a applet code but we cannot run it. Internet Explorer browser is a World Wide Web Browser used to view Web pages.now let͛s see how a applet gets executed what are the different states of a applet. appletviewer application is used to run and check the applets . Life cycle of Applet: Applets don͛t have any main method or constructors. Briefly we can say that applet is a java byte code embedded in a HTML page. Applets have made java a web enabled languase. Applets are executed in the browser. init() Begin or entering Newborn state (By typing URL. Dead state or Destroyed state. paint() start() stop() Running state start() Idle state destroy() Dead state Exit or End (Transition diagram of applet life cycle) . address). Running state (display). Idle or stop state.428     Newborn state. The destroy() method is called to end the execution of the applet or to exit the applet. Whenever the init() method is called the applet is created or we can say that it gets life. Applet has no constructor but init () behaves as a constructor. There are many methods in the applet class but the methods init() . Initialization of all the variables. public void start() Method This method is executed after the init () method. The destroy() method applies only to applets where as the finalize() method is generally used to clean up a single object. When an applet is running in a Java enabled browser. The destroy() method is different from the finalize() method. start(). There are four Applet state. The stop() Method The stop () method is used to halt the running of an applet. 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 . stop() method is always called before the destroy() method is called. the stop () method is called when you move from to another Web page and when you comes back. You can call the stop() and start() method repeatedly if you want to do it. . All the changes in the applet are reflected by the paint method(). creation of objects and setting of the parameters can be done in this method. stop() and destroy() constitutes the life cycle o f applet. Any clean up activity that needs to be performed can be done in this method. 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. the start() method is called to resume the applet.429       Every java Applet when loaded undergoes a series o f state changes. When the start() method is called the execution of the applet gets started. paint(). 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 This method is called whenever we want to free the memory occupied by the variables and objects initialized in the applet. we can free the resources held by the applet using the destroy() method. 430 The paint() Method Whenever it is needed to redrawn the output of the applet paint() method is called. int height) in the above syntax Delay specifies the time in milliseconds that it will wait before update( ) is called. It takes an argument. To use this method. int WIDTH. int width. void repaint( int x_co.there are also other versions available they are given below.awt.Graphics. The update( ) method in turn calls the paint( ) method which draws the contents of the current frame. int x. writing and creating a colored background or an image onto the applet. which is an instance of the Graphics class. int y. This helps in faster updating of the screen. void repaint(long Delay) void repaint(long Delay. int HEIGHT) repaint() takes four arguments to update only a part of the screen. The repaint() Method This method is used in case an applet is to be repainted. repaint() can be called in future by mentioning time interval in millisecond. The first to arguments are the x and y coordinates. The repaint() method calls the update( ) method to clear the screen of an existing content. If the time expires before update() can be called. it is necessary to import the Graphics class as import java. This method helps in drawing. The other methods available in Applet class are defined below . update is not summoned. int y_co. the next two arguments are the width and the height of the image. Collects the AudioClip object from the location specified by the url having the name specified. Determines whether an applet is active or not. Plays the audio clip in the background of applet. 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. . Gets the information about the Applet.String name) String getParameter(String name) boolean isActive() void play(URL u) void play(URL u. Collects the AudioClip object from the location specified by the url.html file are discussed below.int height) void showStatus(String msg) HTML Tags Some of the HTML tags used in the .431 Method AppletContext getAppletContext() String getAppletInfo() AudioClip getAudioClip(URL u) Describe Determines the applet context and returns it. Plays the audio clip in the background of applet. String name) void resize(int width. 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. java file and the . above or at the side of the applet within the HTML file.class file of an applet named Text Applet is stored in the directory /test. It assumes that both the . < / applet> tag is used. CODE and CODEBASE Tags CODE is a necessary attribute that gives the name of the file that contains the applet͛s compiled class. This has two attributes namely NAME and VALUE. The different methods we use to set the graphical enviorment . if the . the CODEBASE tag is used. To do this. The special parameter tag in the HTML file is <PARAM>.class file is stored. 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 is done by including those lines within the < applet > and < / applet > tags. The init () method of the applet.html file are in the same directory. To pass parameters to an applet.class fill are stored in different directories. The size of display of the applet is initialized using the WIDTH and HEIGHT tags. 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. it has to be converted explicitly. To indicate the end of the applet.html file and the . If this method is required to return types other than strings. If the . It is essential to end the applet using this tag. Comment lins can be inserted below. This code instructs the browser or the appletviewer to load the compiled Java applet. otherwise it will not be executed. For example. namely the .432 Applet Tags The <applet> tag is used to start the applet from inside the HTML document as well as from the appletviewer. the HTML file code will appear as indicated below: <APPLET CODE = ͞TestApplet. The CODEBASE tag contains the pathname where the . two things are required ʹ a special parameter tag in the HTML file and the code in the applet to parse those parameters. it is essential to mention it specifically.class͟ CODEBASE = ͞ / test͟ WIDTH=400 HEIGHT=300></APPLET> Passing Parameters to an Applet We have discussed the passing of parameters to a Java application. contains a method called getparameter ().class file. The above methods are defined in Component class .black Color. and their general forms are: void setBackground(Color Color) void setForeground(Color Color) Color specifies the new color.pink Color.blue Color.433 applets use the classes & methods of AWT to perform it͛s input and output operations.cyan Color. To display the output in the applet we use the drawstring() method present in the Graphics class .yellow Color. the upper-left corner is location 0. int x_co. The Color class defines the below constants that can be used to specify colors: Color. setForeground( ) method is used to set the foreground color of the applet means the color of the texts to be written.gray Color.white Color.orange Color.red Color. It͛s general form is : void drawString(String msg.lightGray The below example sets the background color to pink and the text color to magneta: setBackground(Color. .magenta Color. setBackground( ) method is used to set the background color of the applet.darkGray Color.pink).green Color. In a Java window.0. 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. *. 30). } } Output : . public void init() { setBackground(Color. Let͛s create our first applet import java.magneta).cyan). import java. } public void start() { mesg = mesg+" MISS SAMITA". /* <applet code="SimpleBanner" width=750 height=500> </applet> */ public class abc extends Applet { String mesg = " WELCOME TO APPLET".*.applet. setForeground(Color. 50.drawString(mesg.434 setForeground(Color. } public void stop() { } public void paint(Graphics g1) { g1.red).awt. After that we defined the init() method .applet. import java .drawString(msg. then the start() method and at last the paint 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.cyan) and setForeground(Color.Applet. Font.BOLD.435 Let͛s see what are the steps to create a applet from the above example. here we don͛t need the stop() or destroy() method so we have not defined them. public class Second extends Applet { Font f = new Font ("TimesRoman".*.applet and java. Let͛s 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. First we have to import both the packages java.awt . After that we have defined the html tag which is required to makes the applet to run in the web browser. 30) to print the output on the applet. 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. 50.red) method. it͛s a must. 40).awt . name = "Have a nice day " + name . public void init() { name = getParameter ("name") .setColor (Color.class" width=200 height=200 align=TOP> <param name="name" value="Sai"> </applet>*/ .setFont (f). } } /*<applet code="Second. if (name == null) { name = "Java" .drawString (name.blue).436 String name. 50. g1. 50). g1. } } public void paint(Graphics g1) { g1. import java. This method contains the drawString () method apart form. contains the getParameter () method. which take the name of the parameter and returns the value stored at the parameter. font size as 40 and font style as BOLD. which accepts the name (a string) as its parameter. These two methods are used to set the desired font and color respectively. /* <applet code="SimpleBanner" width=750 height=500> <param name="param1" value ="SAI"> </applet> */ public class abc extends Applet { String mesg . two methods namely setFont () and setColor ().437 An instance of the Font class f is declared. The paint () method of the Component class is overridden to execute the paint () method in the class. The init () method declared in line number 7. 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.*.applet. import java.awt. public void init() { . This object has been initialized to contain ͞TimesRoman͟ as font name.*. red). } public void paint(Graphics g1) { g1. } public void start() { mesg = getParameter("param1"). setForeground(Color.drawString(mesg. 50. } } Output : HOW TO PLAY A Audio Clip .438 setBackground(Color.white). 30). au").*.drawString(͞playing music͟. public class player extends Applet { AudioClip a1."sai. public void init() { a1=getAudioClip(getCodeBase().30). } public void paint(Graphics g1) { g1.awt. import java.*. after that i will explain how it is done.play(). } } /*<applet code="Play" width=200 height=200> </applet>*/ . } public void start() { a1.applet.439 Let͛s first see the example below .50. import java. au format music files.awt. Then we call the play method to play the music file.and the music file should reside in the same directory in which the java file is present.event. Below given is given a designer applet to play and stop the music files import java.au will be played.*. The getAudioclip() method returns the URL of the music file specified as it͛s parameter value. We can only play the *.*.440 Output : This program will open a applet and the music file named sai. . import java.awt. public class Play extends Applet implements ActionListener { AudioClip a1. public void init() { b1=new Button("Start").441 import java. } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { a1. add(b1).applet. b1. b2.*. }else{ a1. Button b1."sai. add(b2). } .play().b2. a1=getAudioClip(getCodeBase().addActionListener(this). b2=new Button("Stop").stop().au").addActionListener(this). 70).BOLD.setColor(Color.40)).drawString("This Is Music World". } } /*<applet code="Play" width=200 height=200> </applet>*/ AppletContext . g1.Font.50.442 } public void paint(Graphics g1) { g1.setFont(new Font("Arial". g1.red). AppletContext Code Sample . To use it we have to first create a object of AppletContext using getAppletContext() 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 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. In AppletContext some interesting methods are defined like the getApplet() method . it creates an HTML page in the web browser which is showing the applet. showDocument( ) showStatus( ) method shows the string passed to it as parameter on the status bar at the button of the web browser.it is shown below Example AppletContext context= getAppletContext( ). The example below shows the use of showDocument( ) and showStatus( ) methods .443 AppletContext is an interface which is implemented by an object that represents the applets environment . awt. } } .*. // <applet code="applet1.showStatus( "Puts the message in status bar" ). 22)).444 import java.applet. getAppletContext( ). g1. Font.*.net.BOLD.showDocument(url1). 55. getAppletContext( ).class" width=400 height=100></applet> public class applet1 extends Applet{ public void init(){ try{ URL url1=new URL("http://wallpaper. import java.html").*.drawString(" Hello World".setFont(new Font("Monospaced". 65 ). import java. }catch(MalformedURLException me){} } public void paint( Graphics g1){ g1.net/pkomisar/Flowere. the showStatus() method displays the string passed to it as parameter at the buttom of the applet window . benefitting regular users of Java but the JVM will need to restart each time the browser starts fresh. Note : We can use console output in applet like System. Advantages A Java applet has the following advantages: y y y y y An applet can work properly on "all" the versions of Java installed . it can improve with use: after a first applet is run. Intially the loading time for a applet is noticeable but you will notice it further . the string passed to it will not get displayed on the screen rather it will get displayed in the console. 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.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 JVM is already running and starts quickly. it is used generally for debugging purpose otherwise use of these methods are discouraged.out. When we compare it͛s 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.println() . The awt package present in java is a important package which is needed to a devlop a sophisticated applet. .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. We will discuss all about awt package in the coming chapters. i. The awt is an API. the model for the event handling techniques. Inside the java. Containers. i. The AWT component can be treated as simple beans. The Graphics Class Graphics is an abstract class present inside the java. to control the displaying in a portable fashion. that an API provides libraries.awt package Java facilitates the development of Graphical User Interface components with the help of java. which include Label. we can avail various GUI components. to respond to interactions between the Component and Container in the application.Object . different tools for graphics and images.awt package.awt package.awt package. The awt stands for abstract window toolkit.awt package belongs to the Java Foundation Classes.awt package provides various classes for the development of user interfaces and for painting graphics and images. The JavaBeans architecture can be supported by the AWT.e. It should be mentioned here. LayoutManager. which include Frame. application programming interface. and the LayoutManager.447 Chapter-26 The java. Event system. The signature of this class is: public abstract class java. The java. data-structures and protocols for development of different applications. Also. Components. it facilitates the mechanism for data transfer by cut and paste process through clipboards. for drawing and rendering lines and images. The java. The subsystems are: j j j j j Graphics primitives.awt.awt package which enable the development of Graphical User Interface (GUI) components. Panel and Dialog. There are various subsystems under the java. Button and TextField.e. JFC.lang.Graphics extends java. which contains several classes. 0). we need an environment that enables the process of drawing. vertical coordinate). These methods are:  public void paint(Graphics gph) This method is used at the time of creation of graphics.. the graphics object controls the process of drawing the information on the screen. we cannot perform the operation of drawing.But a type of Graphics class (i. For example. by the help of the Component class present inside the java. the knowledge about the co-ordinate system is required.. To achieve this we need the help of a graphics object. with the help of the GraphicsContext only. A coordinate pair is formed with a combination of x coordinate(i. horizontal coordinate) and y coordinate (i. rectangles and several other shapes For drawing different figures. We can get that environment by the help of GraphicsContext.. The x coordinate denotes the distance moving right from upper left corner. The co-ordinate system provides the scheme for the identification of all possible points on the screen.448 This class provides the declaration of various methods which are used for the purpose of drawing lines.  public void repaint() This method helps to erase the graphics. The graphics object manages the graphics context. As Graphics class is an abstract class.awt package. the co-ordinate of the upper left corner of the screen is (0. The Graphics class makes use of three important methods of Component class for the purpose of creating erasing and updating the graphics.e.  public void update(Graphics gph) .e.e. All coordinates are expressed in integers. Also. Graphics Context and Graphics Object Before drawing any shape on the screen. an object of graphics class) can be defined. it cannot be instantiated.e. i. int d1. we can update the graphics. Some of these methods are which are required for the basic operations related to graphics are give below:  public void drawLine(int c1. .  public void fillOval(int c1.int d2) It is used to draw a rectangle (the out lines only). from the starting co-ordinate (c1. c2 and d2 represents the width and height respectively. int d1. d2).int c2.449 By this method. int d1. int d2) This method is also used to draw a rectangle with its body shaded. int c2. d1) to the ending co-ordinate (c2. C2 and d2 represents the width and height respectively. a filled oval can be drawn on the screen. d1) is the coordinate from where the drawing of rectangle starts.int d1.d1) represents the starting point from where the drawing of the rectangle starts and c2 and d2 represents the width and height respectively. int c2. Java. this method of the Graphics class is used. (c1. int d2): It is used to draw a line. Here (c1.awt contains many methods to handle different operations related to graphics. int d2) With the help of this method. int d2) To draw the outlines of an oval. int c2.d1) denotes the starting coordinate from where the drawing starts.  public void drawRect(int c1.  public void fillRect(int c1. Here also. int c2.  public void drawOval(int c1. We will go in details about the aforesaid methods in the Component class. int d1. (c1. int c3 .int d2. int c3.  public void fillPolygon(int c1[].int d2.  public void drawstring(String message. int d1. int d1.int d3) It is used to draw a the outlines of a rectangle. this polygon is filled with the current color. 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. int pnt) This method does the same operation of drawing a polygon.int d1 . int c1. int c2[]. int d3) . which covers a rectangle that would be formed according to the parameters specified. int c3.  public void fillArc(int c1.int c2 .450  Public void drawRoundRect(int c1. whose corners are in rounded format. int d3) It is used to draw a filled rectangle with its corners in rounded shape.  public void drawArc(int c1.  Public void drawRoundRect(int c1. int c2[]. int d1.  public void drawPolygon(int c1[]. int c2. int d3) The job of this method is to draw an arc on the screen.int d1 .int c2. whose corners are in rounded format.int c2.int d3) It is used to draw a the outlines of a rectangle. int c2) This method simply draws the specified string on the screen starting from the coordinate (c1. int d2. but unlike drawPolygon. c2).  public void fillRoundRect(int c1.int c3 . int c3.int d2 .int c2 .int d2 . green).80. public class A extends Applet { public void init() { System.awt.50.100.*. g. import java.cyan).67.fillOval(60.println("Applet is initialized").98.27}. int x[]={10.451 This method does the same operation as of the drawArc.setColor(Color.5).60. g.98.34}.fillRoundRect(120.80. g.drawLine(40.setColor(Color.cyan). g.25. } public void paint(Graphics g) { g.fillPolygon(x.blue).100. g.20.90.12).*. g.setColor(Color.fillRect(20.setColor(Color.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.fillArc(150.red).y.80.setColor(Color.applet.20. g.60).120).120.100.10.50). g. int y[]={17.150. but this time the arc will be filled with the current color.magenta).100). g. g.  Public void setColor(java.out.40.awt. . Example:import java.90. g.setColor(Color. class" width=400 height=400> </applet>*/ Output:- Color class Color is a predefined class present in the java.25)).105.awt package. set the background and foreground color of the component. } } /*<applet code="A.drawString("Hello GoodMorning".ITALIC. This class facilitates the user to make use of different colors provided by this class to color the graphics.35).setFont(new Font("VERDANA".BOLD+Font. The signature of this class is: . g.Font.452 g. Color java.awt. by the help of the Constructor of the Color class.awt.Color java. which takes three integer values within the range 0 to 255 values.awt.Color java.0) We can get the color red by : new Color(255.0.awt.awt.Paint.Color java. int blue ) For example.0.Object implements java.):  Color(int red.awt.awt.boolean) .255. 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. Each color is a constant as specified by this class.Color white (or WHITE) java.lanag.Color lightGray (or java.Color gray (or GRAY) java.awt.Color java.io. int green.Color java.Serializable 13 predefined colors are provided by this class.awt. We can get the color black by : new Color(0. java.awt.awt.Color java.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 .awt.255) There are also some other constructors of the Color class.Color extends java.e.Color java. These are:  Color(int)  Color(int.awt.awt.0) We can get the color white by : new Color(255. These three integer values are collectively known as RGB (i. red-green-blue values.453 public class java.Color darkGray (or java. This method helps to retrieve the alpha value of the current color of the object.454  Color(float.ColorSpace.awt.float[].0.color.float. The mathods of Component class which use the Color class are  public void setBackground(java.  Color(java.awt.float) This constructor also takes three values in Red-Green-Blue format.awt.Color) Methods of Color class:  public Color brighter() It is used to get the brighter version of the current color.Color) The Color class is also used by the Graphics class to set the color of the object to be drawn.Color)  public void setForeground(java. Font class The java.  public Color darker() It is used to get the darker version of the current color. The signature of this class is : .  int getAlpha() Every color in java has an alpha value which ranges from 0 to 255.0 and 1.awt. The method is  public void setColor(java. But the values are of float type and the value ranges between 0.float) The Color class is used by the methods of the Component class for setting the background and foreground colors.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. TRUETYPE_FONT. then the operating system. CENTER_ BASELINE. protected int size. style and size of the font. Apart from these constants. by default.lang. . provides support for the font. But if we want to manually adjust the font. 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.awt. The availability of Font varies from platform to platform. ROMAN_BASELINE.Serializable If the programmer does not want to use the Font class to manually handle the font. then we have to use the Font class.getFontList().io. 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.getDefaultToolkit(). There are also four constants to define the layout of the font on the screen. TYPE1_FONT. ITALIC. three other variables are used to set the name. int fsize) The first parameter ftype refers to the name of the font. int fstyle. protected int style.Font extends java. HANGING_ BASELINE. We can get the list of font available in different platform through String list_of_fonts [] = Toolkit.Object implements java. These are y y y protected String name.455 public class java. BOLD. blue). we use the Image class to draw an image on the applet.awt package contains an abstract class. This class provides the mechanism to handle the operations that are related to image.Image extends java. gph.20).setColor (Color. This parameter is a constant defined in the Font class.456 Here.BOLD+Font. 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.lang. Image. The third parameter is used to specify the size of the font. If the property does not exists. then it returns null. 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.Font. the second parameter is used to specify the style of the font. The signature for the Image class is: public abstract class java. Image class The java.awt.setFont(fnt). Font fnt=new Font(³Serif´. .ITALIC.Object The image class cannot be instantiated. Generally. } Out of many methods available in the Font class. We can draw an image on the screen. ImageObserver imob) We can retrieve the image from a desired location by the help of one method. The method is: public void drawImage(Image img. The method is: public Image createImage(int imgwidth.200). which is present in both the Applet and Toolkit class. int j. int i. int imgheight) Example: Image img1=createImage (200. String imgpath) Example: public void init() { . The method is: public Image getImage(URL url) public Image getImage(URL url. by the help of one predefined method of Graphics class.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. applet. import java.25.100. gph.drawImage(img. Graphics gph=img.100.setColor(Color.getGraphics().fillOval(90. public void init() { img=createImage(300.pink).70.120.fillRect(150.orange). } } .jpeg´).100.120).awt. } Example:-1 import java. gph.this).*.´ABCD. gph.70). gph.*. } public void paint(Graphics g) { gph.setColor(Color.200).458 Image img1=getImage(getDocumentBase(). public class Image123 extends Applet { Image img. jpg"). public void init() { img=getImage(getDocumentBase().applet. } public void paint(Graphics gph) { gph.30. } . public class Image123 extends Applet { Image img.50.this).*.*. import java.drawImage(im.459 /*<applet code="Image123" width=300 height=300> </applet>*/ Example-2 import java.awt."CAKE. Component extends java. java. The signature of this class is: public abstract class java.awt.460 } /*<applet code="Image123" width=300 height=300> </applet>*/ Component class The java. java.Serializable The Component class has many child classes and they are broadly classified into two categories: Visual Component .awt package provides an abstract class Component which is used to represent the objects on the screen in a pictorial format.Object implements java.lang.awt.ImageObserver.MenuContainer.image.awt.io. These are: Menu MenuBar MenuItem CheckboxMenuItem PopupMenu Button class The java.awt.461 Menu Component Visual Component There are 11 classes.Button extends java.accessibility.awt. which can generate ActionListener on pushing upon it.Acceessible . which comes in the category of the Visual Component.Component implements javax. 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. The signature of this class is: public class java.awt package contains a predefined class Button to develop push buttons. ActionListener) To receive the event generated upon pushing the button.lang. the size of the button varies from one operating system to other.event. the listener is registered with the help of this method. protacted java. public java. Constructos of the Button class: The Button class constructor is overloaded y Button() We can create a button with this constructor. y Methods of Button class: Out of various methods of the Button class.lang. the command name of the event can be retrieved by the method.462 A button can be given a label.awt. The listener can be registered by the help of the addActionListener() method. so that it can receive the events generated upon pushing the button.lang. In order to achieve an action based performance on the button. the commonly used methods are: y public synchronized void addActionListener(java.String getActionCommand() When any event is fired upon pushing the button. Here. public java. Upon clicking the button. Here. But the button won¶t have any label.String paramString() . Button(String l) With this constructor. a button is created having a label l on it. the application has to implement the ActionListener interface and then register the listener. the button size depends on the label size.String getLabel() The label of the button can be retrieved by the help of this method. which generates the ActionListener. an instance of the ActionEvent is sent by the help of the method processEvent(). this method is used. where the components can be drawn.463 The state of a button can be expressed by a parameter string.awt.GraphicConfiguration) Methods of the Canvas class: Out of the various methods of the Canvas class. The label will be set according to the string parameter.Choice extends java. we can select only one item and only that selected item is visible to the user. The Constructors of the Canvas Class: Canvas() Canvas(java. The signature of this class is: Public class java.Component implements java. This method helps to retrieve this parameter string.awt. The Canvas class Canvas refers to a drawing area. The Choice class The java.Graphics) a canvas can be repainted with the help of this method.lang. javax.awt package provides a Choice class by which we can have a popup menu.Accessible The Choice class generates one listener known as ItemListener. public void setLabel(java. clicking on which we can avail the list of items. Also we can have an arrow side to the item.awt.accessibility.awt. . The drawing on the canvas is carried out by the paint() method.String) To set the label of an existing button. the commonly used ones are: public void addNotify() a peer of the canvas is created with the help of this method.awt. and from that menu. public void paint(java.ItemSelectable. Public int getSelectedIndex() By this method the index of the selected item can be retrieved. Methods of the Choice class: The Choice class contains various methods.String getSelectedItem() With the help of this method the currently selected item can be retrieved in String format. public synchronized java.lang. public void insert(java.lang. The most commonly used methods are: public void add(java.String getItem(int) This method helps to return the string from the choice menu.String) an item of String type can be added to the choice menu by this method.String. public int getItemCount() The total number of items present in the corresponding choice menu can be retrieved by this method.String) This method is also used to add an item of String type to the choice menu.Objects[] getSelectedObjects() This method returns an array of Object type having length 1. Public synchronized java.lang.lang.int) . public void addItem(java. The array contains the currently selected items. at the specified index.lang. public java.lang.464 The constructor of the choice class is: Choice() It help to instantiate the choice class. awt.465 This method is used to insert the specified item at the specified position. Checkbox class The java.awt package provides a Checkbox class.lang. A checkbox provides the facility of multiple selections. public void remove(int) We can delete one item from the choice menu according to the specified index by this method. public synchronized void select(int) This method is used to set the selected item to be the item at the specified position.Accesseible The Checkbox class generates one listener known as ItemListener.Component implements java. public void remove(java. Checkbox(java. then the first occurrence of the item is deleted.String) . public void removeAll() With the help of this method.Checkbox extends java. The constructor of Checkbox class Checkbox() This constructor develops a checkbox without having any label on it.lang.awt.accessibility.String) This method is used to delete one item from the choice menu according to the specified.awt. The signature of this class is: public class java. we can erase all the items from the choice menu. If there are more than one item with the same name.ItemSelectable. which is used to develop checkboxes. javax. the state of the checkbox is also specified.io. by this method. CheckboxGroup. i. we have to pass the object of the CheckboxGroup class in the constructor of the Checkbox class. only a single item can be selected at a time.String. boolean) This constructor also develops a checkbox with a label on it.lang.awt. The commonly used methods are: public java. 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.lang. This class is used to develop radio buttons. public void setLabel(java.lang. .466 This constructor develops a checkbox with a label on it. public boolean getState() The state of the checkbox in terms of boolean value is returned by this method. In case of radio buttons.Serializable To generate radio buttons.String) A label is attached to the checkbox.CheckboxGroup extends java. Methods of Checkbox The Checkbox class provides several methods to manipulate the checkbox.String getLabel() This method returns the name or label of the checkbox. The signature of this class is: public class java.lang.e. Checkbox(java. In addition to it.Object implements java. String. The FileDialog is known as a modal dialog.LOAD or FileDialog. FileDialog class The java. FileDialog(Frame.awt class provides a class known as FileDialog. FileDialog(Frame. Methods of FileDialog The commonly used methods of the FileDialog class are: public java.Dialog This class is to display a dialog box on the screen.FileDialog extends java. 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. But.e. CheckboxGroup cx=new CheckboxGroup().String getFile() . Until the dialog window is closed. here the dialog window gets a label on it.467 For example. here the mode for the file is specified. i. int) With addition to the above action. String) This constructor also does the same action as of the above. so that the user can choose a file from it. true).awt. It is a child class of Dialog class. cx. Checkbox cb=new Checkbox(³Male´. The signature of this class is: public class java.lang.SAVE.awt. rest of the application goes to a blocked state. either FileDialog. Label(java. public int getMode() This method is used to get the mode of the concerned file dialog.String) We can set the specified file for the concerned file dialog by this method. this class is used. public void setMode(int) We can set the specified mode for the concerned file dialog.Label extends java.e whether LOAD or SAVE. The signature of this class is: public class java.Component implements javax. For setting the label of different GUI objects.String) The directory name of the concerned file dialog can be set by this method with the specified name.String) This constructor is used to set the label with the specified name. getFileNameFilter() It is used to get the filtered file name from the file dialog.accessibility.String. int) .lang.lang.lang.468 This method is used to retrieve the file from the corresponding file dialog.awt.awt package is the label. The constructors of the Label class are: Label(java. Label class One of the simplest component in the java. public void setFile(java.awt. i.lang. getDirectory() It is used to get the directory name of the concerned file dialog setDirectory(java.Accessible The Label class does not generate any listener. The alignment of the label can have three values which are constants and provided by this class.accessibility. and the list can scroll.469 This constructor set the label with the specified name and the alignment.awt. 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. javax.Component implements java.awt package provides one class List.ItemSelectable.String paramString() A label can be represented by a parameter string. public void setText(java. List(int) . The signature of this class is: public class java.String getText() This method is used to retrieve the text of the concerned label.String) This method is used to set the text for the concerned label by the specified string.lang. Also this class facilitates to visualize more than one item at a time. public java.lang. It is the job of this method to return this parameter string.lang.awt. which enables the user to select more than one item. List class The java.List extends java.awt.Accessible Constructors of List class List() It is used to develop a list of items. we can attach the String as one item at the specified position.lang.String. Public void add(java.470 A list of items can be developed with the specified number of visible line.lang. The signature of this class is: . List(int.awt package provides the Scrollbar class for the purpose of adjustment of the window of any GUI components. Methods of the List class The commonly used methods of the List class are: public void add(java. public void removeAll() This method is used to delete all the items from the list. public void addItem(java.String) We can attach one item. Scrollbar class The java. boolean) Here the lists with specified number of visible items are generated and a mode can be set also.String) The jab of this method is same as that of the add() method. provided by the String parameter. The list can scroll. int) With the help of this method. The ActionListener and ItemListener are fired by the List.lang. at the end of the list by their method. int. And the fourth and fifth parameters refer to the minimum and maximum values respectively. int) This constructor takes five parameters of integer type. public int getMinimum() This method is used to retrieve the minimum value of the concerned scrollbar.Accessible There are two constants declared in the Scrollbar class for setting the mode of the scrollbar.awt. These are: public static final int HORIZONTAL public static final int VERTICAL The scrollbar generates one listener known as the AdjustmentListener.e.471 public class java.awt. .Adjustable. 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.Scrollbar extends java. either HORIZONTAL or VERTICAL. The one sets the mode for the scrollbar. upto which the scrollbar can slide. javax. Scrollbar(int. int. The constructors of the Scrollbar class are: Scrollbar(int) This constructor develops one scroll bar with the specified mode. public int getOrientation() This method is used to retrieve the current orientation of the concerned scrollbar. i. The second one decides the initial value for the scrollbar.accessibility. int.awt.Component implements java. The third parameter determines the size of the scrollbar. The signature of this class is: . we can set the specified minimum value for the concerned scrollbar. we can set the specified int value as the unit increment value for the concerned scrollbar. which is a window and that can fit only one component on it. public void setUnitIncrement(int) Using this method. public int getUnitIncrement() This method determines the increment in unit of the concerned scrollbar. we can set the specified maximum value for the concerned scrollbar. we can set the specified int value as the page increment value for the concerned scrollbar. ScrollPane class The java.472 public int getPageIncrement() This method is used to retrieve the increment in pages of by the concerned scrollbar. public void getValue() We can retrieve the value of the concerned scrollbar by this method. public void setPageIncrement(int) Using this method.awt package provides a predefined class ScrollPane. public void setOrientation(int) The job of this method is to set the provided orientation for the scrollbar. public void setMaximum(int) Using this method. public void setMinimum(int) Using this method. then the ScrollPane automatically brings the scrollbar into existence. will have both the orientations. The signature of this class is: public class java. by default.awt.awt. namely Public static final int SCROLLBAR_ALWAYS Public static final int SCROLLBAR_AS_NEEDED Public static final int SCROLLBAR_NEVER TextField class The java.ScrollPane extends java. The constructors of the ScrollPane class ScrollPane() It develops a scrollpane.Container implements java.awt package provides a TextField class.TextComponent If the text length exceeds to the TextField size. The constructors of the TextField class . ScrollPane(int) It generates a ScrollPane with the specification for displaying the scrollbar. If the component is larger than the size of the ScrollPane window.Accessible We cannot attach more than one component to a ScrollPane.473 public class java. then visibility scrolls to the left.awt. The scrollbar that will be generated. this class declares three constants.accessibility.TextField extends java. TextListener and FocusListener are generated by the TextField. For the conditional requirement of the scrollbar.awt. which is used to take the users inputs in the text form in a single row only. ActionListener. Out of the various methods of the TextField class.awt. in which the user can write something two-dimensionally. TextArea class The java. namely the TextListener and FocusListener .String) It generates a text field and there will be an already String type content according to the parameter specified. int) It constructs a string with specified content and size. TextField(java. both in column and row direction.lang.TextArea extends java. 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.lang.e.474 TextField() This constructor develops the default TextField.TextComponent Two listeners can be generated by the TextArea. The size of the TextField differs from one operating system to another. public char getEchoChar() This method is used to retrieve the character. TextField(int) These constructor developers an empty TextField with the size specified by the parameter. The signature of this class is: public class java.String. i. This is commonly used when we try to enter our password for any account. TextField(java.awt.awt package provides a TextArea class. String) This method is used to attach the specified text in the text area. int) A TextArea will be formed with an already content and the specified number of rows and columns.String getText() To retrieve the content of the TextArea.lang. but the row and column size are specified. public void setText(java.475 The TextArea class declares some constants in order to set the visibility of the scrollbar.lang. TextArea(int.String) This TextArea contains an initial String type message. TextArea(java. this method is used. we can generate an empty TextArea. Methods of TextArea The commonly used methods of the TextArea are: public java.lang.lang. TextArea(java. 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. int. int) Here also. .String. Scrollbar sb1.cb3. Label l1.476 public java. public void init() { setBackground(Color. import java.applet.*. CheckboxGroup cbg.cb2.*. Choice c1.String getSelectedText() The job of this method is to return the selected text to the caller. public class Comp2 extends Applet { Button b1.pink). .cb4. Checkbox cb1. TextArea ta1. Canvas cs1.awt. List li1. TextField tf1. ScrollPane sp1. Example: import java.lang. li1.true).true). c1.yellow). li1=new List(3. b1.setVisible(true).cbg.false).100). .setForeground(Color. cs1.477 b1=new Button("Interface"). l1=new Label("Enter Your Course"). cb3=new Checkbox("Male".setBackground(Color.addItem("Male"). cb2=new Checkbox("Java". cs1=new Canvas(). cs1.add("Female"). cbg=new CheckboxGroup(). c1=new Choice().setSize(100. cs1. cb1=new Checkbox("C").white).add("C").setBackground(Color. c1.cbg.true). cb4=new Checkbox("Female". b1.red). 425.400. li1.Net"). b11.add(b11). add(li1). li1. add(tf1).478 li1. add(sb1). add(c1).Font.add(". add(l1). tf1=new TextField(10). .200)). Button b11=new Button("Learn Java"). ta1=new TextArea(10. sb1=new Scrollbar(Scrollbar. add(sp1). add(b1).BOLD. sp1=new ScrollPane().add("C++"). sp1.10).setFont(new Font("Verdana".HORIZONTAL.10.add("Java").600). add(ta1). 479 add(cb1). add(cb2). } } /*<applet code="Comp2" width=300 height=260> </applet>*/ Output:- . add(cs1). add(cb3). add(cb4). awt. The MenuBar has to be constructed. 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. MenuBar mnbr=new MenuBar().480 Menu components: The java.awt package contains a predefined class MenuBar to manage the topmost level of the window which contains the menu. y The MenuItem has to be constructed y The MenuItem has to be attached with the Menu.awt.MenuComponent implements java. first the MenuBar class has to be instantiated. Let us have a brief look on the various menu components. Step-3 y The Menu has to be attached in the MenuBar. MenuBar class The java.awt package provides various menu component to develop and manage the menus.Accessible In order to develop the MenuBar.MenuContainer.MenuBar extends java. javax.awt. . The MenuBar has to be attached with the Frame. The Frame has to be constructed. The signature of the MenuBar class is: public class java.accessibility. add(mn).MenuItem implements java.awt. fm. Menu class Menu is a predefined class present in the java.Accessible The constructed of the Menu class is Menu(java. the constructor of the Menu class takes a String type parameter which is used as the label of the Menu object.awt.add(item_2).Menu extends java.accessibility.MenuItem) .add(item_1). mn. mn. Frame fm=new Frame(³wordpad´). Then the menu items are added by the help of the add() method.awt package.setMenuBar(mnbr).awt. Now the menu bar has to be attached with the Frame. The methods of the Menu class: y Public void add(java. The signature of the Menu class is: public class java. Here. It is used to develop a pull-down menu containing a number of items that can be selected.awt. Mnbr.MenuContainer.String) The Menu can be instantiated as Menu mn=new Menu(³true´). javax. Then the Menu is added to the 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.lang. y public void remove(int) We can delete one item from the Menu according to the specified index. we can write MenuItem mnitm=new MenuItem(³open´). a string can be added with the Menu component. Then the MenuItem has to be added with the Menu by the add() method.482 By the help of this method. To instantiate the class.Accessible The constructor of this class is y MenuItem(java.add(mnitm). Methods of the MenuItem class .lang. an object of the MenuItem can be attached with the Menu component.awt. Mn.MenuComponent implements javax. 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.lang.awt.String) By the help of this method.accessibility. The signature of this class is: public class java. y public void add(java.MenuItem extends java.String) This constructor is used to develop a menu item which is having a label as specified by the String parameter. y Public void addSeparator() This method helps to add a separator to the Menu component. otherwise it returns false. public void setState(boolean) .String) The label of the menu item can be set as the specified String by the help of this method.String) The methods of this class are: public boolean getState() The job of this method is to check the state of the Menu item.awt. y public void setEnabled(boolean) The label of the menu item can be made selectable or deselect-able according to the boolean parameter. The MenuItem¶s state can be managed by this class. then the method returns true.Accessible The constructor of this class is CheckboxMenuItem(java.lang. then the item can be selected.awt. If the CheckboxMenuItem is selected. If it is true.awt. We can toggle on or off the MenuItem.accessibility. just by clicking the CheckboxMenuItem. javax.483 y public string getLabel() The label of the menu item can be retrieved and returned in the form of a String by this method.CheckboxMenuItem extends extends java. It generates a dual state for the MenuItem components. The signature of this class is: public class java. CheckboxMenuitem class The CheckboxMenuItem is a child class of the MenuItem class.Menutem implements java.ItemSelectable. otherwise not.lang. y public void setLabel(java. it remains unselected. sub=new Menu("Edit"). Pull() { Frame f=new Frame("Menu Demo").setMenuBar(bar). item1=new MenuItem("new"). If true is passed as parameter. bar=new MenuBar(). MenuBar bar.*. f. public class Pull extends Frame { Menu m.item4. //step-1 m=new Menu("File") .awt. otherwise. f.item3. item2=new MenuItem("print"). item3=new MenuItem("Quit").1)).sub. then the CheckboxMenuItem gets selected. CheckboxMenuItem cb1.item2. item4=new MenuItem("edit"). .setLayout(new GridLayout(1. Example-1 import java. MenuItem item1.item5.484 This method is used to set the state of the MenuItem. add(item1).add(item4). //step-2 m. m. sub. m. sub. bar. m.300).add(sub). sub.setSize(300. f. cb1=new CheckboxMenuItem("ok"). } public static void main(String args[]) { Pull p=new Pull(). sub. //step-3 bar. f.add(cb1).add(item3).setVisible(true). } .485 item5=new MenuItem("Cut").addSeparator().add(item2).addSeparator().add(item5).add(m). then that component will be placed at the end of the list.486 } Output:- Container component: The java. A list is maintained for the GUI components that are added to the container. If a component is attached to the container without having any index.awt. To display the components on the screen.awt package provides a class Container which extends to the Component class.Component An AWT Container object is used for the purpose of containing the AWT components. The signature of this class is: public class Container extends java. it is mandatory to attach the components in a container. The order of the list determines the components occupancy inside the container. Methods of the Container class: Component add(Component c): Add the component in the container . 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. int index): Add the component in a container in a specified position Component add(String name. The hierarchy of the child classes is shown in the figure below: .487 Component add(Component c. To make it visible. the container Panel can contain any component and another panel. we have to attach the light weight containers in the heavy weight containers. Frame and the Dialog are heavy weight containers. They are y y y y y Panel Window Applet Frame Dialog Here. So for visibility. For example. the components that are attached to the light weight containers are not visible. . we have to attach the panel with the Applet. But it is not visible to the user. the Panel and Window are considered as light weight containers. the light weight containers are to be nested with the heavy weight containers. The Applet.488 The Container class is divided into five containers. According to java. To make them visible. The signature of this class is: public class java. This class extends the Container class and therefore becomes a container itself.Frame) Applet class .awt.awt. So the user cannot visualize it. The constructor of the Panel calss is: y Panel() Window class The java. Frame or Dialog according to our convenience. an user cannot visualize the Panel itself.accessibility.awt. But. The constructors of the Window class are: y y Window() Window(java.Panel extends java. Panel class: The java.awt.489 Let us have a brief discussion about the containers.awt.accessibility.awt.Accessible Panel is considered as a light weight container in java.Container implements javax.awt package provides a class Panel. we have attach the panel with any of the heavy weight containers like Applet. we have to attach the Window with any heavy weight container like Frame.Container implements javax. In order to make the panel visible to the users.Window extends java. which also extend the java.awt package provides a class Window. The signature of this class is: public class java. It can contain different components as well as other panels also.Container class and therefore acts as a container itself. In ordered to make it visible.Accessible The Window is considered as a light weight container. The constructors of the Frame class: y Frame() It is used to generate a frame without any title. To know in details about the Applet class. which extends to the Window class and therefore acts as a container itself. It is only meant for the standalone application.Window implements java.490 Applet is a class provided by the java. The signature of this class is: public class java. So. So applet is visible to the user.awt. In java. That is why. Frame cannot be executed on the browser.applet package. refer to the java.Frame extend java. These two methods are: y y public void setSize(int. the Applet is considered as a heavy weight container.lang.applet package. y Frame(java. int) public void setVisible(booean) .MenuContainer Frame is considered as a heavy weight container. having a title as specified by the String type parameter. Also they do not have their own main() method.awt. Applets do not have any constructor. it is mandatory for the programmer to use two methods of the Component class.awt class provides a class Frame. Frame class The java.String) This constructor is used to generate a frame. it cannot support the web-enabled applications. The applets can be executed on the web browsers.awt. To properly execute the Frame application. a frame is visible to the user. Font. ScrollPane sp1.BOLD. l1. Choice c1.addItem("Male"). public Frame1() { Frame f1=new Frame("Frame Demo").awt. public class Frame1 extends Frame { Button b1. sp1.*.20)).140)). b1=new Button("Interface").add(b2). l1. c1. List l1.add("C"). b2. l1. b1. l1.add(". l1=new List(3.addItem("Female"). .add("Java").BOLD.setFont(new Font("Arial".true).491 Example: import java. c1=new Choice(). Button b2=new Button("Java Is A Language").setFont(new Font("Arial". sp1=new ScrollPane().Font.add("C++"). c1.Net"). setSize(300. f1.280). f1. f1. } public static void main(String args[]) { new Frame1().setLayout(new FlowLayout()). f1. f1. f1.add(b1).add(sp1).add(c1). } } Output: Dialog class .setVisible(true).492 f1.add(l1) . boolean b) Example import java. Dialog is considered as a heavy weight container.Frame extend java. If it is made modal. is visible to the users. TextField t1. String s. public class Dial extends Frame implements ActionListener { Frame f.493 The java. Box bx. Button b1.*.awt.String.Window As the Dialog class extends the Window class. The dialog boxes can be made modal according to the programmers choice.event. java.lang.Frame. In java. then all other components will be blocked till the dialog box is active. The signature of the Dialog class is: public class java. import java.t2. So. The main job of this class is to develop the dialog boxes.awt.awt.awt.*. The constructors of the Dialog class are: y y Dialog(java.awt package provides a class Dialog.awt.Frame) Dialog(java. it becomes a container.awt. Dial() { . "Dialog Box".500). b1=new Button("OK").setSize(200.setVisible(true). f.setVisible(true).add(t2).getSource()==b1) { String s=t1. f.equals("")) { bx.200). } } } public static void main(String ars[]) { Dial d=new Dial(). . t2=new TextField(20). f.getText().f. if(s==null || s. t1=new TextField(20). bx=new Box(f.add(t1).addActionListener(this). bx.f. b1.setLayout(new FlowLayout()).setSize(500.494 f=new Frame("Display").add(b1). f. } public void actionPerformed(ActionEvent ae) { if(ae.true). addActionListener(this). p2=new Panel().495 } } class Box extends Dialog implements ActionListener { Label l. p1=new Panel().boolean bb) { super(f. b.add(l). Box(Frame f. Panel p1.String s. p1.getSource()==b) setVisible(false).1)). add(p2). } .s.bb). add(p1).add(b). l=new Label("Plz Enter Data"). p2. setLayout(new GridLayout(2. } public void actionPerformed(ActionEvent ae) { if(ae. Button b. b=new Button("OK").p2. 496 } Output:- LayoutManager The java.awt package provides an interface LayoutManager. The child classes are: y y y y y FlowLayout BorderLayout GridLayout CardLayout GridbagLayout .awt. which are used for various layout management process. The preferred size of the java components differs from one platform to another. So.LayoutManager There are five child classes of the LayoutManager. it is the job of the LayoutManager to look after the preferred size of the java components. which facilitates the programmer to place the components in the suitable location. The signature of the LayoutManager is: public interface java. awt package provides a class FlowLayout. . java.497 FlowLayout class The java.io.awt. int) y y This constructor also generates a layout with the specified alignment. Here. There wii be a padding of 5 pixels between the components. i.e. which implements the FlowlayoutManager. These are: y y Applet Panel The constructors for the FlowLayout are: y FlowLayout() This constructor helps to develop a layout.FlowLayout extends java.LayoutManager. 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.Object implements java.awt. FlowLayout(int.Serializable FlowLayout provides five constants for the arrangement of the layout of the components. the first parameter. FlowLayout(int) By calling this constructor a new layout is developed with the specified alignment.lang. the second and the third int parameters denote the horizontal and vertical padding respectively. int. which is having the center alignment. The signature for FlowLayout is: public class java. awt. the components are attached horizontally. then the next component to be attached moves to the next line with the corresponding alignment. If there wii be no more space. add(new Button("Send")). The default alignment of Flowlayout is considered to be CENTER. public class Flow extends Frame { public Flow() { setLayout(new FlowLayout()). import java. add(new TextField(10)). } public static void main(String args[]) { Flow f=new Flow(). setSize(300.498 In case of FlowLayout. } } Output: .300). setVisible(true).*. add(new Label("Name")). lang.String java.String java.lang.lang.lang.Object implements java.lang. int) .LayoutManager2.String java.BorderLayout extends java.awt.String java. Window and Dialog.lang.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.lang. y BorderLayout(int.lang.String java.String java.String java.lang.499 BorderLayout class The java.io.lang.Serializable The BorderLayout class provides some constants to specify the regions.awt package provides another class to manage the layout of the components like Frame.String java.lang.String java. The signature of this class is: public class java. java.lang.String java.String java. This class is known as BorderLayout.awt. 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. with the horizontal and vertical gap as specified by the parameters.awt. y public int getVgap() This method determines the vertical gap between the components.500 This constructor generates a new border layout. To explicitly set the layout as BorderLayout.applet. y public void setHgap(int) This method provides a specific Horizontal gap between the java components. Example: import java. y public void setVgap(int) This method provides a specific vertical gap between the java components. import java. The BorderLayout class does not provide any relaxation for the preferred size. 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.*. public class Border extends Applet .*. SOUTH). add(b5).EAST).BorderLayout. add(b2. Button b3=new Button("East").BorderLayout.NORTH). Button b2=new Button("South").501 { public void init() { setLayout(new BorderLayout()). add(b1.BorderLayout. Button b4=new Button("West"). add(b4. } } /*<applet code="Border" width=300 height=300> </applet>*/ Output: . add(b3.WEST). Button b5=new Button("Center").BorderLayout. Button b1=new Button("North"). Serializable The GridLayout class.Object implements java. The constructors of the GridLayout class are: y GridLayout() This constructs creates a new grid layout. java.awt.awt package contains the GridLayout.awt. The GridLayout works like a spreadsheet. the GridLayout class does not provide any support for the preferred size. All the components in case of the GridLayout acquires same size.GridLayout extends java. by default. .io. with the default specifications.LayoutManager. Also. does not support to any Container.lang.502 GridLayout class The java. The signature of this class is: public class java. 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 int getVgap This method is used to determine the vertical gap between the components in the concerned 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. . y public int getHgap() This method is used to determine the horizontal gap between the components in the concerned layout.503 y GridLayout(int. int) By the help of this method we can generate a grid layout with specified size of rows and columns. 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 int getRows() The number of rows of the concerned layout can be derived by this method. Methods of the GridLayout class y public int getColumns() We can determine the number of columns in the concerned layout by this method. Button b4=new Button("Button-4"). add(b1). add(b2).*.5. setBackground(Color.10)). Button b2=new Button("Button-2").awt.2. add(b4). add(b3). Example import java.504 y public void setVgap() This method is used to set the specified value for vertical gap between the components in the concerned grid layout. public class Grid extends Applet { public void init() { Button b1=new Button("Button-1"). setLayout(new GridLayout(2.lightGray). . Button b3=new Button("Button-3"). 505 } } /*<applet code="Grid" width=300 height=300> </applet>*/ Output: CardLayout class The java. The signature for this class is: . only one component can be made visible at a time.awt package provides the CardLayout class by the help of which. The methods are void next() This method is used to visit the next component of the current component. CardLayout provides some predefined methods .lang. by the help of which we can see other components.LayoutManager.awt.CardLayout extends java. CardLayout(int. by default. does not support any container. void last() This method is used to visit the last component of the layout. void previous() This method is used to visit to the previous component of the current displayed component.Object implements java. a new CardLayout with specified horizontal and vertical paddings will be generated. void first() This method is used to visit the first attached component of the layout. The constructor of the CardLayout is CardLayout() By this constructor. we get a new CardLayout with default specifications. It does not provide support for the preferred size.Serializable The CardLayout. . int) By the help of this constructor. In case of CardLayout.io. more than one component can be attached.506 public class java. java.awt. add(l1). Label l1=new Label("Panel-1"). import java.awt. p.BOLD. p1=new Panel(). public void init() { p=new Panel().507 Example: import java.Font.blue). cl=new CardLayout(). l1. l1.*. p1.b2. l2. public class CardDemo extends Applet implements ActionListener { Panel p.setFont(new Font("Sans Serif". .40)).p1.event. CardLayout cl.applet.red).awt.p3. Button b1.setBackground(Color.*.setForeground(Color. l1. import java.p2.yellow).setLayout(cl).setBackground(Color.*. Label l2=new Label("Panel-2"). b1.white)."First"). p. add(b2).BOLD. p2. add(b1).add(l3).add(p3.green).setForeground(Color."Second").508 l2. p.setFont(new Font("Verdana".add(p1.getSource()==b1) . b1=new Button("NEXT").addActionListener(this). b2=new Button("Previous"). l2. p2=new Panel().BOLD.setBackground(Color."Third"). p3.setFont(new Font("Arial". b2. p3.add(l2). p3.40)). p.Font. p3=new Panel().40)). l3. Label l3=new Label("Panel-3").setForeground(Color.addActionListener(this).Font. add(p). } public void actionPerformed(ActionEvent ae) { if(ae.add(p2.black). In this case a component can occupy more than one cells at a time.io.awt.next(p).lang.previous(p). . }else{ cl. The signature of this class is: public class java.GridBagLayout extends java.509 { cl.Serializable In case of GridBagLayout. java. the area occupied by the component is known as the display area.Object implements java.awt. } } } /* <applet code="CardDemo" width=500 height=500> </applet> */ GridBagLayout class This is a predefined class of java. the entire container is divided into cells of equal size.LayoutManager2.awt package which implements the LayoutManager interface. The adjustment mode is denoted by FILL. Button b1. .applet.NORTHEAST GridBagConstraints.awt.l4.SOUTHEAST GridBagConstraints.*.CENTER GridBagConstraints.tf3.Font.BOLD.*. import java.setFont(new Font("Verdana". the size of the components can be adjusted according to our requirement. then the placement of the component is decided by the anchor. public class GridbagTest extends Applet { TextField tf1. public void init() { l1=new Label("Collect The Information") .l2.SOUTH GridBagConstraints.SOUTHWEST GridBagConstraints.510 Here.tf4.l5. l1. The values of the anchor are: j j j j j j j j j GridBagConstraints.EAST GridBagConstraints.NORTH GridBagConstraints.WEST GridBagConstraints.l3.NORTHWEST Example: import java. Label l1.tf2. When the component is smaller than its display area.24)). l2=new Label("Enter Your Name"). gbag.Font.14)). l4.BOLD.REMAINDER.RELATIVE. gbc.14)).setFont(new Font("Verdana".weighty=1. gbc.setConstraints(l1. tf4=new TextField(15). tf2=new TextField(15). l5=new Label("Enter Mobile Number"). gbc.0.anchor=GridBagConstraints.14)). l5.NORTH.setFont(new Font("Verdana". GridBagConstraints gbc=new GridBagConstraints().511 l2.BOLD. l4=new Label("Enter Your State").14)).gridwidth=GridBagConstraints. b1=new Button("Submit"). GridBagLayout gbag=new GridBagLayout().gbc) . gbc. gbc.BOLD.BOLD.anchor=GridBagConstraints. setLayout(gbag). l3.Font. .gridwidth=GridBagConstraints.Font.setFont(new Font("Verdana".setFont(new Font("Verdana". l3=new Label("Enter Your City").Font. tf1=new TextField(15). tf3=new TextField(15).EAST. CENTER.gridwidth=GridBagConstraints. gbag. add(tf3).REMAINDER. gbc. gbc. add(l2).RELATIVE.gridwidth=GridBagConstraints.gbc). gbc.REMAINDER. .gridwidth=GridBagConstraints. gbag. gbag. gbag.setConstraints(l4. gbc.gbc). add(tf2).gbc) . gbc. gbc.gbc).gridwidth=GridBagConstraints.gridwidth=GridBagConstraints.gbc) .setConstraints(l5. gbag.REMAINDER.REMAINDER.setConstraints(l3. gbag. add(l3).setConstraints(b1.gridwidth=GridBagConstraints. add(tf1).anchor=GridBagConstraints.setConstraints(tf2.setConstraints(tf1. gbag.gbc) . add(l1). add(l4).gridwidth=GridBagConstraints. gbc. gbc.gbc).setConstraints(tf3.gbc).RELATIVE.setConstraints(tf4.setConstraints(l2.RELATIVE.512 gbag.gbc) . gbag. add(tf4). add(b1).513 add(l5). } } /*<applet code="GridbagTest" width=300 height=300> </applet>*/ . y y 1. the x and y co-ordinates at which this event occurred. In an Object oriented approach it is also possible to handle events. handleEvent ( ) method is implicitly called for every event object. pressed the key. it is received by one or more listener that acts on that event.0 model the total event handling procedure is done through two methods action( ) and handleEvent ( ) method.EventListener. When an event is fired. Clicking on the mouse. 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. In java AWT when an user generates an action. The fundamentals of event-driven programming are used to translate events to code.514 Event Handling The program is able to respond some dynamic actions in an interactive environment. There are two popular model was used to handle event in java. .util. Event types are encapsulated in a class hierarchy rooted at java.0 model or Hierarchical model 1.2 model.EventObject.util. action( ) method having three parameters namely ± the event name that has been occurred. 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. Event Delegation Model In event delegation model. Then the event handlers can respond to the events. then AWT generates an event and communicates these events to event handlers. This model having various problems and the problems are solved through 1.2 model or Delegation model In 1. j In java Listener is an object that implements a specific EventListener interface and extended from the generic java. select an item from List is an example of performing actions. etc. etc .515 j An Adapter class is an anonymous inner class that includes all methods specified by the corresponding interface but not providing any functionality. j ItemEvent (³item state has changed´).) j FocusEvent (component got focus. lost focus ) j InputEvent j KeyEvent (component got key-press.) 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 component¶s model. . key-release. The semantic Events classes defined by the AWT are as follows: j ActionEvent (³do a command´). moved. etc. j AdjustmentEvent (³value was adjusted´).) j MouseEvent (component got mouse-down. Types of event handling The AWT provides two conceptual types of events such as low-level event and semantic event. The low-level event classes defined by the AWT are as follows: j ComponentEvent (component resized. 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. mouse-move. import java.awt.awt.*.event package. ActionListener:This is one interface suggested by the event delegation model. The signature for this interface is: public interface java.b2. Example:import java.event.event.ActionListener extends java.event.EventListener This interface provides the declaration for an abstract method: public abstract void actonPerformed(java. 1.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. public void init() .awt. //1st step public class Button1 extends Applet implements ActionListener //2nd step { Button b1.util.b3.awt. This interface is declared within the java.*. import java.awt.ActionEvent) This method is used to receive the action events.*.applet. }else{ setBackground(Color. }else if(ae. add(b1).addActionListener(this). } .addActionListener(this). b3. b2.addActionListener(this). b3=new Button("Blue"). } //step-4 public void actionPerformed(ActionEvent ae) { if(ae.517 { b1=new Button("Red"). add(b2).blue). b2=new Button("Green").getSource()==b2) { setBackground(Color. add(b3).red).getSource()==b1) { setBackground(Color. //3rd step b1.green). awt.event package.EventListener The interface contains the declaration of an abstract method : public abstract void itemStateChanged(java.ItemListener extends java.util. The signature for this interface is: public interface java.awt.event.ItemEvent) This method is used to receive the events generated from the Checkbox.518 } } /*<applet code="Button1" width=220 height=200> </applet>*/ 2. Choice and List. Example:- . ItemListener This interface also inhabits inside the java.awt.event. *. String msg="". cb2.cb4. cb1. add(cb1). } . cb2=new Checkbox("Sybase". add(cb2).awt.addItemListener(this).applet. cb4=new Checkbox("DB2". cb3=new Checkbox("Infomix".awt.event.cbg. public class Radio extends Applet implements ItemListener { CheckboxGroup cbg. cb4. cb1=new Checkbox("Oracle".cbg. add(cb3). import java.cbg.addItemListener(this).*. Checkbox cb1.true).*.addItemListener(this).cb2. import java.cb3.false). cb3.519 import java. public void init() { cbg=new CheckboxGroup(). add(cb4).false).false).cbg.addItemListener(this). 170. AdjustmentListener . g.120).drawString(msg. } public void paint(Graphics g) { msg="Current Selected Item Is ". msg+=cbg. } } /*<applet code="Radio" width=400 height=400> </applet>*/ 3.520 public void itemStateChanged(ItemEvent ae) { repaint().getLabel().getSelectedCheckbox(). AdjustmentEvent) This method is used to receive the events generated by the component Scrollbar.521 This interface is provided in the java.HORIZONTAL.awt.BorderLayout. public void init() { setLayout(new BorderLayout()).event.addAdjustmentListener(this).1. add(h1.awt.NORTH).v1. h1.v2.util. The method is: public void adjustmentValueChanged(java. TextField tf1.EventListener The AdjustmentListener contains the declaration of one abstract method.event.h2. Panel p1.event.1. h1=new Scrollbar(Scrollbar.awt. Example:public class Scroll extends Applet implements AdjustmentListener { Scrollbar h1.200). . The signature for this interface is : public interface java.1.AdjustmentListener extends java. 200). add(v1.getValue()).1.BorderLayout.VERTICAL.getValue()).522 h2=new Scrollbar(Scrollbar. add(p1).BorderLayout. add(v2.setValue(h1.setText("Horizontal Location :. p1.addAdjustmentListener(this). tf1.200). v1=new Scrollbar(Scrollbar.BorderLayout.HORIZONTAL. v2=new Scrollbar(Scrollbar.1. h2. add(h2.1.SOUTH).200). p1=new Panel().1.add(tf1).getValue()). h2.1. v2.VERTICAL. tf1=new TextField(18).WEST).1. } public void adjustmentValueChanged(AdjustmentEvent ae) { if(ae.addAdjustmentListener(this).addAdjustmentListener(this).1. v1.1. .EAST).1."+h1.setValue(h1.getAdjustable()==h1) { h1. 523 } if(ae."+v1.getValue()).setText("Horizontal Location :.setValue(v1.setValue(h2.setText("Vertical Location :.getValue()).setValue(h2. tf1.getAdjustable()==h2) { h2.getValue()).getValue()). h1. } } } Output: . v1.setValue(v2.getValue()). tf1.getValue()). } if(ae.getValue()).setText("Vertical Location :. } if(ae.getAdjustable()==v1) { v1."+v2. tf1.setValue(v1.getValue()). v2.getAdjustable()==v2) { v2.setValue(v2."+h2.getValue()). event.awt.awt.*. .TextEvent) This method has to be defined in ordered to receive the events generated by the components TextField and TextArea. The signature of this method is: public interface java.awt. TextListener The TextListener is an interface suggested by the event delegation model and present in the java. Example:import java.event.*.util.524 4.awt.TextListener extends java.EventListener The interface contains one abstract method which is declared as: public void textValueChanged(java.event package.awt. import java.event. t1.getText()). } public void textValueChanged(TextEvent te) { t2.addTextListener(this). t2.applet. } } /* <applet code="CopyText" width=400 height=400> </applet> */ .10).*. public void init() { t1=new TextArea(10.t2.setText(t1.10). public class CopyText extends Applet implements TextListener { TextArea t1. t2=new TextArea(10.addTextListener(this).525 import java. add(t2). add(t1). awt.event. FocusListener The FocusListener is an interface present inside the java.FocusEvent) Suppose. is associated with the focusLost() method. The signature of this class is: public interface java. But. KeyListener . the textfield which will be in use. So.event.526 5.util. the user can write in a single text field at a time.EventListener This interface provides the declaration for two abstract methods: y y public void focusGained(java.awt.event package.event. TextField.FocusListener extends java. 6. is associated with the focusGained() method and the other textfield which is not in use at that particular point of time. The two abstract methods of the FocusListener interface are used to receive the events generated by the TextArea. there are two text fields attached to the screen.awt.awt.FocusEvent) public void focusLost(java. Button and Choice Components. MouseEvent) public void mouseExited(java.awt.event.awt. The signature for this interface is: public interfaced java.awt.event.KeyListener extends java.event.awt.awt.event. The signature of this interface is: public interface java.event.MouseEvent) public void mouseClicked(java.event package.event.event.awt.MouseMotionListener extends java.awt. The signature of this interface is: public interface java.awt.MouseListener extends java.EventListener The abstract methods present inside this interface are y y y public void keyPressed(java.event.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. released or typed.awt.EventListener There are five abstract methods declared in this interface.awt.KeyEvent) public void keyReleased(java.util. These are . MouseListener This interface is suggested by the event delegation model and situated in the java. 7.util.event.awt. MouseMotionListener y y y y y The MouseMotionListener is used to handle the events generated by all type of components.event.KeyEvent) All of the above methods are used in case of a key pressed.EventListener There are two abstract methods declared in this interface. 8. These are: public void mouseEntered(java.MouseEvent) public void mouseReleased(java.KeyEvent) public void keyTyped(java.awt.527 This interface is also present in the java.MouseEvent) public void mousePressed(java.util.event package.awt. gc. gc.*. GraphCanvas gc.*.setVisible(true). public class CanvasDemo extends Applet implements MouseListener.awt.setSize(300. public void init() { gc=new GraphCanvas(). gc.setBackground(Color.awt.100).MouseEvent) Example:import java.*. import java.528 y y public void mouseDragged(java. addMouseMotionListener(this).event.200). } public void mouseDragged(MouseEvent me) { . addMouseListener(this).MouseEvent) public void mouseMoved(java.event.awt. add(gc).applet. gc. import java.blue).awt.MouseMotionListener { int x.event.setLocation(100.y. y=me.getX().Font.getY(). gc.setColor(Color. y=me. .setLocation(x. } 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.y). } public void mouseMoved(MouseEvent me) { } public void mouseClicked(MouseEvent me) { x=me.getY(). gc.white).529 x=me.getX().setLocation(x. g.30)).setFont(new Font("Sans Serif".y).BOLD. setColor(Color.50.50). g.40.10. g. } } /* <applet code="CanvasDemo" width=500 height=500> </applet> */ 9.fillRect(40.pink). ContainerListener .40).530 g.drawString("Painting On Canvas". event.event.event. ComponentListener This interface is suggested by the event delegation model and inhabits in the java.event.event.awt.WindowListener extends java.awt.awt.ComponentEvent) componentMoved(java.util. The methods are: y y y y public public public public void void void void componentShown(java. The signature of this interface is: public interface java.event.awt. The signature for this interface is: public interface java.ContainerListener extends java.event. These are: y y public void componentAdded(java. The signature of this class: public interface java.EventListener .ComponentListener extends java.awt.event package.ComponentEvent) componentHide(java.awt.awt.awt.event package.awt.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.event. WindowListener This is the last listener interface provided by the event delegation model and placed in the java.ContainerEvent) 10. This interface declares two methods.event.EventListener The ContainerListener provides the mechanism to receive the event generated by all types of containers.ContainerEvent) public void componentRemoved(java.util.ComponentEvent) 11.util.event package.awt.ComponentEvent) componentResized(java.531 This interface is suggested by the event delegation model and situated in the java.awt.awt. *. import java.awt.awt.event. 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.200).awt.WindowEvent) windowDeiconified(java.event.awt.event. f1.WindowEvent) windowDeactivated(java.awt. public WindowDemo() { f1=new Frame("Winow Event").setVisible(true).event.awt.WindowEvent) windowOpened(java.WindowEvent) Example:import java.awt.WindowEvent) windowIconified(java.532 There are seven methods declared in this interface for handling the events.WindowEvent) windowClosed(java.event.awt.event. f1. } public void windowActivated(WindowEvent we) { .WindowEvent) windowClosing(java. public class WindowDemo extends Frame implements WindowListener { Frame f1.setSize(200.event.awt. f1.*.event.addWindowListener(this). But the over ridden methods present there in the adapter class does have any codes at all. . Adapter classes are treated as anonymous inner class. } public void windowOpened(WindowEvent we){} public static void main(String args[]) { WindowDemo d=new WindowDemo().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). 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. } } 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. To avoid the problem sun microsystem introduced adapter class for each and every listener that have more than one methods. An adapter class implements event listeners. event. public Window1() { .awt.*. import java.b2.534 WindowAdapter import java.awt.*. Button b1. public class Window1 extends Frame implements ActionListener { Frame f1. addActionListener(this).setBackground(Color.blue). b1=new Button("Red").red).getSource()==b1) { f1. f1. f1.addActionListener(this). f1. }else{ f1. f1.setLayout(new FlowLayout()).add(b2).535 f1=new Frame("Frame Demo"). b2.setSize(200. b2=new Button("Blue").setBackground(Color. b1.200). f1. } public void actionPerformed(ActionEvent ae) { if(ae.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent aw) { System.setVisible(true). .add(b1). } } ).exit(0). f1. *. .event. } } MouseAdapter.536 } } public static void main(String args[]) { Window1 w1=new Window1(). import java.y.awt.awt. import java. public void init() { gc=new GraphCanvas1(). GraphCanvas1 gc.*.*. public class CanvasDemo1 extends Applet { int x. MouseMotionAdapter import java.applet. } }). addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent me) { x=me. gc.getX(). } } class GraphCanvas1 extends Canvas . gc.setSize(300.setLocation(100.y). gc. y=me.getX(). } }). y=me. gc.setLocation(x.blue).537 gc.100).setBackground(Color.setVisible(true). add(gc). gc.setLocation(x.200). addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { x=me.getY().getY().y). setColor(Color.50).pink).30)).Font.BOLD. g.setColor(Color.50.40. g. } } /* <applet code="CanvasDemo1" width=500 height=500> </applet> */ .white).10. g.538 { public void paint(Graphics g) { g.drawString("Painting On Canvas".setFont(new Font("Sans Serif".fillRect(40. g.40). setBackground(Color.j. b2=new Button("RESUME"). Button b1. import java.ActionListener { Thread t=null. add(b3). int i.applet. add(b2).awt. .orange). b2.b2. boolean stopFlag. add(b1). b1.event.b3.class" width=400 height=400> </applet>*/ public class BallRunning extends Applet implements Runnable.java import java.*. add(b4).*.awt. b3=new Button("SUSPEND").addActionListener(this).addActionListener(this). /*<applet code="BallRunning.b4. import java. public void init() { b1=new Button("START").*. b4=new Button("STOP").539 BallRunning. resume(). stopFlag=false.suspend(). t. if(o==b1) { if(t==null) { t=new Thread(this).start(). if(o==b3) t. b4. if(o==b4) { if(t!=null) .540 b3.getSource().addActionListener(this).addActionListener(this). } public void actionPerformed(ActionEvent ae) { Object o=ae. } } if(o==b2) t. . t=null.j--) { try{ repaint(). } } } public void run() { for(i=0.fillOval(i+85.80).setColor(Color.j=400.blue). .stop(). if(stopFlag) break. g.i++.80.541 { stopFlag=true.sleep(30). Thread.i+45. t. } catch(InterruptedException e){} } } public void paint(Graphics g) { g. the main thread. .j-45. This is done by the underlying OS. g.setColor(Color.80.red). therefore a particular colors with a fixed intensity is fired to the moniter screen. } } Here. Othe thread just moves the ball in different direction.80). since the applet is displayed constantly . the two balls simultaneously move in random inside the view port. I think this is quite justified because the main do its unique task. In the main thread the applet program executes and in the child thread t.fillOval(j-15.542 g. I have used two threads. In. l2.*.b2.*. public class mballs extends Applet implements Runnable.l2. tf1=new TextField(5).b4. .java import java. import java. Label l1.awt.tf1.applet.b3. tf2=new TextField(5). l2=new Label("No of Balls").event. import java.awt.*. b3=new Button("pause").orange). b1=new Button("start").543 mballs.orange). b4=new Button("Resume"). TextField tf2.setForeground(Color.ActionListener { Thread t=null.setForeground(Color. int l. Button b1. b2=new Button("stop"). public void init() { l1=new Label("Enter Speed in ms"). l1. add(b2).addActionListener(this).black). t=null. add(b4). add(l2).start().addActionListener(this). } . add(b3). b3. } public void actionPerformed(ActionEvent ae) { if((ae.getSource()==b1)&&(t==null)) { t=new Thread(this). setBackground(Color. add(tf1).stop(). add(l1). t. } else if((ae. b4. b2.addActionListener(this).544 b1. add(b1).addActionListener(this).getSource()==b2)&&(t!=null)) { t. add(tf2). k++) { .resume().545 else if((ae.getSource()==b4)&&(t!=null)) { t. } } public void run() { for(.getText()))%1000.parseInt(tf2. Thread.. } catch(Exception e){} } } public void paint(Graphics g) { for(int k=0.getText())).) { try { repaint().k<(Integer. } else if((ae.getSource()==b3)&&(t!=null)) { t.suspend().sleep(Integer.parseInt(tf1. 546 l=((int)(Math. g.io. .((int)(Math.rand om()*1000))%500+100. g.random()*1000))% 254.random()*1000))%254)).((int)(Math.*.l.random()*1000))%254.fillOval(((int)(Math.setColor(new Color(((int)(Math.random()*1000))%100.java import java.l).random()*1000))%500+100. } } } /*<applet code="mballs" width=800 height=650> </applet>*/ ncolor.((int)(Math. b2.applet.b4.addActionListener(this). public void init() { l=new Label("Enter Speed in ms"). b1=new Button("start").ActionListener { Thread t. b2.547 import java. int x.*. b3.awt. Button b1. .addActionListener(this). import java.event.*. b3=new Button("pause"). Label l. TextField tf. b4. public class ncolor extends Applet implements Runnable.*. b4=new Button("Resume"). tf1=new TextField(5). b2=new Button("stop"). import java.y. add(l).b3. b1.awt.*.tf1. String s.addActionListener(this). import java. tf=new TextField(20).net.addActionListener(this). t=null. } else if((ae.getSource()==b1)&&(t==null)) { update(getGraphics()).getSource()==b4)&&(t!=null)) { .start(). add(b4). t=new Thread(this).getSource()==b3)&&(t!=null)) { t.548 add(tf1). t.stop(). } public void actionPerformed(ActionEvent ae) { if((ae. add(tf). } else if((ae. } else if((ae. add(b1).getSource()==b2)&&(t!=null)) { t. add(b2). add(b3).suspend(). resume().50)). Graphics g=getGraphics().setColor(new Color(((int)(Math.random()*1000))%254)).i++) { if(s.((int)(Math.random()*1000))%254.getText().setFont(new Font("Monotype Corsiva".BOLD. for(int i=0. draw().Font.charAt(i)!=' ') { try { getAudioClip(new URL(getCodeBase(). } } public void run() { x=y=0.length(). .((int)(Math.play(). "chime.549 t. } public void draw() { s=tf.random()*1000))% 254.au")). g.i<s. } catch (Exception e) {} } g. drawString(String.getText())).parseInt(tf1.valueOf(s.y+=25.100+x.sleep(Integer. x+=25.java .100+y).charAt(i)).550 g. try{Thread.} catch(Exception e){} } } } /*<applet code="ncolor" width=400 height=400> </applet>*/ Image1. cyan).applet.100). public class Image1 extends Applet implements Runnable { Image im1.start().getGraphics(). public void init() { im1=createImage(100. } public void stop() { flag=false. int i=0. Graphics g. boolean flag=true.Applet.551 import java. } public void start() { t1=new Thread(this).awt. import java.*. setBackground(Color. t1. } public void run() { . Thread t1. g=im1. g.10. g.setColor(Color. g.22)). try{ Thread.i).this).setColor(Color.100.i). g. g.i.drawString("Sai".10.BOLD.sleep(100). } } /*<applet code="Image1" width=200 height=200> .10.fillRect(10.black).Font. }catch(InterruptedException ie) { } } } public void paint(Graphics g) { i+=5. if(i>=100) i=5.setFont(new Font("Verdana".drawOval(30.552 while(flag) { repaint(). g.white).drawImage(im1. g.60.100).i. 553 </applet>*/ ` . if you have ever google through AWT classes you might have come across the term ³peer component´ the alias name given to AWT.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. internally system dependent native codes are executed & the required system call is performed in to display various visual components on the screen. let me first address those drawbacks. check-box. Why this name is given? Whenever you develop any GUI application in AWT. With the introduction of JFC. So. As a java developer you can feel that while performing GUI development in AWT. listener attached to it is invoked to perform the desired task. Whenever any action is performed on those components. Actually when the AWT class file is executed by JVM. So the ³LOOK & FEEL´ component of AWT is platform dependent. This is what we call the peer component. JVM requests the underlying OS to make appropriate system call to develop the GUI & return it to the JVM. the look & feel can either be system dependent or independent. Again here also the task is performed by the system call of the underlying OS. AWT has drawbacks!! Yes it does have. A GUI contains various components like button. The drawbacks of AWT class are removed by the introduction of JFC. text-field etc. you are not sticking to the platform independent features & that is why GUI looks different in different platform. 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) . The visual display component & the action component in together is called ³LOOK & FEEL´ component. 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 . State means. . This package contains quite rich set of classes and methods for the development of various visual objects like button text-area. Just check hierarchical levels in the diagram. check-box etc. normally these visual objects and components light weight and fallow the MVC architecture. JComponent class resides at the top. this is done by the invocation of isSelected() method. JComponent:According to the order pf hierarchy. 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. When ever user interacts with these visual objects.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. Model represents the state of visual objects. MVC stands for model view controller. Class: this class is meant to develop various geometrical shape. This class is extended by all the visual components of JFC. y y y y Briefly about swing For gui development programmer often uses JFC methods and constructors. assume that there is a radio button in the GUI and whether it is selected or not represents its state or model. hence its methods & constructors are available to them. etc are embedded . They are 1. the core class of javax. this GUI is called window pane.scroll bar . Content pane .swing package is used to develop GUI in which various visual objects like text field.556 Window panes Jframe class. radio button . chech box . There are four types of window panes are available. If you are attaching some visual components to the foreground of any GUI they are attached to the glass pane window. .557 2. 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. Glass pane 1. you can communicate with this pane with the use of getContentPane() method . 3 Layered pane This pane resides beneath the root pane . 2. normally it is used to embed a collection of objects. Root pane This window resides just below the glass pane window. 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. 4 Content pane This pane lays below all the above defined planes . Root pane 4. This can be performed by the invocation of method getRootPane() . We can communicate with the getLayeredPane () method. 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. Layered pane 3. setVisible(true).swing. public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME").558 whenever you are attaching any visual objects to GUI u have to attach them to one of these panes. w1. w1. } } Output : . Your first window Enough theory let¶s have a programming example import javax.*.300).setSize(300. *. Although you have clicked the close button . Some thing is lacking for the complete termination of the program . 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. This method is called when you click the close button.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 it¶s argument. the default size that is passed to the setSize() method is 0 pixel x 0 pixel . } } setDefaultCloseOperation() this method upon calling removes the program from the memory permanently. public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME").setSize(300. the program is not going to removed from the memory this is because of it¶s TSR characteristics. w1. w1. setDefaultCloseOperation(JFrame. Now there is a interesting thing associated with this program. w1.EXIT_ON_CLOSE).300). Just see the example below import javax. the program is not going to be removed from the memory this is because of it¶s TSR characteristics. the solution is to invoke the setDefaultCloseOperation() method.setVisible(true). .swing. As the name suggests setSize() sets the size and setVisible() makes the window visible. *. import java. when the GUI is resized.560 BoxLayout class BoxLayoutManager provides implementation techniques to embed various visual objects either vertically or horizontally. It shows similarity with the FlowLayout. You can specify the orientation of the BoxLayout during the construction. The following example emphasizes the utility of BoxLayout. BoxLayout follows the principle to maintain the optimum size of various visual objects properties. import java.event. import javax.*. These visual objects or you can say the components are not going to wrap. class BoxDemo extends JFrame { public BoxDemo() { setTitle("Box Layout").swing. Suppose the components are gathered around the Y_AXIS then the automatic resizing is done by the BoxLayout class.awt. Theis Layout manger solely belongs to the JFC.setLayout(new BorderLayout()) . JPanel contentpane =( JPanel)getContentPane().*.*.awt. . contentpane.util. import java. This Layout facilitates to add visual objects vertically or horizontally maintaining a stack principle. The predefined fields X_AXIS & Y_AXIS is used to arrange the visual objects. contentpane. b. } } public static void main(String args[]) { BoxDemo b=new BoxDemo() .exit(0).add("North".cancel). addWindowListener(myapp). contentpane.Y_AXIS).561 Box mainbox=new Box(BoxLayout.400). } private class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.ok). JButton cancel=new JButton("CANCEL"). b.add("South". JButton ok=new JButton("OK").setSize(400. myadapter myapp=new myadapter() . } } Output .setVisible(true). swing. .*.*. import java.awt. import javax.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. EXIT_ON_CLOSE).563 import javax. w1. setDefaultCloseOperation(JFrame.setBackground(Color. public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME"). import java.*. w1. } } Output: . c1. w1. Container c1=w1.*.300).swing.awt.setVisible(true).setSize(300.green).getContentPane(). . By the container object.awt. This method takes argument as various static predefined fields of Color class. g. The background color can only be added to the container.100).*. This package makes the setBackground() method available to you.awt.* package.564 Steps to add color y y y y Import the java. Adding text to the window JFC provides two ways to display text in a window frame 1. In this technique you have to extend the JPanel class scince paintComponent() is available there.swing. invoke the setBackground() method. This is done by calling the getContentPane () methodthrough w1.*.drawString("Hello world". Let͛s have a coding example First technique : import javax. import java. Therefore you have to make a container object for the window w1. by overriding the paintComponent() method. class X extends JPanel{ public void paintComponent(Graphics g) { super.50.paintComponent(g). setSize(300.EXIT_ON_CLOSE). c1.add(a1). w1.setBackground(Color. setDefaultCloseOperation(JFrame. Container c1=w1. } } .green). c1.getContentPane(). X a1=new X().300). w1. w1.565 } } public class window1 { public static void main(String a[]) { JFrame w1 = new JFrame(" WELCOME").setVisible(true). add(a1).*. Invoke the paintComponent() of JPanel class by the statement super. Add the object of class X to the container by the statement c1.paintComponent(). . This methods takes the string to be displayed along with the co ordinate position.566 c Steps y y y y y y y extend the JPanel class. Inside main() create the object of the class . public class window1 extends JFrame { JLabel l1. import java. Second technique : import javax. Create the Container object by the getContentPane().swing.awt. that has extended the JPanel class.*. Invoke the method drawstring() inside the overridden body of paintComponent(). override the paintComponent(). getContentPane().300). setDefaultCloseOperation(JFrame. c1. Container c1=w1. w1. Constructor of JLabel is going to take the string to be displayed as it͛s argument. c1. y Create an object of JLabel.green).setBackground(Color. y Add it to the container object.l1). w1.567 window1() { l1 = new JLabel("hello world"). } } steps y Extend the class JFrame .add(w1.EXIT_ON_CLOSE). . } public static void main(String a[]) { window1 w1 = new window1().setSize(300.setVisible(true). w1. Let us have another example for TextArea in case of Swing. } } public static void main(String args[]) .*.setFont(new Font("Arial". import javax. } class myadapter extends WindowAdapter { public void windowCloseting(WindowEvent e) { System. public class TextAreaDemo extends JFrame { JTextArea jtx.exit(0).swing. jtx. import javax.14)).text.event.PLAIN. jtx=new JTextArea( ).swing.Font.568 import java. setTitle("Text area Example").setLayout(new BorderLayout()) . contentpane.*.*. public TextAreaDemo() { JPanel contentpane=(JPanel)getContentPane( ).*.jtx).add("Center".awt. myadapter myapp=new myadapter(). contentpane. import java.awt. addWindowListener(myapp). } } Output JComponent class This class belongs to the javax. donot embed that object to the frame. Component class of awt package is it͛s parent class . Rather create an window pane and embed the visual component to it. tx. tx. along with the inherited method this class has also defined it͛s own methods whenever you are creating any visual components or visual objects .swing package .setVisible(true). .setSize(150.150). hence the methods of the Component class is inherited to the JComponent class.569 { TextAreaDemo tx=new TextAreaDemo( ) . setForeground() this method is similar to the setBackground() method.red). This method takes the object of Font class as its argument. setBackground(): this method is used to add the back ground color to a GUI. Creation of push button using JButton class .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. for example setBackground(Color. This method takes static color element from Color class. The layout manager sets the visual component at the desired places in the GUI. setFont(Font font_obj): this method used to set different on a GUI application. This is done by the invocation of setLayout() method through the object of Container class. green).b1). public class window1 extends JFrame { JButton b1. w1. w1.*.*.setSize(300.swing. } } Output .setBackground(Color.571 import javax.EXIT_ON_CLOSE).setVisible(true).300). w1.getContentPane(). import java.awt. c1. } public static void main(String a[]) { window1 w1 = new window1().add(w1. window1() { b1 = new JButton("hello world"). setDefaultCloseOperation(JFrame. Container c1=w1. c1. instead of creating a object of JLabel you have to create the object of JButton and the rest are similar.*.awt. Let us have another programming example.*.event.awt. public class PanelDemo extends JFrame { public PanelDemo( ) { setTitle("Box 1").572 . import java. import java. 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.*.swing.util. Creation of push button is similar to that of adding text to a GUI discussed in second technique . . import javax.*. JPanel contentpane =(JPanel)getContentPane( ). import java. add(cancel). pd.setVisible(true). } } Output:- .setSize(400. contentpane. } private class myadapter extends WindowAdapter { public void windowCloseing(WindowEvent e) { System. JButton ok=new JButton("ok"). } } public static void main(String args[]) { PanelDemo pd=new PanelDemo().400). JButton cancel=new JButton("CANCEL").573 contentpane. myadapter myapp=new myadapter(). pd.setLayout(new GridLayout()). contentpane.exit(0). addWindowListener(myapp).add(ok). JCheckBox a=new JCheckBox(String l_name. Visual objects includes check box. . text fields. the constructor of JCheckBox is over loaded. radio button. it neither has a level name nor any image is attached to it. the check box created upon execution of this statement is said as blank CheckBox. Other forms of the existing constructors are: JCheckBox a=new JCheckBox(String level_name). The next argument is of boolean data type. the argument taken by the constructor is a string holding the level name for the check box. Check box: First create the object of JCheckBox by the statement JCheckBox=new JCheckBox(). you are already familiar with the tskof first argument. bollean status). If you send boolean true value.574 Embedding the Components Components means the visual objects. buttons etc. then the checkbox is appread as auto selected. // creation of two check box cbox1=new JCheckBox("java").awt.event. import java. To determine whether the check box is selected or not.*. After creation of check box. cbox3=new JCheckBox(".NET"). window1() { //Creation of Content pane Container c1=getContentPane().575 JCheckBox a=new JCheckBox(String l_name.setLayout(new FlowLayout()). public class window1 extends JFrame implements ActionListener { JCheckBox cbox1. cbox2=new JCheckBox("C++"). //creation of text area tarea=new JTextArea(10.cbox3. String s1. Lets have a program: import javax. import java.*.*.cbox2. do the modeling of check box by calling the getModel() method. . JTextArea tarea. you have to use the isSelcted() method.getModel(). This is done by the execution of Model mm=a. this constructor attach the level name along with a image to the check box. This is done by the execution of the statement boolean x=m.20).isSelected().awt. //Set flow lay out c1.swing. Image im). add(cbox3).add(cbox2). if(cbox3. setDefaultCloseOperation(JFrame.setVisible(true).addActionListener(this).add(cbox1).add(tarea). c1.isSelected())s1+="C++".NET". cbox2.isSelected())s1+="java".576 // add these visual objects c1. cbox3.isSelected())s1+=". c1.setSize(500.addActionListener(this).getModel(). tarea. } public static void main(String a[]) { window1 w1=new window1().getModel().500). //embed the listeners cbox1. } .setText(s1).addActionListener(this). c1. w1. s1="". } public void actionPerformed(ActionEvent ae){ if(cbox1. w1. if(cbox2.EXIT_ON_CLOSE).getModel(). *. import java.*.awt.awt.event.*.577 } Output: Let us have another example for the checkbox. .swing. import java. import javax. cb. cb=new JCheckbox("Toggle").SELECTED) setTitle(³checkbox selected ´). myadapter myapp=new myadapter(). addWindowListener(myapp). contentpane.add(cb). } class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System . exit (0).setLayout(new GridLayout(2. contentpane.getStateChange( )==ItemEvent.2).addItemListener(this). public CheckboxDemo() { setTitle("check box example"). . JPanel contentpane=(JPanel)getContentPane(). } } public void itemStateChanged(ItemEvent e) { if(e.578 public class CheckboxDemo extends JFrame implements ItemListener { JCheckbox cb. setSize(250. } } Output Radio button: .579 else setTitle(³Checkbox unselected´) . } public static void main(String args[]) { CheckboxDemo c=new CheckboxDemo() .250).setVisible(true) . c. c. //creation of text area tarea=new JTextArea(10. 4.event.awt.awt. the constructor of JRadioButton class is overloaded.cbox2. import java.*.*. cbox2=new JRadioButton("C++"). // add these visual objects .20). import java. 2. JTextArea tarea. ImageIcon i) this constructor takes another extra parameter as image icon to the radio button. window1() { //Creation of Content pane Container c1=getContentPane().580 Radio buttons are created by instanciating the object of JRadioButton class. s1 serves as the level name for the argument. String s1.swing. JRadioButton(String s1. //Set flow lay out c1. public class window1 extends JFrame implements ActionListener { JRadioButton cbox1. It͛s various constructors are 1. JRadioButton() : this is the default constructor for JRadioButton.*.setLayout(new FlowLayout()). 3. // creation of two radio button cbox1=new JRadioButton("java"). JRadioButton(String s1. JRadioButton(String s1) this constructorn takes String s1 as its argument. boolean b) the boolean value b suggests that by default the button is selected or not See the example below import javax. cbox2. c1. tarea. w1.isSelected())s1+="java".add(cbox1). } public static void main(String a[]) { window1 w1=new window1().addActionListener(this).add(tarea).add(cbox1). s1="".setText(s1). b.500).add(cbox2).addActionListener(this).setSize(500.EXIT_ON_CLOSE). //embed the listeners cbox1.getModel(). .getModel(). c1.add(cbox2).isSelected())s1+="C++".581 ButtonGroup b=new ButtonGroup(). //button group is created & two button behaves as a single group from which only one can be selected c1. b. } public void actionPerformed(ActionEvent ae){ if(cbox1. if(cbox2. setDefaultCloseOperation(JFrame. } } Output: If you select the c++ that is going to be displayed on the text area. Let us have another example: .582 w1.setVisible(true). rb1=new JRadioButton("Enabled").*. contentpane.add(rb2).awt. } .*.add(rb1). myadapter myapp=new myadapter().setActionCommand("One Activated"). rb2=new JRadioButton("Disabled").event. contentpane. public RadioButtonDemo() { setTitle("Radio Buttons Example"). public class RadioButtonDemo extends JFrame implements ActionListener { JRadioButton rb1.add(rb1).setActionCommand("Two Activated"). rb1. ButtonGroup grp=new ButtonGroup().583 import java.awt. import javax.setSelected(true). grp. import java.add(rb2). addWindowListener(myapp).addActionListener(this). rb1. rb2.swing.*. rb2.setLayout(new FlowLayout()). JPanel contentpane=(JPanel)getContentPane(). contentpane.addActionListener(this).rb2. rb1. grp. getSource()==rb1) { setTitle("First radio button enabled.setEnabled(false). . rb2.584 class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System. } } public static void main(String args[]) { RadioButtonDemo rb=new RadioButtonDemo().setSize(300.")."). } } public void actionPerformed(ActionEvent e) { if(e. rb. rb1.300).getSource()==rb2) { setTitle("Second radio button enabked. } else if(e.setEnabled(false). rb2. rb1.setEnabled(true).setEnabled(true).exit(0). The visual appearance of a GUI along with it͛.s visual objects is called LOOK components .585 rb. } } Output: Navigation through LOOK and FEEL Swing facilitates plaf. swing facilitates 3 types of LOOK and FEEL . 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 . 1 :Mmetal LOOK and FEEL 2: Motif LOOK and FEEL 3: Window LOOK and FEEL .setVisible(true). it means plugable look and feel. sun.getContentPane().awt.windowsLookAndFeel͟ Then you have to invoke the updateComponentTreeUI() to incorporate the change.*.MotifLookAndFeel͟ As a argument to setLookAndFeel(). public class window1 extends JFrame implements ItemListener { JButton button.swing. import javax. 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.event.motif.swing.swing.awt. import java.plaf. For windows Look and Feel the string is ͞com. the default look and feel choosed whenever we design a swing application is metal. Now let͛s have a example import javax.plaf.java.586 Since everything in java are class and objects therefore the above mentioned LOOK and FEELs are clases of javax.rb3.rb2.swing.*.java.*.*. JCheckBox cBox.plaf package . . window1(){ //create the content pane c=this. JTextField tF. JRadioButton rb1. import java. ButtonGroup bGroup.plaf.windows.sun.swing. Container c. 100. 80. 100. //Design a button group & add all the radio button to that group bGroup=new ButtonGroup().add(rb1). 250. rb1=new JRadioButton(). 100.50. c. 100.setBounds(150.587 //set the appropiate lay out manager c. bGroup. 30). cBox=new JCheckBox("check box"). rb2. 1000. 250.add(rb3). bGroup.setBounds(100. .setBounds(50. //embed visual objects button=new JButton("BUTTON"). rb3.setBounds(100. 1000. 150. 30).add(tF).setBounds(250. rb1.40). 50). 50). rb3= new JRadioButton(). rb2=new JRadioButton(). 250.setLayout(null). bGroup. tF=new JTextField(). 30). // locate each visual component on the GUI button.setBounds(100.add(rb2).add(button). // embed these visual objects to the content pane c. tF. cBox. rb1.add(rb2).setLookAndFeel("com.updateComponentTreeUI(c). c.metal.Windows LookAndFeel").sun.add(cBox).getModel(). // embed the listener rb1.swing.motif. rb1.plaf.setLookAndFeel("com. }catch(Exception e){} } public static void amin(String[] args) .addItemListener(this).swing.isSelected()) UIManager.EXIT_ON_CLOSE).plaf. SwingUtilities.getModel().isSelected()) UIManager.add(rb1).addItemListener(this).isSelected()) UIManager. this. if(rb3.MotifLook AndFeel"). } public void itemStateChanged(ItemEvent ie) { try{ if(rb1.getModel().plaf.java. if(rb2.MetalLookAndFeel ").setLookAndFeel("javax.java.sun.addItemListener(this).windows. c. c.add(rb3).588 c.setDefaultCloseOperation(JFrame.swing. 589 { window1 w1=new window1(). getRowCount() : this method is invoked by the table object. Each table consists of rows and column. it¶s return type is integer.500). w1.setTitle("My Window"). 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. Methods associated with JTable class 1.setVisible(true). w1. 2. } } Execute the codes to go through various available look & feel component. w1. It returns the number of rows present in that table. getColumnCount() : similar to the getRowCount() it returns the number of columns present in the table. .setSize(500. JTabbedPane class When you instanciate the JTabbedPane class. other versions of this method takes strings and image as argument for the name of the tabs and icons. If no column is selected then this method is going to return -1.LEFT . the visual object of this class is encapsulated with tabs. This method is overloaded in this class. These fields are used to indicated by the fields. getSelectedColumns() : this method returns an array of integers . getSelectedRows() : this method returns an array of integers . JTaabbedPane.BOTTOM.RIGHT. 7. getColumnName(int i) : this method takes the index number of the column number as it¶s argument and returns the name of the column in the form of string. .590 3.TOP.JTabbedPane. 6. 4.JTabbedPane. getSelectedColumn() : this method is invoked by the JTable object. setValueAt(Object data . 8. this array contains the index number of all the selected rows. getTableHeight() : this method returns the length of the table in terms of pixel. int row_index . this array contains the index number of all the selected columns. GUI developed by this class is called JTabbed frame. 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 returns the index number of the column which is selected on the GUI. 5. it¶s returns type is integer. This class contains some predefined fields such as JTabbedPane. int column_index) : this is used to put the data in the specified position of the table. 5 getTabCount() : this method is invoked by the object of the JTabbedPane class to count the number of tabs present in the tabbed pane . Programming example: import javax. import java.*. public class TabbedDemo extends JFrame { . import java.*. 6 getSelectedIndex( ) : this method returns the index number of the selected tabs from the JTabbedPane.*.swing.event.Component c) This method is used to embed a visual object or a component at the position specified by the index i. 7 getComponentAt( int i) : This method returns the visual object or component associated with the index i. 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. 8 setComponentAt(int index.591 2 removeTabAt( int i) : this method is invoked through the object of the JTabbedPane class.awt.awt. the argument I indicates the index of the tab to be removed from the frame . public TabbedDemo() { getContentPane().setSelectedIndex(0) .add(fpane.addTab("Second".exit(0). } private class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System. fpane.addTab("Third".addTab("First".592 JTabbedPane fpane=new JTabbedPane().setVisible (true) . . } } void makePane(String thestring) { TabbedDemo newtab=new TabbedDemo(). fpane. fpane. addWindowListener(myapp) . getContentPane().First) . JPanel First=new JPanel().CENTER).Second) . JPanel Third=new JPanel() .setLayout(new BorderLayout()).Third) . newtab. myadapter myapp=new myadapter() . fpane.BorderLayout. JPanel Second=new JPanel(). 593 newtab. } } Output:- JSplitPane class .setVisible(true).400) . td.setSize (400.200).setSize(250. td. } public static void main(String args[]) { TabbedDemo td=new TabbedDemo(). 594 This class is used to divide the GUI or the window in exactly two parts but not more than that. is used to get the 3 getTopComponent() : this method is used to deal with the top or left component. getButtomComponent() : this method is used to the buttom or right component . Methods 1 setDividerLocation( int pix) : this method sets the divider location between two components. 6 . Splitting is done in two ways y horizontal splitting process : in this process it splits the window into two parts horizontally. deal with 4 5 remove() : this method is used to remove the component from the split pane. y Vertical splitting process : in this process it splits the window into two parts vertically. 2 getDividerLocation( ) : this method divider location. remove(int i) removes the component specified by the index i. public class window1 extends JFrame implements ActionListener { String st1="This is my area to write java code". JButton button.*.getContentPane().plaf.awt. JTextArea tA.*. import java. setRightCompnent():deploy frame. window1(){ Container c. . setLeftComponent():deploy frame.*. the component at left of the 8 9 10 the component at right of the import javax. //set the appropiate lay out manager c.setLayout(new BorderLayout()). import javax. import java.*. JSplitPane jsp.swing.event.awt.595 7 setTopComponent(Component object) : deploy the component at top of the frame. setBottomComponent(): deploy the component at bottom of the frame.swing. //create the content pane c=this. w1. tA=new JTextArea("this is the text area").500). jsp=new JSplitPane(JSplitPane.setSize(500. w1.addActionListener(this). jsp.setTitle("My Window").EXIT_ON_CLOSE). tA).HORIZONTAL_SPLIT. button.setDefaultCloseOperation(JFrame. c.jsp). this.setDividerLocation(300). } public void actionPerformed(ActionEvent ie) { tA. } public static void amin(String[] args) { window1 w1=new window1().setText(st1).596 //embed visual objects button=new JButton("BUTTON").setVisible(true). } } . button. w1.add("CENTER". 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. To create a root node the JTree() constructor is invoked. getNewLeadSelectionPath() Each nodes present in the tree contains data or element. y y JComboBox Class As the name suggests this class is used to create the combo box component for the GUI interface. getLastPathcomponent(). this method is used to return the path that describes the position of the element in the tree. 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. In the next stage to spawn child the constructor of DefaultMutableTreeNode() is invoked. getPathCount() To know the number of paths available to the particular node. Methods of JTree class. When you select an item. This method returns a TreePath object. . then two stage approaches is followed. The argument passed to JTree class constructor can either be the entity of hash table containing keys & values or element of vector. In first stage the root is developed & in second stage Childs are spawned from the root node. You can either create an empty combo box by JComboBox comb=new JComboBox(). y y add(Object node): this method is invoked by the root node in order to add a node to the root node. This method returns the item or element that is selected by the user. y y y y y JList class This class is used to create the list of items to be displayed on the GUI. getselectedIndex() this method is used to extract the element specified by the index from the combo box. invoked through new operator is used to JList jl=new JList(Object []arr). JList() constructor when create an empty list. You can also send the object of vector to supplay the list items. The constructor for creation of JList object is JList jl=new JList(). but first of all you have to select the item to be extracted.598 Or create an combo box having list of items by JCombobox comb=new JComboBox(Object []arr). Methods of Combo Box class y y addItem(): This method is invoked by the combo box object to add item to the combo box. removeItem(): This method is used to remove the selected item from the combo box. this constructor is used to create a list containg the array of elements suppilied by the array arr. From this list you are able to select more than item. getSelectedItem(): this method is used extract an item from the combo box. getItemCount(): This method is used to count the nuber of elements present in the combo box. getItem(int i) This method is used to extract the element specified by the index number I from the combo box. removeAll(): This method is used to remove all the elements present in the combo box. . y getSelectedItem():This method returns the selected item from the list. here the array contains list of items to be displayed in the combo box. setBounds(100. String mesg=""."goa"}."karnataka".setLayout(null). import javax.*. getSelectedValues(): this method returns the array of selected items.*. getSelectedIndices(): This method is used to return array of indices. class list extends JFrame implements ListSelectionListener { JList j1. JLabel j2. j1. Object ary[].swing. y y y import java.add(j1). list() { Container c1 = getContentPane()."mharastra".event.swing. c1. String s1[]={"orissa".599 getselectedIndex(): this method is used to retun the index of the selected item.100.100). .*."kerela". c1. import javax. j1 = new JList(s1).awt.50. " .400.600 j2 = new JLabel(). tb. setDefaultCloseOperation(JFrame.setVisible(true).getSelectedValues().setText("selected : "+mesg).EXIT_ON_CLOSE). mesg="". } public static void main(String a[]) { list tb = new list(). tb.setBounds(50. c1. j1.setSize(600. for(int i=0. } public void valueChanged(ListSelectionEvent ae1) { ary = j1. .200.40).i++) { mesg += " .addListSelectionListener( this). mesg += (String)ary[i].400).add(j2). tb.i<ary. j2.length. } j2.setTitle("MY LIST"). . Steps to create a menu object and add it to the GUI.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. 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 it¶s normal state. Here c1 is the Container class object y Create a JMenu object through new operator. y Attach the menu bar object to the container of GUI.602 y Create a menu bar by JMenuBar j1 = new JMenuBar(). state as long as you have pressed .add(j1).the what similar to the push button.add(jm). y Add the JMenu object to the menu bar. J1. by invoking the JMenu constructor JMenu jm = new JMenu(³hello´). C1. To create a toggle button you have to invoke the constructor and supply the label name.gif"). c1.603 the left mouse key and when you release the left mouse key the button comes to it¶ normal state. j1. import javax. TogleButon() { Container c1 = getContentPane().awt.add(j1). ImageIcon image1. j1 = new JToggleButton("START / STOP". image1). another overloaded format of the constructor of this class takes the image icon along with the label name.swing.addActionListener(this).*. image1 = new ImageIcon("start.event.setLayout(new FlowLayout()).*. import java. } . c1. import java.awt. class TogleButon extends JFrame implements ActionListener { JToggleButton j1.*. ae1) if( j1. 800).setVisible(true). } } When you 1st clicked see the out put . tb.setIcon(image2).604 public void actionPerformed(ActionEvent { ImageIcon image2 = new ImageIcon("stop.setIcon(image1). } public static void main(String a[]) { TogleButon tb = new TogleButon(). else j1.setDefaultCloseOperation( JFrame.gif").EXIT_ON_CLOSE).setSize(800 .isSelected()) j1. tb. tb. .605 When you clicked for the 2nd time see the output. An interesting aspect is that through JFC classes java provides vertical progress bars . getMaximum() : this method is used to get the optimum value of the progress bar. setValue() : progress bar.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 . while installing the software . how many percentage remaining . getMinimum() : this method is used to get the least value of the progress bar. 2 . 5 . You have seen the scroll bar when you copy a file . ProgressBar object is created by calling the constructor of the JProgressBar class. JProgressBar( int X ) X indicates the orientation of the progress bar Methods 1 . 2. 3 . getValue() : this method is used to have the current value of the progress bar. how long it will take to complete the entire execution of the process. the various overloaded constructors are 1. JProgressBar(). etc. getOrientation() : this method is used to get the orientation of the progress bar. this method is used to set the value of the . 4 . 607 6 . message[1]="This may take some time . import java. setStringPainted() : this method percentage of the progress of the task bar.getContentPane().*.min. final Runnable runnable=new Runnable( ) { public void run ( ) . int min = 0.swing. message[0]="performing Operation. public class Progress extends Object { public static void main (String args[ ]) { JFrame frame =new JFrame("ProgressMonitor Example"). setOrientation() : this method is used to set the orientation of the progress bar.BorderLayout. final ProgressMonitor monitor=new ProgressMonitor(frame. message. int max = 100.event.".awt. import javax. 7.CENTER).*..*. is used to display the import java. frame.add(button.."."Iteration".max ).awt. JButton button=new JButton("Start"). String[] message=new String[2]. }catch(InterruptedException dontcare ) { } } } //monitor.setProgress( 100 ). for(int i=1.sleep( sleepTime ). } Thread. button. thread.isCanceled( )) { monitor.start( ).close( ). break.setProgress( i ).i++) { try{ monitor. . monitor.608 { int sleepTime = 500. if(monitor.addActionListener( new ActionListener ( ) { public void actionPerformed(ActionEvent event) { Thread thread = new Thread(runnable).setNote( "Iteration" + i). }.i<100. } } Output JColorChooser class This class is used to select different colors available in the Color menu bar.pack( ). JColorChooser(javax.colorchooser. The constructors of this class are 1.setVisible( true ). frame.swing. JColorChooser(java. frame. //show the frame.Color) 3.awt. JColorChooser() 2.ColorSelectionModel) .609 } } ). These are 1.String SELECTION_MODEL_PROPERTY 2. import java. } } .*.setVisible(true).*.String CHOOSER_PANELS_PROPERTY Example-13 import javax. import java. JPanel content=(JPanel)getContentPane( ) ."Center"). public class ColorChooserDemo extends JFrame { public ColorChooserDemo( ) { setTitle("JColorChooser Example"). Public static final java.610 This class provides three String type constants for selecting the model for the color.lang.lang.lang. c.event. Public static final java.String PREVIEW_PAEL_PROPERTY 3.swing.awt. import java. JColorChooser jcc = new JColorChooser( ).add(jcc. content.*.awt.lang.*. Public static final java. } public static void main(String args[]) { JFrame jf = new JFrame("JColorChooser Example"): ColorChooserDemo c = new ColorChooserDemo(). 611 Output Dealing with the keyboard events . A state of a key can be determined by various methods available in the java. the os invokes the appropriate interrupt service routine through device driver. VK_0 to VK_9 holds the logical value of the key between 0 to 9.event package.event package. VK_F1 to VK_F12 holds the logical value of the key between F1 to F12. for detailed description the reader¶s can go through the chapter-26.awt. an interrupt is generated and propagates to the operating system.Upon receiving the interrupt signal. The value attribute represents the key that has been pressed. Status of the key indicates whether a key is pressed or released and the represents which key is pressed. When you press a key. Each event is closely entangled with a listener object. All these listener interfaces and event handling classes belongs to the java. VK_HOME holds the logical value of the key HOME VK_END holds the logical value of the key END . In java the generated interrupt is termed as event. The JVM hides this complex techniques from the programmer by providing listener interfaces and event handling methods. when you press a key.awt. an event is generated according to the status of the key and the value of the key. VK_A to VK_Z holds the logical value of the key between A to Z.612 Normally an user interacts with the system by entering data through the keyboard. 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 . JTextArea txt. window1() { cnt=getContentPane().swing.add(txt).*. cnt. txt=new JTextArea(³ please press a key:´).awt. import javax. class window1 extends JFrame implements KeyListener { Container cnt.BOLD. .*.Font.20)).setFont(new Font(³Arial´.awt.614 We can also get the logical value behind the keycodes such as VK_F1 for F1. txt. import java.event. String st1=´´. in the form of a String by the following predefined method: Static String getKeyText(int keycode) Example:- import java.*. VK_SHIFT for SHIFT and etc. . if(keycode1==KeyEvent.VK_END) st1+=´the END key´. if(keycode1==KeyEvent. if(keycode1==KeyEvent.setVisible(true). if(keycode1==KeyEvent.615 txt. kkk.addKeyListener(this).VK_PAGE_DOWN) st1+=´page-down´.VK_PAGE_UP) st1+=´page-up´. } public void keyPressed(KeyEvent kee) { int keycode1=getKeyCode().VK_F1) st1+=´The F1 key´. if(keycode1==KeyEvent. if(keycode1==KeyEvent.VK_HOME) st1+=´the HOME key´.VK_ALT) st1+=´the Alter key´.VK_F3) st1+=´The F3 key´.VK_F2) st1+=´The F2 key´. if(keycode1==KeyEvent. if(keycode1==KeyEvent. } public void keyReleased(KeyEvent kee) {} public void keyTyped(KeyEvent kee) {} public static void main(String arg[]) { KeyBoardEvents kkk=new KeyBoardEvents(). EXIT_ON_CLOSE). MessagePane MessagePane allows the programmer to develop the GUI. Various methods of the MessageBox Method public static void showMessageDialog(Component c1. } } Just run code & see the ouput.616 kkk. a MessageBox is poped-up instantly. . Object msg1) Description C1 determines the visual object or the frame to be poped-up and msg1 represents the message to be displayed.setDefaultCloseOperation(JFrame. such that when a particular event is fired with respect to a visual object. title1 represents the title of the box and message_type1 is used to display the exact type of the message like ERROR_MESAGE. QUESTION_MESSAGE. . Object msg1. WARNING_MESSAGE. Here. title1 represents the title of the box and message_type1 is used to display the exact type of the message like ERROR_MESAGE. WARNING_MESSAGE. QUESTION_MESSAGE. int messageType1) C1 determines the visual object or the frame to be poped-up and msg1 represents the message to be displayed. Object msg1. INFFORMATION_MESSAGE. INFFORMATION_MESSAGE. icn is used to display the picture as an icon for tht particular message box. or PLAIN_MESSAGE. or PLAIN_MESSAGE public static void showMessageDialog(Component c1. Icon icn) 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. String title1. String title1. int message_type1. b1.*. } public Dimension getPerferredSize( ) { return new Dimension(100. add(b1). } public void actionPerformed(ActionEvent e) { JOptionPane.awt.event.lang."Hai. } public static void main(String s[]) .60).*."Informational Message pane". public class MessagePaneDemo extends JPanel implements ActionListener { public MessagePaneDemo( ) { JButton b1 = new JButton("Click here").showMessageDialog(this. import java.INFORMATION_MESSAGE).618 import java.*.addActionListener(this). import java.See The Message".JOptionPane.awt. getWindow( ). frame.setSize(panel. win.exit (0).619 { JFrame frame = new JFrame("Information"). } } Output .setBackground(Color. frame.setVisible(false).setVisible(true). frame. frame. System.getContentPane().setForeground(Color. } } class WindowCloser extends WindowAdapter { public void WindowClosing(WindowEvent e) { Window win=e.add(panel). MessagePaneDemo panel=new MessagePaneDemo( ). frame. frame.addWindowListener(new WindowCloser( ) ).black).getPreferredSize()).lightGray). 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 .620 JOptionPane A JOptionPane class is used to design option pane dialog box which is encapsulated with four major visual objects. . You have to to remember these fields to work in different option panes.621 Input Area Options Area Option Attributes JOptionPane class contains various predefined fields which are used to configure the pane prior it is displayed. 622 . . Each default value is defines as a class variable for JOptionPane.623 The option type for an OptionPane is used to determine the buttons to be displayed in the option button¶s area. Example-11 import javax. We can also create our own button combinations if we use a generic option pane.*.swing. There are four defaults setting for this value. addActionListener (this).*.*. add (b1).out.624 import java. b1.awt.out.*.println(³Cancel Button was pressed´). result =JOptionPane.CANCEL_OPTION: System.out. switch(result) { case JOptionPane. break. import java.YES_OPTION: System.awt. . break.1ang. public class Confirm extends JPanel implements ActionListener { public Confirm( ) { JButton b1 =new JButton("click here").println(³No Button was pressed´). case JOptionPane. } public void actionPerformed (ActionEvent e) { int result.println(³Yes Button was pressed´). break. case JOptionPane.event. import java.NO_OPTION: System.showConfirmDialog(this.´Continue´). black). frame. } } class WindowCloser extends WindowAdapter { public void windowCloseing(WindowEvent { e) . frame.addWindowListener (new WindowCloser ( )). frame.getContentPane ( ). frame.getPreferredSize( ) ). } public static void main(String s [ ]) { JFrame frame =new JFrame (³Confirm Dialog´).625 case JOptionPane.setVisible (true).setForeground(Color. frame.lightGrey). } } public Dimension getPreferredSize( ) { return new Dimension (100.println(³Dialog closed´).setBackground(Color. frame.add(panel. Confirm panel =new Confirm ( ). 60). break.setSize(panel.´Center´).out.CLOSED_OPTION: System. public class InputDialogDemo extends JPanel implements ActionListener { .*. import javax.*.exit( 0).626 Window win =e. System.getWindow( ).*. win.awt.event.swing. import java.*.awt. import java. import java.lang. } } Output: Let us have another programming example which shows another task of the JOptionPane.setVisible(false). lenght()==0)) { System.out. output=JOptionPane.println("Entered data is :" + output). add(b1).out.println("zero data: "). } public void actionPerformed(ActionEvent e) { String output.627 public InputDialogDemo( ) { JButton b1=new JButton("Click here").showInputDialog(this. if((output==null)||(output. } } public Dimension getPreferredSize( ) { return new Dimension(100. } public static void main(String s[ ] ) ."Enter your favorite place"). System. } else { System. b1.out.addActionListener(this).println("Enter data in the text field "). 60). frame.exit(0)."Center"). frame.setSize(panel.black).gray).getContentPane( ). } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.setVisible(true). frame. InputDialogDemo panel = new InputDialogDemo( ).addWindowListener(new WindowCloser( ) ). frame.setBackground(Color.getWindow( ) .628 { JFrame frame = new JFrame("Confirm Dialog"). win.setVisible(false). } } Output . frame.add(panel.setForeground(Color.getPreferredSize( ) ). System. frame. 629 . Client access services from the Server. This is one of the main attractions of java. FTP (File Transfer Protocol ± enables transfer of files between computers). If the server provides application services then server is treated as Application Server. such as y Server y Client y Peer y Protocol y Physical Media y Physical Devices Servers provide services to the client. . The classes within this package encapsulate the socket model developed by Berkeley software Division.net package. Networking in java is possible through the use of java . Java networking is done using TCP/IP protocol. SMTP (Simple Mail Transfer Protocol ± provide e-mail facility). A network is a set of computers and peripherals. which are physically connected together. Examples of different types of protocol available in TCP/IP are. Networking enables sharing of resources and communication. 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). Network required some components. Java applets can be downloaded from a Web site. Protocols Communication between computers in a network or a different network requires certain set of rules called protocols. Peer is a computer that works as a server and also as a client.net Introduction to Networking A group of computer connected by cable to share the information is popularly known as network.630 Chapter-28 Java. HTTP (Hyper Text Transfer Protocol ± enables interaction with the Internet). Internet is a network of networks. NNTP (Network News Transfer Protocol ± acts as a bulletin board for sharing news). A server waits till one of its clients makes a request. 25 is assigned for e-mail. port takes the input from the input devices and loaded in the memory through the CPU. the computer is assigned with a permanent IP address. It is similar to every student of a batch having a unique id. Each protocol establishes specific set of rules to communicate.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. A sample IP address is given below. which requests for some service from another computer. By connecting directly to the Internet. It can accept multiple connections at a time to the same port number. An IP address is a 32-bit number which has four numbers separated by periods. 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. to transfer hypertext pages and images. In case connection is made using ISP. 80 for HTTP and so on. Whereas the port is the 16 bit number. y In the context of TCP or UDP. For example. is called a client. Specific ports are assigned to some protocols by TCP/IP. As a verb. The one that processes the request is called Server. port is a communicating channel between two application. web browsers and servers use the HTTP protocol. A few example are port number 21 is assigned for FTP. . which is used by the TCP or UDP to deliver the data to the appropriate application. Generally the port having three meaning. It is possible to connect to the Internet either directly or by using Internet Service Provider. y y Client/Server A computer. 23 is assigned for Telnet. Port number ranges from 0-65535. In the context of the hardware. data is transmitted to the appropriate application within the network or outside the network. it assigns a temporary IP address for each session. Whereas the registered ports are in between 1-1023. factory methods are used.0. They are found in the java . Domain Naming Service It is very difficult to remember the IP address to connect to the Internet. as there are no constructors available for this class.com implies com is the domain name reserved for US commercial sites. . InetAddress There are classes provided in java to enable networking. www. InetAddress is one such class. The Domain Naming Service (DNS) is used to overcome this problem. which is used to encapsulate the IP address and the DNS. DNS maps one particular IP address to a string of characters which is popularly known as domain name. For example.632 80.net package.yahoo. which is yahoo¶s server. yahoo is the name of the company and www is the name of the specific computer. 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.53 IP address . To create an instance of InetAddress class.0. i<is.println(is[i]).out. ia=InetAddress. } } } Output: . InetAddress is[]=InetAddress.*.getLocalHost(). public class InetDemo { public static void main(String args[])throws UnknownHostException { InetAddress ia=InetAddress. System. Program: import java.length.633 static InetAddress[] getAllByName(String name) Returns an array of InetAddresses that represent all of the addresses that a particular name resolves to.getAllByName("localhost").i++) { System.net. for(int i=0.println(ia).out. if they are unable to locate the host. ll the methods throw UnKnownHostException. System.println(ia).out.getByName("localhost"). and DatagramSocket is a mechanism used to send or receive DatagramPackets. int size) The above constructor takes a byte array and its size as its parameter. DatagramPacket is the class. DatagramPacket (byte data [].net package. A DatagramPacket object can be created as follows. int port) In addition to the byte array and its size. Constructors The constructor of the class is overloaded. DatagramPacket (byte data[ ].634 Datagram Datagram is a type of packet that represents an entire communication. int size. Methods public synchronized int getPort() public synchronized byte[] getData() Returns the port number. InetAddress ia. There is no necessity to have connection or disconnection stages when communication using datagrams. which enable communication-using datagrams. the above constructor takes the InetAddress and the port as its parameters. DatagramPacket DatagramPacket is a class present in java. This is less reliable than communication using TCP/IP. This class works as a dada container. Returns the data in byte format . There are two classes in java. which acts as the data container. This class is used to broken the data into small packets and send it over the net through the DatagramSocket class. The first constructors does not take any parameters and is created as given below: DatagramSocket s = new DatagramSocket( ) . DatagramSocket The class DatagramPacket does not provide methods to send or receive data. There are two constructors of DatagramSocket class. which must be handled. Listed below are its constructors and some of its methods. The next constructor is given as follows. 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 . The DatagramSocket class takes up this job. DatagramSocket s= new DatagramSocket (int port). Constructors The creation of a DatagramSocket object throws a SocketException.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. InetAddress ia=InetAddress.readLine(). System.*. public static void main(String args[])throws Exception { byte buffer[]=new byte[2300].serverport=10000.out.The send and receive methods of the DatagramSocket class throw an IOException which must be caught. if((s==null)||s.net.in)).636 public InetAddress getLocalAddress() Return the InetAddress of the local address.equalsIgnoreCase("end")) { .println("Enter Text"). BufferedReader br=new BufferedReader(new InputStreamReader(System. import java. ds=new DatagramSocket(serverport).*.io.getByName("localhost"). Write The Server side Application import java. public static int clientport=9999. while(true) { String s=br. public class DataServer { public static DatagramSocket ds. Note . import java.length.net.*.ia.637 break.clientport)). public static int clientport=9999.send(new DatagramPacket(buffer. ds.java Execute it:.javac DataServer. public static void main(String args[])throws Exception .getBytes(). public class DataClient1 { public static DatagramSocket ds.buffer. } } } y y y Write the server side application Compile it :. } buffer=s.io.java DataServer Write The Client Side Application import java.*.serverport=10000. } } } y y Compile Client side Application:.p.println("Client is waiting for server to send data").out.out. There are two kinds of sockets in java ± a server and a client. Sockets are used for data communication using this protocol.638 { byte buffer[]=new byte[2300].getLength()). . DatagramPacket p=new DatagramPacket(buffer. stream protocols.0.println(str). System.javac DataClient1. ds=new DatagramSocket(clientport).java Execute Client side application:.java DataClient TCP/IP TCP/IP sockets are the most reliable.net package.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.buffer. Java.receive(p). It is possible to send arbitrary amounts of data using TCP/IP. bi-directional.length). while(true) { ds. System.getData(). String str=new String(p. int port). The next constructor takes the InetAddress and port number as its parameters to create a Socket object. which must be caught. Socket s=new Socket(InetAddress ia . Creation of a Socket object throws an UnknowmHostException or an IOException. which must be caught and handled. Socket s = new Socket (String hostName. 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 ( ) . int port). On a Socket we write the data. From the Socket we read the data. The constructor throws an IOException or an UnknowmHostException. Constructors The first constructor takes the hostname and port as its parameters to create a Socket object.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. The normal socket object is used for further transfer of data. . Creation of this object throws an IOException.true). ServerSocket Class The ServerSocket object waits for the client to make a connection.getInputStream ())) How to write the data on Socket? PrintWriter out=new PrintWriter(socket.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. this class has accept ( ) method which is used to wait for a client to initiate communications. which must be caught and handled. An object of this class registers itself as having an interest in client connections. Constructors There are two types of constructors available.getOutputStream(). The first constructor accepts a port number as parameter to create a ServerSocket object on that port. Apart from using the methods listed above. *.net. int max) . public class FServer { public static void main(String args[])throws Exception { ServerSocket ss=null. try{ ss=new ServerSocket(9999).*. . try{ s1=ss.accept(). ServerSocket ss=new ServerSocket(int port. }catch(IOException ie) {} Socket s1=null.io. Write the Server Side Application import java. The queue length indicates the maximum number of client connections that the system can have before refusing further connections.641 ServerSocket ss=new ServerSocket(int port) . import java. The next constructor accepts a port and maximum queue length as parameters. } out. String line. File f=new File(s). out.exists()) { BufferedReader d=new BufferedReader(new FileReader(s)).write(line). System. ss.getOutputStream().close(). } } .flush().close(). } d.readLine(). while((line=d. BufferedReader stdin=new BufferedReader(new InputStreamReader(System. s1.out.println("Enter The File Name").in)). if(f. String s=stdin.642 }catch(Exception e) {} PrintWriter out=new PrintWriter(s1.close().readLine())!=null) { out.close().true). io.java Execute the Server side application by java FServer Write the client side Application import java.net. public class FClient { public static void main(String args[])throws Exception { Socket s=null. in=new BufferedReader(new InputStreamReader(s. String userinput=null. try{ s=new Socket(InetAddress.*. import java.9999).643 y y y Write the server side application through ServerSocket class Compile the server side application by javac FServer.*.getLocalHost(). }catch(Exception ue) { . BufferedReader in=null.getInputStream())). Both the programs terminate after the request is serviced. A check is made at the server end and if the file exists.out.readLine())!=null) { System. after which a message is displayed giving details about the local port number.close(). The server program requests for a file name. Once a client makes a connection. Communication between Server and Client application through multithreading .close(). The transfer of data between the client program and the server program takes using the socket object. s. This file may present in the current working directory or anywhere. the data is read by the socket object using the getInputStream () method. the accept method is called to accept the connection.java Execute the client side application java FClient The ServerSocket object waits for a client to make a connection at some port number 9999. } } y y Compile the client side application javac FClient.644 } while((userinput=in. } in. client address and the port number of the client.println(userinput). The client end displays the file contents. 20). Thread th.Runnable { Button b1.orange). TextArea ta. public AppServer() { Frame f=new Frame("Server Side Chatting").addActionListener(this).setLayout(new FlowLayout()). b1=new Button("Send").*. PrintWriter pw.*.net.awt. tf=new TextField(15). ta=new TextArea(12. ServerSocket ss.io.awt.645 Write the server side application import java. TextField tf.setBackground(Color.event. b1. f. public class AppServer extends Frame implements ActionListener. . import java. Socket s. import java. b1.*. BufferedReader br.*.pink).setBackground(Color. f. import java. f.300).getInputStream())). br=new BufferedReader(new InputStreamReader(s.setLocation(300.add(tf).accept().add(ta).20)).cyan). f. f.setSize(200.200).BOLD. f.addWindowListener(new W1()). s=ss. th.validate(). } private class W1 extends WindowAdapter { public void windowClosing(WindowEvent we) .Font. f.setVisible(true).true).setDaemon(true).add(b1). f.setBackground(Color. }catch(Exception e) { } th=new Thread(this). setFont(new Font("Arial".646 ta. try{ ss=new ServerSocket(12000). th.start(). f. f. pw=new PrintWriter(s.getOutputStream(). getText()).setText("") } public void run() { while(true) { try{ ta. }catch(Exception e) { } } } public static void main(String args[]) { AppServer a=new AppServer().exit(0).647 { System.append(br. } } public void actionPerformed(ActionEvent ae) { pw. tf.println(tf.readLine() +"\n"). . } } . import java.*.awt.awt.*. public class AppClient extends Frame implements ActionListener. import java.Runnable { Button b.io.java AppServer Write the client side application import java.java Execute Server side application:. .javac AppSerer.net.*.648 y y Compile Server side application:. import java.event.*. add(b). public AppClient() { Frame f=new Frame("Client Side Chatting").add(ta). ta. f.20).getLocalHost(). f.setBackground(Color. b. br=new BufferedReader(new InputStreamReader(s. TextArea ta.true). Socket s.12000). f. pw=new PrintWriter(s. tf=new TextField(15).setBackground(Color. f.setLayout(new FlowLayout()).addWindowListener(new W1()).cyan). f.649 TextField tf. Thread th. ta=new TextArea(12.addActionListener(this). }catch(Exception e) . f. PrintWriter pw. BufferedReader br. try{ s=new Socket(InetAddress.add(tf).getInputStream())). b=new Button("Send") .getOutputStream().orange). .println(tf.exit(0).setSize(200. f.Font.BOLD.getText()) tf.start().20)).setDaemon(true).setVisible(true).200). f. setFont(new Font("Arial". } } public void actionPerformed(ActionEvent ae) { pw.setText("") } public void run() { while(true) . f.300).650 { } th=new Thread(this). } private class W1 extends WindowAdapter { public void windowClosing(WindowEvent we) { System. .validate(). th. f. th.setLocation(100. }catch(Exception e) } } public static void main(String args[]) { AppClient a1=new AppClient().append(br.651 { try{ ta.javac AppClient. } } {} y y Compile the client side application:.java AppClient .java Execute the client side application:.readLine()+"\n") . www. The last component specifies the actual file path. NNTP. Given below is an example of an URL. port number and actual file path. IP address or the hostname. FTP or gopher. 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.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. SMTP.yahoo.com:80/root/htmlfiles/index.html http is the protocol. The third component.html is stored under root/html files directory. http://www. The IP address is delimited on the let by double slashes (//) and on the right by a slash (/) or a colon.com is the host name. Java provides URL class that provides an API to access information across the Internet. The protocols may be HTTP. Components of URL The URL has four components ± the protocol. . port. The most commonly used protocol of the web is the hyper text transfer protocol (HTTP). The Web is a collection of higher level protocols and file formats. is optional and is delimited on the left by a colon and on the right by a slash. 80 is the port number and the file index.yahoo. String hostname. URL u = new URL(String urlname). This is the most commonly used constructor to create the URL object. String urlspecifier).653 Constructors There are four constructors and creation of a URL object throws a MalformedURLException. String path). The next constructor takes the name of the protocol. The first constructor takes the urlname as parameter and creates an object. The last constructor accepts the URL object and a string. port number and the file path as parameters. URL u = new URL (URL urlobj. int port. String hostname. String path). host name. Methods int getPort( ) Returns specified pot number in URL / returns ± 1 if port is not explicitly set . The third constructor accepts three parameters as given below. URL u = new URL (String protocolname. URL u = new URL (String protocolname. out.out. public class U1 { public static void main(String args[])throws Exception { URL u=new URL("http://sify.getPort()).com:80/index.println("Protocal Used Is "+u.jsp"). System.*. Returns the protocol name String getProtocol() Program: import java.println("Host name is "+u.println("Port Number is "+u. } } .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.getHost()).println("File Name Is "+u.net.out.out. System. System.getFile()). System.getProtocol()). out.jsp").*. while((line=br. public class ReadUrl { public static void main(String args[])throws Exception { URL u=new URL("http://localhost:8085/ex1.println(line).readLine())!=null) { System.io. import java.openStream())). } } . BufferedReader br=new BufferedReader(new InputStreamReader(u.close().655 Output: Program: import java. String line. } br.net.*. net. import java. It is the super class of all classes that represents a communication link between the application and URL.656 URLConnection URLConnection is an abstract class present in java.net package. URLConnection is a general-purpose class.*.*.io. 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. which provides methods to know more about the remote resource. public class UrlConn { . 657 public static void main(String args[])throws Exception { URL u=new URL("http://localhost:8085/ex1. } } } .getInputStream())). BufferedReader br=new BufferedReader(new InputStreamReader(uc. while((line=br.openConnection().jsp").readLine())!=null) { System. URLConnection uc=u.out.print(line). String line. CLI requires neither host variables nor other embedded SQL concepts that would make it less flexible from a programmer¶s perspective.JDBC is an API whose prime task is to execute SQL statements. Call Level Interface is a library of function calls that supports SQL statements. however. JDBC API lets the programmer to invoke SQL commands from Java programming language methods. 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 contains a number of classes and interfaces for executing SQL statements. It is still possible. Java Database Connectivity (JDBC) is a standard developed by Sun Microsystem.658 CHAPTER 29 JDBC(Java Database Connectivity) Introduction to JDBC JDBC stands for Java Database Connectivity . to maintain and use specific functions of a database management system when accessing the database through a CLI. . It is possible to publish vital information from a remote database on a web page using a java applet. while ensuring the more difficult and uncommon tasks are at least made possible. low-level interfaces are not. JDBC was developed in 1996. While high level interfaces are user-friendly. JDBC API enables java applications to interact with different types of databases. automatically downloaded from the network and java is an elegant language to create database applications.659 The goal of creating JDBC is to create an interface that keeps simple tasks simple. JDBC API contains a number of pre defined methods where SQL statements are passed as a parameter in String format. Some of the advantages of using java with JDBC are y y y y y Supports a variety of Relational databases. . 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. robust. j Pointer is an integral part of ODBC whereas java never permits the programmer to use pointer. Java uses JDBC API which is a low-level API interface that is used to execute various SQL commands. 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. Java programs are secure. Hence the need for JDBC came into existence. JDBC Vs ODBC The most widely used interface to access relational database today is Microsoft¶s ODBC API. Java and JDBC The combination java with JDBC is very useful because it lets the programmer run his/her program on different platforms. 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. Java application and applets are connected with JDBC driver through the DriverManager. Two tier model In two tier model java applets and applications are directly connected with any type of database. Different types of Driver Managers JDBC API contains three components: y y y Application Driver Manager Driver. which is used for various purposes. JDBC driver is of four different types. JDBC Driver Models JDBC supports two tier and three tier models. The installed JDBC driver is JDBC compatible or not is checked through Driver component.660 j On all client machines ODBC drivers are manually installed whereas JDBC drivers are installed automatically in every client machines. In two tier model client directly communicate with database server through JDBC driver. Middle tier server performs various functions: j It extracts the SQL commands from the clients and send these commands to database server. Three tier model In three tier model client connect with database server through a middle tier server. The JDBC application through the predefined methods executes SQL Statements and retrieves the results from the database server. 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 . j Extracting the results from the database server and submit the result to the client. 5. C:\oraclexe\app\oracle\product\10. Set path=C:\Program Files\Java\jdk1. The Type-1 driver is used to bridge the gap between JDBC-ODBC Bridge and ODBC driver.0\bin. 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.0\server\BIN. 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.2.5. Set classpath=C:\Program Files\Java\jdk1.0\server\BIN. . C:\oraclexe\app\oracle\product\10.2.0\bin.661 The JDBC-ODBC Bridge plus ODBC driver This driver is popularly known as Type-1 driver. "tiger").println(e1. System. ResultSet rs=st.getConnection("jdbc:odbc:omm".out. int salary=rs.getString("ename"). } }catch(Exception e1) { System.executeQuery("select * from emp").getInt("sal").createStatement().sql.out."scott".662 Example-1(Type-1 Driver) import java. public class Type1 { public static void main(String ll[]) { try{ Class.println("Employee Name is: "+name+" and "+"Salary is :"+salary). } } } .forName("sun. while(rs.next()) { String name=rs.JdbcOdbcDriver").getMessage()).*.jdbc.odbc. Connection con= DriverManager. Statement st=con. %WL_HOME%\server\lib\webservices.jar.DataSource. import javax.%WL_HOM E%\server\lib\ojdbc14. This driver is used to convert JDBC calls to client API for any database. %POINTBASE_CLASSPATH%. 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.naming. %JAVA_HOME%\jre\lib\rt. In type-2 driver programmer has to install any middleware server like weblogic server. 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. Set CLASSPATH=%WEBLOGIC_CLASSPATH%. Example-2(Type-2 Driver) import java.util.Context. import javax. import javax.jar.Properties.InitialContext.jar.sql.663 Native-API partly-java driver This driver is popularly known as Type-2 driver.*.sql. import java.naming. public class Type2 { public static void main(String[] args) { . "webl ogic. DataSource source=(DataSource)ctx.INITIAL_CONTEXT_FACTORY. Connection con=source. } } catch (Exception e) { } } } JDBC-Net pure Java driver This driver is popularly known as Type-3 driver. The middleware server converts the net protocol to a DBMS protocol.getString("ename"). p. Statement st=con. System.PROVIDER_URL. ResultSet rs=st."t3://localhost:700 1").WLInitialContextFactory"). .put(Context.getInt("sal"). int salary=rs.next()) { String name=rs.getConnection(). Properties p=new Properties().println("Employee Name is: "+name+" and "+"Salary is :"+salary). p. String pool="pool1". Whatever protocols used in the middleware server is vendor dependent.executeQuery("select * from emp"). This Type-3 driver converts JDBC calls into DBMS independent net protocol. InitialContext ctx=new InitialContext(p).out.lookup(datasource).664 try{ String datasource="ds1".put(Context. while(rs. Through this driver the middle ware server connects with a variety of clients.createStatement().jndi. Connection con=source.WLInitialContextFactory").Context. Statement st=con. p. String pool="pool3". import java. ResultSet rs=st.sql.createStatement(). Properties p=new Properties().INITIAL_CONTEXT_FACTORY."t3://localhost:7001"). import javax. public class Type3 { public static void main(String[] args) { try{ String datasource="ds3".sql.PROVIDER_URL.naming.put(Context."weblogic. import javax.util.lookup(datasource).naming.executeQuery("select * from emp").*. import javax. p.next()) { String name=rs.DataSource.getConnection(). while(rs.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.getString("ename"). InitialContext ctx=new InitialContext(p). . DataSourcesource =(DataSource)ctx.Properties.jndi .put(Context.InitialContext. jar.println("Employee Name is: "+name+" and "+"Salary is :"+salary). Type-3 and Type-4 Driver are the most preferred ways to access data from databases Server. Type-4 driver converts JDBC calls to network protocols used by the DBMS directly.0\server\jdbc\lib\ojdbc14.0\bin.666 int salary=rs. C:\oraclexe\app\oracle\product\10.getInt("sal"). ARCHITECTURE JDBC Applicaion JDBC Type-4 Driver DBMS Interface server listener DBMS Set path=C:\Program Files\Java\jdk1. Through this driver client directly make requests to the database server.5.out. System.2. } }catch (Exception e) { } } } Native-protocol pure java drivers This driver is popularly known as Type-4 driver. This type driver supports two-tier architecture. . getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11".out.jdbc.registerDriver(new oracle.0\bin. } st. Statement st=cn. class Customer { public static void main(string args[]) throw SQLException { DriverManager. while(rs.close(). }catch(Exception ex) . ResultSet rs=st.0\server\jdbc\lib\ojdbc14.. System."sai".getString(1). try{ Connection cn=DriverManager.createStatement(). System.driver.println(s).OracleDriver()).close().5. cn.2.").667 Set classpath=C:\Program Files\Java\jdk1.sql."sai").jar.next()) { String s=rs.out. C:\oraclexe\app\oracle\product\10. Example-4(Type-4 Driver) import java.*.executeQuery("select * from emp1´).println("Connection to the database««. } } } In the url. thin is the JDBC driver.sql package.out. rashmi is the database name. An SQL BLOB is a built-in data type that stores a Binary Large Object in a database table.668 { System. This interface contains some predefined methods: j j j j Blob Blob is an interface present in java.sql package We have seen that the JDBC API defines a set of interfaces and classes are found in the java. 1521 is the port on which the connection is to be established and orc11 is the system ID. The methods of this interface are: j getBinaryStream() j getBytes() j length() getArray() getBaseType() getBaseTypeName() getResultSet() . ³sai´ is the user id and ³sai´ is password.sql Array This interface is used to map java array into SQL type ARRAY. Interfaces in java.println("The exception raised is : " + ex). 1521 is the port on which the connection to the database name.sql package. java. In SQL CLOB is a built-in data type that stores a Character Large Object in a database table.sql package.sql package.669 j position() CallableStatement CallableStatement is an interface present in java. The methods in this interface include the getXXX(where XXXstands for any datatype) methods and the following methods. 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() .sql package. Information such as database tables. A connection is session in a specific database engine. Escape syntax is used for procedures that return a parameter. 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. j registerOutParameter() j wasNull() Clob Clob is an interface is present in java.CallableStatements is used to call SQL stored procedures. This interface extends the PreparedStatement interface. A CallableStatements may return a ResultSets or multiple ResultSets. The Driver interface is used to create connection objects. This interface is a reference to an SQL structure type value in the database. table names. j j j j j j Ref acceptsURL() connect() getMajorVerson() getMinorVerson() getPropertyInfo() jdbcCompliant() Ref is an interface present in java. 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. first it must create an instance of the driver and then it registered in the DriverManager.670 prepareStatement() rollback() setAutoCommit() setReadOnly() j j j j DatabaseMetaData The DatabaseBaseMetaData interface provides information regarding the database itself. The following are the methods present in the Driver interface.sql package. The method present in this interface is . such as version information. Many of the method of this interface return lists of information in the form of ResultSet objects. and supported functions. When a Driver class is loaded. The reference of the interface is saved in the persistent storage mechanism. 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. . This interface is used to map the SQL user defined data types.671 getBaseTypeName() y ResultSet The ResultSet interface provides methods for the retrieval of data returned by a SQL statement execution. 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. getXXX and updateXXX methods are present in this interface. namely.sql package. The most often used methods. A ResultSet maintains a cursor pointing to its current row of data. 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() . The writeXXX methods (where XXX represents any data type) of this interface are used to write data on SQLData object.672 j getSQLTypeName() j readSQL() j writeSQL() SQLInput SQLInput 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. A Statement can open only one ResultSet at a time.sql package. The programmer does not invoke this interface. Rather. Another method in this interface is: j wasNull() SQLOutput SQLOutput is an interface present in java. This interface is also used by the driver and the programmer does not invoke it directly. Statement The methods of the Statement interface are used to execute SQL statements and retrieve data into the ResultSet. This interface contains an InputStream that contains a stream oriented values. The readXXX methods (where XXX represents any data type) of this interface are used to read the attributes from the input stream. the driver uses it. Object class. 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.sql Date The Date class contains methods to perform conversion of SQL date formats and Java Date objects. This class inherits its methods from the java. 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.673 j getAttributes() j getSQLTypeName() Classes in java. .lang. .util. Date as a SQL Time value.object class. The methods of this class are used to perform SQL time and java Time object conversions. 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. called JDBC types.lang. 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 Types class defines constants that are used to identify generic SQL types. It allows the JDBC to identify java.674 Time The Time class extends the Date class. Its methods are inherited from the class object. The information given in the exception includes a string describing the error. They are: j j j j j j j Import the java. When an error occurs in the batch update operation then BatchUpdateException is thrown at runtime. The SQLException provides information on a database access error.sql package Register the driver Connect to the database Create a statement Execute the statement Retrieve the results Close the statement and the connection . the error code and a chain to the next exception.sql There are four Exceptions in java. The SQLWarning provides information on database access warnings and is chained to the object whose method caused it to be report. Let us see each of them in detail.sql class. SQLException The SQLException extends Exception.675 Exceptions in java. Steps for using JDBC There are seven basic steps for using JDBC to access a database. SQLWarning The SQLWarning extends SQLException. a string describing the SQLState. BatchUpdateException The BatchUpdateException extends the SQLException. String passwd). The return value connected to the url. Connect to the database The next step is to connect to the database . . let us consider the following Import the java.user is the database user and passwd is the password to be supplied to get connected to the database. of these steps in detail. When you want to make java-database connectivity then the programmer is bound to import java. 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.sql package The interfaces and classes of the JDBC API are present inside the package called java.676 Before dealing about each case.registerDriver(Driver dr) . Syntax DriverManager.getConnection(String url. Syntax DriverManager.sql.*.sql package. String user . Where url is the database url of the form jdbc:subprotocol:subname.The getConnection() method is used to establish the connection. prepareStatement(String str).The syntax of each of these is given below: Syntax cn. int rsConcur ) . rsType and rsConcur denote and type and concurrency of ResultSet . where cn is a connection object and str is a sql statement that may contain one or more IN parameter place holders. Where cn is a connection object.createStatement().preparestatement(string str. rsType is a result set type and rsConcur is a concurrency type. This method creates and returns a PreparedStatement object for sending sql statements with parameters to the database. int rsConcur). Where cn is a connection object. Where cn is a connection object. cn. This method creates a statement object that will generate ResultSet objects with the given type and concurrency. cn. creates and returns a statement cn. This method creates a preparedstatement object that will generate ResultSet objects with the given concurrency.677 Create a statement A statement can be created using three methods. createStatement(). namely.createStatement(int rsType. str is a SQL statement. . This method object for sending SQL statement to database. int rsType . respectively. cn.prepareCall(string str).prepareStatement() and prepareCall(). They are execute (). This method returns a Boolean value and is used to execute any SQL statement.678 where cn is a connection Object and is a SQL statement that may contain one or more IN parameter placeholders. The return value is a Boolean . Execute the Statement We have three methods to execute the statement. it is more efficient to use a PreparedStatement.preparecall(String str. It creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency. which is true if the next result is a ResultSet and false if it is an update count. str is a SQL statement.execute(). . SQL statements without parameters are normally executed using Statement objects. This method is used execute an SQL statement that may return multiple results. Where cn is a connection object. This method creates and returns a CallableStatement object for calling database-storing procedures. Let us see the syntax of these below: Syntax Stmt. Stmt. Stmt. Where stmt is a PreparedStatement object. int reConcur). retype is a result set type and rsConcur is a concurrency type. If the same SQL statement is executed many times. Where stmt is a statement object.executeQuery(). or there are no more results.execute(string str). int retype. cn. Where stmt is a statement object and str is an SQL statement. executeQuery() and executeUpadate(). The method returns a result set generated by executing the query in stmt. DELETE statement this method return value is an int.executeQuery(string str). For example. which counts the number of rows are affected. This method takes query as string & is invoked by the statement object Stmt & returns the ResultSet.The return type is void. stmt. Where cn is the connection to be closed.The syntax is given below: Syntax Stmt.next() method. UPDATE. . The close() method is used to close the statements and connection.close(). To retrieve the data from the ResultSet we need to use the getXXX methods. Retrieve the results The results of the SQL statements (in particular q ueries are) are stored in a ResultSet object. getString is used to retrieve the string value and getDate() is used to retrieve a date value. By the object of PreparedStatement this method executes SQL statements. But . This methods release stmt¶s database. it is better to close the connections.close(). These methods retrieve the data and convert it to a java data type. since open connection can cause problem. To move in to the next row in the ResultSet we make use of the ResultSet. Here stmt is a statement object and str is a SQL statement for performing INSERT. Where stmt is a statement object to be closed. Close the statement and connection It is not absolutely necessary to close the connection. There is a separate getXXX methods for each data type. UPDATE or DELETE task. Stmt. In case of INSERT. Here stmt is an object of PreparedStatement.executeUpdate().679 Stmt.executeUpdate(string str). Cn.The getXXX takes one argument which is the index of the column in the ResultSet and return the value of the column. The create command is used to create database tables. Let us consider the case of ³The Rhythm´.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.Let us learn how to execute each of these. In this part we will be learning how to execute Data Definition Language (DDL) and Data Manipulation Language(DML) commands. 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) . alter and drop . DDL Commands The DDL commands are create. 2).681 Price Number(5.tranid Example-5(Create The table) import java.driver.ProdName Number(5.registerDriver(new oracle. . Address varchar2(30)).on.OracleDriver()). Create table Product (ProdId Number(3). CustName varchar2(15). Price Create table Transaction (Custid Number(3). Stock.sql.Qty Number(2) .ProdId Number(3). public class Customer1 { public static void main(String args[])throws SQLException { DriverManager. TranDt Da2te).* .jdbc. Number(3).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).hand Number(4) ). varchar2(10). cn."sai").println(³The Exception raised is ³ + ex).*. System. Statement st =cn.println("Connection to the database«").getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11".createStatement ()."sai". }catch(SQLException ex) { System.682 System. try{ st.println("Connected to the database"). } } Connection to the database« Connection to the database« Table customer created Example-6(Table Transaction Altered) import java.close(). Connection cn=DriverManager. System. .Address varchar2(30))"). } st.out.sql.CustName varchar2(15).println(³Table Customer Created´).close().out.out.out.executeUpdate("create table Customer(CustId number(3). st=cn.createStatement()."sai". }catch(Exeception ex) { System.println("The Exeception raised is:"+ ex).jdbc. try{ Connection cn=DriverManager.executeUpdate("alter Number(4))").out.registerDriver(new oracle. System.out.out.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11".driver. Statement.oracleDriver())."sai").683 public class Customer_alt { public static void main(String args[])throws SQLException { DriverManager. System. st. } } } table Transaction modify(Qty The output is as follows: Connected to the database Table Transaction altered .println("Connected to the database").println("Table Transaction altered"). } } } The out put is follows: Connected to the database Column amount dropped DML Commands .sql."sai").driver.").createStatement().println("Table Trans dropped").println("Connected to the database"). System. }catch(Exeception ex) { System.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11".oracleDriver()).executeUpdate("drop table Trans").out.out.out.*. System. try{ Connection cn=DriverManager. st.684 Example-7(Column Dropped) import java.registerDriver(new oracle.out. System."sai"..println("The exception raised is:"+ex). public class Customer_drop { public static void main(String args[])throws SQLExeception { DriverManager.jdbc.println("Connecting to the database«. Statement st=cn. "sai").getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11". Now the tables are created. st.driver. wants to input the data in the tables. System. public class CustomerInsert { public static void main(String args[])throw SQLException { DriverManager.println("one row inserted"). into customer values (100.createStatement(). Statement st = cn.sql. try{ Connection cn=DriverManager."sai".*.OracleDriver()).close(). System. insert. µusha¶.println(³Connected to the database´). Pioneer System Ltd. Orissa¶)").out.685 The Data Manipulation Language Commands are the select. The insert command is used to input the data and the select command is used to retrive the records from the tables.executeUpdate("insert µ100. st.close(). update and delete commands. Example-8(Insert a row in the table) import java.Oracle. cn.jdbc.Cuttack .out.registerDriver(new oracle. }catch(Exception ex) { .Naya Bazar. 686 System.registerDriver(new oracle. refValue=readEntry("Enter the Product ID: ").println(³The Exception raised is ´ + ex).sql. import java. } } } The output is as follows: Connected to the database One row inserted Example-9(Update a row) import java. String UpdateValue.io. .getConnection ("jdbc:oracle:thin:@:1521:orc11". public class ProductUpdate { public static void main(String args[])throws SQLException.out.IOException { DriverManager. String refValue."sai").driver.*.jdbc. updateValue=readEntry("Enter the new Price: ").OracleDriver())."sai".*. String Str. try{ Connection cn = DriverManager. }catch(IOException ex) .toString(). System.in. cn. st. }catch(Exception ex) { System.println("The Exception raised is "+ex).out. } } static String readEntry(String prompt) { try{ StringBuffer tempo=new StringBuffer().out.close().println("Row Updated"). System.in.append ((char)c).out.flush(). st. System.close(). str="update product set price = "+ updateValue + ". int c=System.read ().executeUpdate(str).createStatement().687 Statement st=cn.out."+"where prodId ="+refValue . c=System. } return tempo. while (c!='\n' && c != -1) { tempo.print(prompt).trim().read(). registerDriver(new oracle. System.00 Row update Example-10(Delete One row) import java. st. try{ Connection cn = DriverManager.sql.jdbc.executeUpdate("delete from Product where ProdId=105").OracleDriver()). } } } The input and output are as follows: Enter the product id: 100 Enter the new price: 110."sai"). System.out.driver. .*.createStatement(). public class CustomerDel { public static void main(string args[])throws SQLExeception { DriverManager.println("One row deleted").out. Statement st=cn.688 { return "".getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11"."sai".println("Connected to the database"). Let us see examples of equi join and outer join.out.println("The Exception raised is:" +ex).*. import java.689 }catch(Exeception ex) { System. } } } 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.sql.*: public class ListTran { . A join is a database operation that relates two or more tables by names of values that they share in common. Example-11(Join Two Table) import java.io. Joins There are different types of joins available in Oracle. This is a case where the join is needed. transaction where System.getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11". } rs.out.prodname.690 public static void main(String args [])throws SQLExeception. ResultSet rs product.proid=transaction.OracleDriver()).registerDriver(new oracle:jdbc:driver. st.out.prodid.getgetInt(3) + "\t" + rs. } } } The output of the program is as follows: .getString(2)+"\t"+ rs.qty product.out.close()."sai").trained. try{ Connection cn= DriverManager.executeQuery("select product.close().prodid").Println(rs.close(). while (rs. = from st.createStatement(). }catch(Exeception ex) { System.IOExeception { DriverManager.next()) { System.getInt(1)+"\t"+rs.println("ProdID\tProdName\t\tTranID\tQuantity"). Statement st= cn."sai".println("the exception is " +ex). cn.getInt(4))). sql. Example-12(Transaction) import java. in addition to the inserting the corresponding record in the Transaction table. Cn. then the data will become inconsistent.*. the corresponding row in the Product table should also be updated.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.*.io.setAutoCommit (false) . public class TransCmt { public static void main(String args [])throws SQLException. In order to be sure that either both the operations are executed or neither of them is executed. import java. A transaction is a set of one or more statements that are executed together as a unit. Whenever there is a transaction.IOException . Let us take the instance of The Rhythm. If either of the operations fails. we can make use of transitions. jdbc. }catch(Exception ex) { System.out. Statement stm=cn.prinln("Changes commited") st. cn. Statement stmt = cn.executeUpdate("Update Product set stock_on_hand = " + i + "where ProdId = 103").next(). stmt.setAutoCommit(false). rs. 101. i = i -1. 6. System."sai".createStatement(). cn.createStatement(). 1.createStatement(). cn.executeUpdate("Insert into transaction values(103. stm.close().registerDriver(new oracle. stock_on_hand from product where .println("The Exception raised is " + ex). '3jan-09¶)").driver. rs=st.OracleDriver()) .rollback(). try{ Connection cn=DriverManager. ResultSet rs.692 { DriverManager."sai").getConnection ("jdbc:oracle:thin:@rashmi:1521:orc11". cn.commit().getInt(1). Statement st=cn.close().out. int i=rs.executeQuery("select ProdId=103"). If the database is changed.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. . no matter same program will serve your problem. D.out. A ClassCastException is thrown at line 6.694 Chapter-30 Brain Teasers QUESTION 1 public class Test1 { public static void main(String args[]) { class Foo { public int i = 3. QUESTION 2 public class Test2{ public static void main(String args[]){ int i =1. Foo foo = (Foo)o. i = 3 B. } Object o = (Object)new Foo(). . Compilation fails.println("i = " + foo.j =10. C. } } What is the result? A. A ClassCastException is thrown at line 7. System.i). } . demo = new Demo().out. System. } void takeDemo(Demo demo) { demo = null. i = 6 and j = 5 B.695 do { if(i++> --j) { continue.println("i = " +i+ "and j = "+j). i = 5 and j = 5 C. i = 6 and j = 6 QUESTION 3 class Test { private Demo d. i = 5 and j = 6 E.takeDemo(d). What is the result? A. i = 6 and j = 5 D. } } while (i <5). void start() { d = new Demo(). this. QUESTION 4 interface Animal { void soundOff().696 } When is the Demo object. After the start() method completes.println("Roar"). After line 9. After line 5. } class Elephant implements Animal { public void soundOff() { System.out. eligible for garbage collection? A. . D. When the instance running this code is made eligible for garbage collection.out. created on line 3. C. B. When the takeDemo() method completes. E.equalsIgnoreCase( "meat eater" )) { return new Lion(). } } class Lion implements Animal { public void soundOff() { System.println("Trumpet"). } } class Alpha1 { static Animal get( String choice ) { if ( choice. println("i =" +i+" and j = "+j). new Animal(). C.697 } else { return new Elephant(). QUESTION 5 public class Test { public static void main(String args[]) { int i = 1. } while (++i <5). Elephant e = new Alpha1(). .out.get("veggie"). } } } Which compiles? A. do { if(i>j) { break. B. } j--. System.get("meat eater"). D.soundOff().soundOff(). new Alpha1().j = 10. Lion 1 = Alpha. h. i = 6 and j = 4 D.held). i = 6 and j = 6 QUESTION 6 class Test { public static void main(String args[]) { Holder h=new Holder(). i = 6 and j = 5 B. i = 5 and j = 6 E. h. } } class Holder { .out. System.println(h.bump(h).698 } } What is the result? A. i = 5 and j = 5 C.held=100. 0 1 100 101 QUESTION 7 public class Test { public static void aMethod() throws Exception { try { throw new Exception().held++. B.out. } catch (Exception e) { . } } public static void main(String args[]) { try { aMethod(). } } What is the result ? A.println("finally"). C. } finally { System. public void bump(Holder h) { h. D.699 public int held. QUESTION 8 package test1. exception finished C. } System.out. Compilation fails.700 System.out.Test1 { public static void main(String[] args) { System.println("exception"). public class Test1 { static int x = 42.out. } package test2. finally B. } } What is the result? A. finally exception finished D.println("x = " + x). public class Test2 extends test1. } .println("finished"). } public static void main( String[] argv ) { int i =0. return true. foo('D'). Compilation fails because of an error in line 4 of class Test2. foo('C')){ i++ .701 } What is the result? A. D.out. Compilation fails because of an error in line 3 of class Test1.print(c). QUESTION 9 public class Delta { static boolean foo(char c) { System. for ( foo('A'). x = 0 B. x = 42 C. foo('B')&&(i<2). E. } } } What is the result? . Compilation fails because of an error in line 2 of class Test2. An exception is thrown at runtime. Decrement de=new Decrement(). } } What is the result ? . D.decree(d). QUESTION 10 class Test { public static void main(String args[]) { double d=12. } } class Decrement { public void decree(double d1) { d1=d1-1.3.println(d). de.out. Compilation fails.702 A. System.0. ABDCBDCB B. ABCDABCD C. D. An error at line 5 causes compile to fail. f2[]. It prints f2[0] = NaN. System. C. f2 = f1. An error at line 6 causes an expectation at runtime. An error at line 6 causes compile to fail.println("f2[0]= " + f2[0]).0 ±1. QUESTION 12 public class Test { public int aMethod() { . E.0 12. 0. B.3 QUESTION 11 public class ArrayTest { public static void main(String[] args) { float fl[].3 11. fl = new float[10].703 A. D. } } What is the result? A. It prints f2[0] = 0.out. B.0. C. int j = test.println(j). 1 C. System. test. } else if (bool) { . } } What is the result? A.out.aMethod(). 2 D.out.704 static int i = 0. } public static void main (String args[]) { Test test = new Test(). QUESTION 13 public class Test{ public static void main(String args[]){ boolean bool = true. 0 B. if(bool = false) { System. i++. return i. Compilation fails.aMethod().println("a"). println("c"). b C. } else { System. byte c=15. System.out.out.705 System.println("c").out. } } .out. } What is the result? A. QUESTION 14 public class Xor { public static void main(String args[]) { byte b=10.println("d"). b=(byte)(b^c) . Compilation fails. } else if (!bool) { System.println(b). d E. a B. c D. QUESTION 16 . C. } } Which is true? A. An exception is thrown at line 7. C. 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(). D. An exception is thrown at line 2. B. Compilation fails. D. The code runs without exception. B.706 What is the output ? A. E.707 public class Test{ public static void main(String args[]){ int i = 0.println("value = " + switchIt(4)).println(i). 0 2 4 5 C. i <4. Compilation fails.print(i + "").out. for (. 0 1 2 3 4 D. QUESTION 17 public class SwitchTest { public static void main(String[] args) { System. i += 2) { System.out. 0 2 4 B. An exception is thrown at runtime. } System. switch (x) { . } public static int switchIt(int x) { int j = 1. } } What is the result? A.out. value = 3 B.708 case 1: j++. value = 6 E. value = 8 QUESTION 18 public class Foo { public static void main(String[] args) { try { return. case 3: j++. } return j + x. value = 5 D. value = 4 C. } finally { . } } What is the result? A. value = 7 F. case 2: j++. default: j++. case 4: j++. case 5: j++. Compilation fails. } } } What is the result? A. C. The code runs with no output. Finally B.println( "Finally" ). System. int i=0.709 System. D.out. flag = i < 10.println( i++ ). QUESTION 19 public class Alpha1 { public static void main( String[] args ) { boolean flag. do { flag = false. } while ( (flag)? true:false ). } } What is the result? . An exception is thrown at runtime.out. continue. " + sub. The code runs with no output.toString() + ".getLenght(). The code enters an infinite loop. Compilation fails. 5. 4.4 . System.710 A.getLenght(). } public static void main(String[] args) { Super sooper = new Super(). E. } } public class Sub extends Super { public Long GetLenght() { return new Long(5). 000000000 B. D. QUESTION 20 class Super { public Integer getLenght() { return new Integer(4).println(sooper.4 B. An exception is thrown at runtime. 0123456789 C.out. F.5 C. Sub sub = new Sub(). 4. } } What is the output? A.toString() ). . } public static void main(String args[]) { foo(0).5 E.711 D. QUESTION 21 public class Test { public static String output ="". } catch(Exception e) { output += "2". return. public static void foo(int i) { try { if(i==1) { throw new Exception(). Compilation fails. 5. } output += "4". foo(1). } output += "1". } finally { output += "3". new Base(). Compilation fails. . E. The code runs with no output. Base B. BaseBase C. D.out. } } public class Alpha extends Base { public static void main( String[] args ) { new Alpha(). } } What is the result? A.712 } } What is the value of the variable output at line 23? QUESTION 22 class Base { Base() { System.print("Base"). An exception is thrown at runtime. println("j="+j). } } What is the result? A. j = 2 E. case 2: j = 2.1: j = 1. QUESTION 24 . j = 1 D.j = -1. switch (i) { case 0. default: j = 0. j = 0 C. j = -1 B.out. } System.713 QUESTION 23 public class Test{ public static void main(String args[]){ int i = 1. Compilation fails. Answer: C .out.print("C"). } public static void badMethod() {} } What is the result? A.print("D"). Compilation fails. System. BD C. ABCD E.out. } System.out.print("B"). AC B. ACD D.714 public class X { public static void main(String [] args) { try { badMethod(). } catch (Exception ex) { System. } finally { System.print("A").out. } } } What is the result? A.out. switch (f) { case 12: System. Compilation fails. Twelve Zero Default E. Zero B.println("Zero").println("Twelve"). case 0: System.out. default: System.715 QUESTION 25 public class Test{ public static void main(String args[]){ Float f = new Float("12"). Default D. QUESTION 26 public class X { public static void main(String [] args) { . Twelve C.println("Default").out. } catch (Exception ex) { System.out.out.out. } public static void badMethod() { throw new RuntimeException(). } System.print("C").print("B"). System.print("A"). QUESTION 27 .print("D"). BCD E.out. ABC D.716 try { badMethod(). AB B. } } What is the result? A. BC C. Compilation fails. } finally { System. i <3.out. case 3: System.out. What is the result? A.print("two "). done B. one two done C. one two three done D.print("one "). case 1: System.println("done"). i++) { switch(i) { case 0: break. Answer: D QUESTION 28 public class Conditional { public static void main(String args[]) { .out. one two three two three done E.717 public class Test{ public static void main(String args[]){ for (int i =0.out. } } System. Compilation fails.print("three "). case 2: System. System.9 Value is 9 Value is 9.out. 1)).0 Value is 99 Compile Time Error class A { final public int method1(int a.println(³Value is ´+((x>4) ? ) 99. B. } } public class Test { public static void main(Strings args[]) { B b. E. C.718 int x=4. } } class B extends A { public int method1(int a. int b) { return 1.method1(0. D. } } What is the output ? A.println("x = " + b.out.9 : 9). int b) {return 0. QUESTION 29 Value is 99. System. } . } public static void main(String[] args) { Super sooper = new Super(). D.out.println(sooper. En exception is thrown at runtime.719 } What is the result? A." + sub.getLenght() + ". x = 1 C. x = 0 B.getLenght() ). } . QUESTION 30 class Super { public int getLenght() { return 4. } } public class Sub extends Super { public long getLenght() { return 5. Compilation fails. System. Sub sub = new Sub(). 4 B.720 } What is the output? A. Compilation fails. } public static void main(String args[]) { System.4 D. 4.5 E.out. 4.println(x).5 C. QUESTION 31 class Test { static int x=10. } static{ x/=5. } } . static{ x+=5. 5. 5. out. .print("B").print("C"). D. } System. Compile time error 10 15 3 QUESTION 32 public class X { public static void main(String [] args) { try { badMethod(). System.721 What is the output ? A. } finally { System.out. B.print("A"). } catch (RuntimeException ex) { System.out.out. C.out.print("E"). } catch (Exception ex1) { System.print("D"). } public static void badMethod() { throw new RuntimeException(). } } What is the output A. byte c=a*b. byte b=2. System. ABCDE F. Compilation fails. BDE D. BCDE E. QUESTION 33 public class Test { public static void main(String args[]) { byte a=2. BCD C.722 } } What is the result? A. Compile time error .out.println(c). BD B. The code does not run. } } What is the result if this code is executed with the command line? java Foo world A.) { .. E. Compilation fails. for (. 0 QUESTION 34 public class Foo { public void main( String[] args ) { System. tp. 00000100 D. Hello world D. j = 5. 4 C. QUESTION 35 public class Test{ public static void main(String ags[]){ int i = 0. Hello B.out. Hello Foo C.println( "Hello" + args[0] ).723 B. . j = 0. break tp.) { if (i> --j) { break tp. } } System. case 4: j +=1. i = 1. QUESTION 36 public class Test { public static void main(String Args[]) { int i =1.println("i=" +i ". j = 4 C. i = 3.724 i++. j = 0 B. i = 1.. Compilation fails. What is the result? A. j = 0 E. default: j +=2. j = 4 D.j ="+j).out. for(. i = 3. switch(i) { case 2: j +=6. public Super(String text) { i = 1. 0 B. 9 F. 13 QUESTION 37 class Super { public int i = 0. } .725 case 0: j +=4.println("j =" +j). } System. 6 E. 4 D. 2 C. } } What is the result? A.out. } } public class Sub extends Super { public Sub(String text) { i = 2. i).out. } . } while (++i <6).println(sub. } j--. Compilation fails. QUESTION 38 public class Test{ public static void main(String args[]){ int i = 1. } } What is the result? A.out.726 public static void main(String args[]) { Sub sub = new Sub("Hello"). System. 0 B.println("i = " +i+" and j = "+j). do{ if (i>j) { continue. 1 C.j = 10. System. 2 D. y=4. i = 5 and j = 5 C. if(x>2) { if(x<5) { System.println(³Message Two´). i = 6 and j = 4 D. i = 6 and j = 5 B.z=5.727 } What is the result? A. . i = 6 and j = 6 QUESTION 39 public class Test { public static void main(String args[]) { int x=0. i = 5 and j = 6 E.out.println(³Message One´) }else{ System.out. } } else if(z > 5) . out.out.print("A"). .out. B.out. } finally { System. C.println(³Message Three´). } catch (Exception ex) { System.out.println(³Message Four´). }else{ System. Message Message Message Message One Two Three Four QUESTION 40 public class X { public static void main(String [] args) { try { badMethod(). D.print("B"). System.print("C").728 { System. } } } What is the output ? A. } catch (Exc0 e0) { System. E.out. D. BCD is printed before exiting with an error message.println("Ex0 caught"). C. C is printed before exiting with an error message. ABCD B. } catch (Exception e) { .out.729 } System. Compilation fails. } } What is the result? A. } public static void badMethod() { throw new Error().print("D"). QUESTION 41 class Exc0 extends Exception { } class Exc1 extends Exc0 { } public class Test { public static void main(String args[]) { try { throw new Exc1(). BC is printed before exiting with an error message. println("Class A"). Compilation fails because of an error at line 2.730 System. Ex0 caught B. . } } } What is the result? A.println("exception caught"). exception caught C. } public static void main(String[] args) { new A().out. Compilation fails because of an error at line 6. } } What is the result? A. Compilation fails. D.out. QUESTION 42 public class A { void A() { System. Class A B. System.out.println("newBar").doBar(). D. newBar = new Bar(). E.out. return b. An exception is thrown at line 6. The code executes with no output.println("finishing"). QUESTION 43 class Bar { } class Test { Bar doBar() { Bar b = new Bar(). Bar newBar = t. System. } } What is the output? QUESTION 44 . } public static void main (String args[]) { Test t = new Test(). An exception is thrown at line 2.731 C. D. Compilation fails.732 interface Beta {} class Alpha implements Beta { String testIt() { return "Tested".out. } public static void main( String[] args ) { Beta b = getIt(). QUESTION 45 public class Test{ public static void main(String ar[]){ . } } public class Main1 { static Beta getIt() { return new Alpha(). Tested B. The code runs with no output. C.println( b. An exception is thrown at runtime. System.testIt() ). } } What is the result? A. while (y--) { x++.println("x =" + x + "y =" +y). x = 6 y = 0 B. } ++i.733 int x = 1. QUESTION 46 public class Test{ public static void main(String ar[]){ int i = 0. x = 6 y = -1 D. while (true) { if(i==4) { break. } } What is the result? A. } . Compilation fails.out. } System. x = 7 y = -1 E. y =6. x = 7 y = 0 C. i = 4 D. i = 3 C. Compilation fails. int y = 5 / x. } System.println("i="+i). } } What is the result? A.out.out.out. } catch (Exception e) { System.out.println("Exception"). } catch (ArithmeticException ae) { System. i = 5 E. } } .println("Arithmetic Exception").println("finished"). QUESTION 47 public class Test{ public static void main(String args[]){ try { int x = 0.734 System. i = 0 B. Compilation fails. D.length == 2 ) { if ( args.735 What is the result? A.[0]. Compilation fails. .println( new Boolean( args[1] )). Arithmetic Exception QUESTION 48 public class Alpha{ public static void main( string[] args ){ if ( args.out. finished B. Exception C. true B. false D. } } } And the code is invoked by using the command: java Alpha -b TRUE What is the result? A.equalsIgnoreCase("-b") ) System. null C. j = 2 D. The code runs with no output. i = 42. j = " + j). j = 2 B. j = 1 E. QUESTION 49 public class Test{ public static void main(String args[]){ int i = 0. j = 1.736 E.out. An exception is thrown at runtime. } } What is the result? A. Compilation fails. i = 1. j = 1 C.println("i = " + i + ". i = 42. } System. if ((i++ == 1) && (j++ == 2)) { i = 42. Answer: B QUESTION 50 . F. i = 1. An exception is thrown at runtime. 0 B. } } What is the result? A.out. 1 C.737 public class X { private static int a. } public static void main(String args[]) { . QUESTION 51 public class Test { public static void add3 (Integer i) { int val = i. D.intValue(). public static void main(String [] args) { modify(a). val += 3. System. Compilation fails.println(a). } public static void modify(int a) { a++. i = new Integer(val). intValue()). abc B. QUESTION 52 public class Test{ public static void main(String ar[]){ String a = null. 3 C. System. a.out. 0 B.concat("def"). add3(i). null .738 Integer i = new Integer(0). a. D. An exception is thrown at runtime.println(a). } } What is the result? A.out. System.println(i. } } What is the result? A. Compilation fails.concat("abc"). true B.out.length > 4 && args[4]. E. abcdef D. Compilation fails. Compilation fails. The code runs with no output. F. QUESTION 53 public class Test { public static void main(String [] args) { System. Answer: D QUESTION 54 . } } If the program is invoked using the command line: java Test One Two Three -d What is the result? A. D. false C. An exception is thrown at runtime.equals("-d")). An exception is thrown at runtime.println(args.739 C. public float getVar() { return x. // insert code here } Which two are valid examples of method overriding when inserted at comment line ? (Choose two) A. } D. float getVar() { return x. . } B. } } class SubClass extends BaseClass { private float x = 2.Of. protected float getVar() { return x.of. } E.740 class BaseClass { private float x = 1. } QUESTION 55 class A { public byte getNumber() { return 1. public float getVar(float f) { return f. protected float getVar() { return x. public double getVar() { return x. } C. Compilation fails. QUESTION 56 class A { public A() { System.println(b. 1 B.out. An exception is thrown at runtime. } } class B extends A { .out. } } What is the result? A. } public static void main(String args[]) { B b = new B(). D. 2 C.getNumber()).741 } } class B extends A { public short getNumber() { return 2.println("hello from a"). System. hello from a hello from b QUESTION 57 class MyThread extends Thread { public void run() { System. B.742 public B () { System.println("AAA"). Compilation fails. } } public class Test { public static void main(String args[]) { A a = new B(). super(). hello from b D. hello from a C. .out.out.println("hello from b"). } } What is the result when main is executed? A. hello from b hello from a E. } } What is the result? A. public static void main(String [] args) { X that = new X().start(). AAA B. private int y. BBB C. The code runs with no output.743 } public void run(Runnable r) { System. } public static void main(String[] args) { new Thread(new MyThread()). (new Thread( that )).start(). QUESTION 58 public class X implements Runnable { private int x.out. (new Thread( that )).println("BBB"). .start(). D. Compilation fails. y = 1"). The program prints pairs of values for x and y that might not always be the same on the same line (for example..out. y = 2"). The program prints pairs of values for x and y that are always the same on the same line (for example. The thread name at the start of the line shows that both threads are executing concurrently. y++. C. "x = 1.println(Thread.) { synchronized (this) { x++.744 } public void run() { for (. } } } What is the result? A. Compilation fails. each value appears only once (for example. y = 1" followed by "x = 2. y = 1").currentThread(). } System. B. "x = 1. . In addition.getName() + "x = " + x + ". "x = 2. y = " +y). start(). try { Thread. The thread name at the start of the line shows that only a single thread is actually executing.println("A done").out. Answer: D QUESTION 59 public class A extends Thread { A() { setDaemon(true).sleep(60000). "x = 1. y = 1" followed by "x = 2. . each value appears only once (for example. } catch (InterruptedException x) { } System. } public void run() { (new B()). } class B extends Thread { public void run() { try { Thread.sleep(60000). y = 2"). The program prints pairs of values for x and y that are always the same on the same line (for example. y = 1"). "x = 1. In addition.745 D. start(). public static void main(String[] args) { System. There is no exception that the application will print anything. in no guaranteed order. .println("B done"). } } What is the result? A. A done B. A done B done D. } } public static void main(String[] args) { (new A()). B done A done E. The application outputs "A done" and "B done". B done C. QUESTION 60 public class Test { private static int[] x.out.out.746 } catch (InterruptedException x) {} System. F.println(x[0]). 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. . A NullPointerException is thrown at runtime. 0 B. } What is the result? A. Compilation fails. } }. null C.747 } } What is the result? A. An exception is thrown at runtime. C. D.println(obj.hashCode()). 42 B. Compilation fails because of an error on line 12.out. E. System. E.0 C. QUESTION 62 public class Test { private static float[] f = new float[2]. f[0] = 0. f[0] = 0 B. } } What is the result? A. public static void main(String args[]) { System.println("f[0] = " + f[0]).println(str). QUESTION 63 public class Test { public static void main(String[] args) { String str = NULL. Compilation fails because of an error on line 17. } } .out.748 D. Compilation fails. D. An exception is thrown at runtime. System. Compilation fails because of an error on line 16.out. Compilation fails.out. Infinity D.sqrt(-4D)). NULL B. } } What is the result? A. C. QUESTION 64 public class Test{ public static void main(String ar[]){ System. QUESTION 65 public class Test{ public static void main(String args[]){ . E. An exception is thrown at runtime. D.749 What is the result? A. An exception is thrown at runtime.println(Math. The code runs with no output. NaN C. Compilation fails. -2 B. replace('b'. } static void operate (StringBuffer x.printIn{a + ". b.out. abcd B. System. 'd')." +b}.replace('a'. ABCD C.toLowerCase(). dccd D. dcba E. F. operate (a. System. Compilation fails. StringBuffer b = new StringBuffer ("B"). QUESTION 66 public class Foo { public static void main (String [] args) { StringBuffer a = new StringBuffer ("A"). 'c').750 String a = "ABCD".out. String b = a.println(b).b). StringBuffer y) { . b. } } What is the result? A. An exception is thrown at runtime. B". 'i').751 x.B". } public static void bufferReplace(StringBuffer text) { text = text. The code compiles and prints "A. F.B". The code compiles and prints "AB.append ("C") } public static void main (String args[]} { String textString = new String ("java"). The code does not compile because "+" cannot be overloaded for StringBuffer. y = x.A". . StringBuffer textBuffer= new StringBuffer ("java").AB". C. QUESTION 67 public class Test { public static void stringReplace (String text) { text = text. D. The code compiles and prints "A.replace ('j' . The code compiles and prints "AB. The code compiles and prints "B. E.append(y). B. } } What is the result? A. " +b}. operate (a. StringBuffer y) { x.out. } } What is the result? . StringBuffer b = new StringBuffer ("B"). System.append {y}. y = x.752 stringReplace (textString). System. bufferReplace (textBuffer). } static void operate (StringBuffer x.out. } } What is the output? QUESTION 68 public class Foo { public static void main (String [] args) { StringBuffer a = new StringBuffer ("A").println{a + ".println (textString + textBuffer).b). D. The code compiles and prints "AB. i= Test. C. The code does not compile because "+" cannot be overloaded for StringBuffer.k.AB". B.B". D.B".A". An error at line 9 causes compilation to fail. The code compiles and prints "A. Compilation succeeds. E.k. The code compiles and prints "A. } public class Test implements Foo { public static void main(String args[]) { int i. An error at line 10 causes compilation to fail. i= Foo. . i= test.B". The code compiles and prints "AB. The code compiles and prints "B. Test test = new Test (). An error at line 2 causes compilation to fail. C. F. QUESTION 69 interface Foo { int k = 0.753 A.k. } } What is the result? A. B. QUESTION 70 public class Test{ public int aMethod(){ static int i=0. int j = test.out. Compilation will fail. i++. An error at line 11 causes compilation to fail. System. } public static void main (String args[]){ Test test = new Test().754 E. Compilation will succeed and the program will print "1" D.aMethod(). Compilation will succeed and the program will print "2" QUESTION 71 public class Test { . B. return i. Compilation will succeed and the program will print "0" C.printIn(j). } } What is the result? A. while (i) { if (i==4) { break. } ++i. 5 E. 3 C. 4 D. The code will not compile.755 public static void main(string args[]) { int 1= 0. Answer: E QUESTION 72 public class A extends Thread { private int x=2. public static void main(String args[])throws Exception { . } } } What is the value of i at line 10? A. 0 B. 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 Frame¶s 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. } public static void main(String args[]) { ((Test1)new Test()). } } What is the output? QUESTION 88 interface Task1 { String toString().println(³Sai´). } public class Task { public static void main(String args[]) { System.println(new Task1() { .out.start(). 772 public String toString() { return "Java". b.go().go(). } } interface Go { .go(). S2 b=new S2(). } }). } } What is the output? QUESTION 89 public class Check { public static void main(String args[]) { S1 a=new S1(). S3 c=new S3(). a. c. out.println("C").773 void go().out. .println("Java") } } class S2 extends S1 { public void go() { System. } class S1 implements Go { public void go() { System. } } class S3 extends S2 implements Go { } . println(i). public void show(int i) { i+=i. System. t.774 What is the output? QUESTION 90 public class Text { int i=12. } } What is the output? QUESTION 91 public class Boot1 { . } public static void main(String args[]) { Text t=new Text().out.show(10). i).s+"\t"+b. System. public Boot1() { this("Java") . System.out.out. s=s1. String s.out.println(b.println("Second").println("First").775 int i. } public Boot1(String s1) { this(1. } } What is the output? . } public Boot1(int i1.println("Third")."See Java Program"). } public static void main(String args[]) { Boot1 b=new Boot1(). System. System.String s1) { i=i1.out. 776 QUESTION 92 public class N1 { public static void main(String args[]) { String str="null". QUESTION 93 public class Loop1 { .println("null").out.out.out. if(str==null) { System.println("zero"). } else if(str.length()==0) { System. } else{ System.println("Java") } } } What is the output? . iterator(). .reverse(l) . } } What is the output? QUESTION 94 import java. return l. } public static void main(String r[]) { List l1=new ArrayList(). System. public class Col1 { public static Iterator reverse(List l) { Collections. int y=10.777 public static void main(String args[]) { int x=0. }while(x<5). ++x. do{ y--.util.*.println(x+"\t"+y).out. sorted.util. } public static void main(String args[]) { . sorted. return sorted. sorted.add("3"). public class Col2 { public static Collection get() { Collection sorted=new LinkedList().778 l1. l1.add("1").print(obj+"\t").add("B") .add("2"). } } } What is the output? QUESTION 95 import java.add("C") . for(Object obj : reverse(l1)) { System.*.out.add("A"). l1. print("A. class Excep1 { public void process() { System.*.io.out.print(obj+"\t"). } } } What is the output? QUESTION 96 import java.out. } } public class Excep extends Excep1 { public void process()throws IOException { System."). throw new IOException().").print("B. } public static void main(String arg[]) .779 for(Object obj: get()) { System.out. process().780 { try{ new Excep(). }catch(IOException ie) { System.println("Exception").out. } } static class B extends A { void process() . } } } What is the output? QUESTION 97 public class Process { static class A { void process()throws Exception { throw new Exception(). println("B") } } public static void main(String args[]) { new B(). } } What is the output? . }catch(Exception e) { System. throw new RuntimeException().out.process().out.println("Caught").out.781 { System. QUESTION 98 public class Ex1 { static void test()throws RuntimeException { try{ System.print("Test") . } } public static void main(String args[]) . out. } } What is the Output? QUESTION 99 import java.io.out. public static void main(String args[]) { Forest f=new Forest().*.println("Runtime "). try{ .782 { try{ test(). class Tree { } public class Forest implements Serializable { private Tree t=new Tree().println("End"). } System. }catch(RuntimeException re) { System. j=j.close(). ObjectOutputStream oos=new ObjectOutputStream(fos) oos.int j) { this. oos.783 FileOutputStream fos=new FileOutputStream("A. static ObjectOutputStream oos.txt"). public Serial(int i. } private void writeObject(ObjectOutputStream oos)throws IOException . public class Serial implements Serializable { public int i. QUESTION 100 import java. } } } What is the output? .io.printStackTrace(). }catch(Exception e) { e. static ObjectInputStream ois.writeObject(f).*. this.i=i.j. readInt().writeInt(j).out.7).writeInt(i). System.oos=oos. oos. j=ois.readObject(ois).ois=ois.ClassNotFoundException { this.readInt(). s1. i=ois.784 { this.println(i+"\t"+j). } public static void main(String args[])throws Exception { Serial s1=new Serial(12.writeObject(oos). s1. oos. } } What is the output? . } private void readObject(ObjectInputStream ois)throws IOException.
Copyright © 2024 DOKUMEN.SITE Inc.