Core JAVA

HISTORY OF JAVA Java is a high-level object-oriented programming language developed by the Sun Microsystems , for the development of enterprise grade applications. This Language is evolved from a language named Oak. Oak was developed in the early nineties at Sun Microsystems as a platformindependent language aimed at allowing entertainment appliances such as video game consoles and VCRs to communicate. Oak was first slated to appear in television set-top boxes designed to provide video-on-demand services. Oak was unsuccessful so in 1995 Sun changed the name to java. Therefore Java 1.0 was officially released to the world. It was only developed keeping in mind the consumer electronics and communication equipments. A team of Sun Microsystems including Patrick Naughton, Mike Sheridan in the guidance of James Goslings decided to develop an advanced programming language for the betterment of consumer electronic devices.

Where is Java being Used?
Java-programming language was only developed for the small devices but now it can be found in a variety of devices like cell phones, e-commerce application, PCs and almost all network or computing devices. Java is available in different form: JSP – Like PHP and ASP, Java Server Pages based on a code with normal HTML tags, Which helps in creating dynamic web pages. Java Applets – This is another type of Java program that used within a web page to add many new features to a web browser. These are small program used in the programming of instant messaging, chat service, solving some complex calculation and for many other purposes. J2EE – The software Java 2 Enterprise Edition are used by various companies to transfer data based on XML structured documents between one another. JavaBeans – This is something like Visual Basic and a reusable software component that can be easily assemble to create some new and advanced application. Mobile Java - Java is also used for various entertainment devices especially

1

mobile phone. Mobile Information Devices Profile (MIDP) uses Java run time environment in cell phones, mobile tracking systems and other traditional PDA devices, including MP3 players, digital TV, video, 3D, simplifying games, etc.

Java as an Internet Language
The features that favors it to be an internet language are: - Cross Platform Compatibility: The java source files (java files with .java extension) after compilation generates the bytecode (the files with .class extension) which is further converted into the machine code by the interpreter. - The byte code once generated can execute on any machine having a JVM. Every operating system has it's unique Java

Virtual Machine (JVM) and the Java Runtime Environment (JRE).
Support to Internet Protocols: Java has a rich variety of classes that abstracts the Internet protocols like HTTP , FTP, IP, TCP-IP, SMTP, DNS etc . Support to HTML: Java programming language provide html pages as a view to interact with the user, that are used for web application. Support to XML parsing: This is used to share data among different applications over the internet. Support to Web Services : Java has a rich variety of APIs to use xml technology in diverse applications that supports N-Tiered Enterprise applications over the internet. Features like JAXB , JAXM, JAX-RPC , JAXR etc enables to implement web services in java applications. It makes java a most suited internet language. Support to java enabled Mobile devices: Java language also works with any java enabled mobile devices that support MIDP 1.0/2.0 including the symbian OS mobile devices.

-

Java Releases
The tables given below provide information about the name and time of releases for different versions of Java technology. Releases Event Month Year Java 1.5.0_09 October 2006 Java 1.5.0_08 August 2006 Java 1.5.0_06 December 2005 Java 1.5.0_05 October 2005

2

Java 1_5_0_04 July Java 1_5_0_01 February Java 2 Platform, Standard Edition 1.4 February (J2SE 1.4) Java 2 Platform, Standard Edition 1.3 May (J2SE 1.3) Java 2 Platform, Enterprise Edition December (J2EE) Java 2 Platform, Standard Edition (J2SE) August Java Development Kit 1.2 (JDK 1.2) December Java Development Kit 1.1 (JDK 1.1) February Java Development Kit 1.0 (JDK 1.0) January

2005 2005 2002 2000 1999 1999 1998 1997 1996

Download JDK
JDK(Java Development Kit) is a software development program provided by sun Microsystems. Java Development Kit or JDK comes in various version and can be downloaded free from the sun Microsystems. JVM compiler, debugger and other tools are used with JDK for developing java based application & java applets. So make sure that your JVM compiler & JDK versions are same. JDK also known as Java 2 Platform, That comes in three editions J2ME, J2SE & J2EE.

-

Java Features
Platform Independent Simple Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system. The concept of Write-once-run-anywhere (known as the Platform independent). The programs written on one platform can run on any platform provided the platform must have the JVM.

Object Oriented:

3

If any language used classes and objects that language is called Object Oriented Programming Language. - Object: is anything that is existing in the real world. - Object Properties: An instance of a class, Object is created using new operator for memory allocation. Method: - A method is a function - A function can return to anywhere - A method can return to inside a class - An object contains variables and methods Class: Is a template for multiple objects with similar features A class is a model for creating objects Class does not exists physically Without class we cannot create object. Class will also have variables and methods Objects will also have variables and methods Without creating atleast one class we cannot write java program

-

To be an Object Oriented language, any language must follow at least the four characteristics. Inheritance: It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed. Encapsulation :

It is the mechanism of combining the information and providing the abstraction.

Polymorphism : - As the name suggest one name multiple form. Dynamic binding : - It is the way of providing the maximum functionality to a program about the specific type at runtime. - As the languages like Objective C, C++ fulfills the above four characteristics yet they are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java, it is a fully Object Oriented language. Robust

4

The widely used protocols like HTTP and FTP are developed in java.Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form.Java has the strong memory allocation and automatic garbage collection mechanism.In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance. Multithreaded: . Interpreted .Compiler and interpreter by checking the errors makes the system secure from crash.While executing the java program the user can get the required files dynamically from a local drive or from a computer through the Internet.The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. Dynamic . Secure . Java as an interpreted language depends on an interpreter program. These features makes the java as a portable language.Java does not use memory pointers explicitly.The bytecode Verifier checks the classes after loading.Thus. . .The interpreter program reads the source code and translates it on the fly into computations. Portable . Security manager determines the accessibility options of a class like reading and writing a file to the local disk. and lightweight process called threads. - 5 . . . . .It provides the powerful exception handling and type checking mechanism as compare to other programming languages. .Java is also a Multithreaded programming language. Performance . .Multiple threads execute instructions according to the program code in a process or a program.Java uses native code usage. Distributed .Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system. .Java also have the standard data size irrespective of operating system or the processor. Multithreading means a single program having different threads executing independently at the same time.

. Byte code is an intermediary language between Java source and the host system. to be easily interpreted on any machine and to be easily translated into native machine code on the fly. given the presence of the Java runtime system. ArchitectureNeutral . The architecture of the JVM is given below - JRE consists of a number of classes based on JavaAPI and JVM. and without JRE.- Java as an interpreted language is its error debugging quality. Most programming language like C and Pascal converts the source code into machine code for one specific type of machine as the machine language vary from system to system . it is impossible to run Java. Java Virtual Machine(JVM) JVM is the main component of Java architecture and it is the part of the JRE (Java Runtime Enviroment) . 6 . Mostly compiler produce code for a particular system but Java compiler produce code for a virtual machine . JVM provides security to java.The Java compiler by generating byte code instructions. JVM is a part of Java Run Time Environment that is required by every operating system requires a different JRE .The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors. The programs written in Java or the source code translated by Java compiler into byte code and after that the JVM converts the byte code into machine code for the computer one wants to run. This is a software process that converts the compiled Java byte code to machine code. Due to this any error occurring in the program gets traced. It provides the cross platform functionality to java.

contain class code along with method code. 7 . Method Area: Bytecode instructions will be loaded . 4. Heap : Heap is second part of memory. Java Stack: Java method is executed. Native Method Stacks: Native methods are methods written in some other language like C or C++ 6. method return results are stored in Java Stack. PC Register: (Program counter Register):These registers store the address of the instruction being executed by Microprocessor 5.JVM Block Diagram Class Loader Sub System Run Time Data Areas Method Area (class code) Heap (create object) Java Stack (execute method) PC Register Native method stacks Execution Engine Native Method Interface Native method Libraries - Java Compiler is outside the JVM Class loader subsystem loads dot class files into memory and verifies the bytecode instructions and then allots required memory to execute instruction. Execution Engine: It contains Interpreter and JIT Compiler which translate the byte code instruction into machine language. Method parameters and temporary results .It contains objects. It is used for creating objects 3. The allotted memory is divided into five parts 1. 2.which are executed by MicroProcessor.

memory is allocated only to objects. so it becomes impossible to know exactly when memory will be reclaimed. JVM Runtime Environment contains the two parts such as: Java API classes: Java API classes are the predefined classes required for the program compilation and interpretation. so that it is impossible to accurately predict when one thread will be executed over another. no two JVMs are exactly alike. The Java runtime employs a garbage collector to reclaim the memory occupied by an object. Native Method Interface: is useful to linkup with the native methods or Microprocessor. Garbage Collection: It is the process that the Java Virtual Machine used to find and reclaim unreachable objects to free microprocessor memory space. The thread scheduling algorithms are different between one JVM and another . JVM Implementation: Though implementations of Java Virtual Machines are designed to be compatible. Memory Management with JVM :Java language in combination with runtime eliminates the problems of memory management and corrupted pointers. JVM ask the operating system for enough memory to run the JVM itself and some free memory for the application to create new objects. garbage collection algorithms vary from one JVM to another. then JVM stops the application and issues the "Out of memory error". There is no explicit allocation of memory in Java. For example. JVM's heap stores all objects created. 8 . the JVM will ask the operating system for more and if there is no more additional memory available from the operating system. It is a type of Memory Manager. If the free memory area is getting too small.7. - Java Virtual Machine Specification JVM Specification = Java programming language + Java Virtual Machine architecture + Java class-file format.

. s/w or h/w of a computer.exe. .0. 2. Today most of the web browser are java compatible.java-- - Xyz. Eave’s Dropping: Reading others data illegally Tampering: Not only reading other data but also modifying it. . Few of them are: Internet Explorer Netscape HotJava Firefox 1. 3.- Java Virtual Machine: JVM is also a part of the JRE. Interpreter 9 . Java Enabled browsers Java language is the most powerful language and is widely used in the web application. Impersonation: A person acting as another person on Internet. 4.4 Mozilla 1. first virus developed by Pakistan Virus spreads through .JVM made Java System Independent. 7. Virus: A program that can damage data. understanble by Pentium processor 210 byte code instruction are available JVM is system dependent JVM is different for different operating system . 6. 3 types of translators i.6 Security Problems on Internet 1.class-- JVM --PC Size of each instruction is 1 byte or 8 bits JVM can understand byte code instructions JVM is a program Converts byte code instructions into machine language instructions and gives to the microprocessor .class file is system dependent .com. and translating this into actions or operating system calls . 5. Xyz.dat . The Java Virtual Machine is responsible for interpreting Java bytecode.sis Virus cannot be carried by text file Translator is a program that converts any computer program into machine language.

8086.Macro Assemblers . Assembler s/w – Turbo Assemblers .8080. iii.obj (contains machine language instructionsof a source Run Xyz. Following figure shows the working of the Java compiler: 10 .8088. - Compiler Assembler Interpretor: Converts the program one line at a time into machine language Compiler: Converts all lines of the program at once atleast 10 times faster than the interpreter.exe (machine language instructions with a copy of all header files.ii.80286 Celeron –200 instructions Pentium 225 instructions Java Compiler A Java Compiler javac is a computer program or set of programs which translates java source code into java byte code. Assembler: Translates assembly language to machine language Mnemonics are used in assembly languge. First Microprocessor 4004.Micro Assemblers compile Xyz.c program) Xyz.

-

Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine.

Java Compiler When you run javac command on the command prompt, it shows the following output. C:\>javac Usage: javac <options> <source files> where possible options include: -g Generate all debugging info -g:none Generate no debugging info Generate only some debugging info

-g:{lines,vars,source} -nowarn -verbose -deprecation used

Generate no warnings Output messages about what the compiler is doing Output source locations where deprecated APIs are

-classpath <path> Specify where to find user class files and annotation processors -cp <path> annotation processors Specify where to find user class files and

11

-sourcepath <path> -bootclasspath <path> -extdirs <dirs> -endorseddirs <dirs>

Specify where to find input source files Override location of bootstrap class files Override location of installed extensions Override location of endorsed standards path

-proc:{none,only} Control whether annotation processing and/or compilation is done. -processor <class1>[,<class2>,<class3>...] Names of the annotation processors to run; bypasses default discovery process -processorpath <path> -d <directory> -s <directory> Specify where to find annotation processors Specify where to place generated class files Specify where to place generated source files

-implicit:{none,class} Specify whether or not to generate class files for implicitly referenced files -encoding <encoding> -source <release> release -target <release> -version -help -Akey[=value] -X -J<flag> C:\> Specify character encoding used by source files Provide source compatibility with specified

Generate class files for specific VM version Version information Print a synopsis of standard options Options to pass to annotation processors Print a synopsis of nonstandard options Pass <flag> directly to the runtime system

12

Java Interpreter
Java interpreter translates the Java bytecode into the code that can be understood by the Operating System. Once the class is loaded, java follows a C-like convention and searches for the class that contains a method called main(). If it finds an appropriate main() method, the interpreter starts the application by executing that method. From there, the application starts additional threads, reference other classes, and create its user interface. Java applet is a compiled Java code, the Java interpreter can't directly run them because they are used as part of a larger applications. For this we use Java Applet Viewer.

-

The Figure below shows the working of Java Interpreter:

Java Debugger Java debugger helps in finding and the fixing of bugs in Java language programs. The Java debugger is denoted as jdb. It works like a command-line debugger for Java classes.

13

Java Comments
These comments are advantageous in the sense that they make the programmer feel convenient to grasp the logic of the program. Although these comments are ignored by the Java compiler, To provide the additional information about the code, use comments.

There are three types of comments used in Java. These are: 1. Single LineComment //text: Comments are non executable statements 2. MultiLine Comment /*text*/: these comments have several lines as comment 3. Jav aDocumentation Comment /**text*/

Java Keywords
There are few keywords in Java programming language. Remember, we cannot use these keywords as identifiers in the program. The keywords const and goto are reserved though, they are not being currently used. The brief description of each one of the keyword is given below. abstract When a class is not to be instantiated, use abstract keyword but rather extended by other classes. This keyword is used in a method declaration to declare a method without providing the implementation. assert It is used to define an assert statement. Any boolean condition in a program is declared with the help of assert statement. The condition is checked at runtime if the program is running with assertions . If the condition is false, the Java runtime system throws an AssertionError. boolean This keyword is used to pertain to an expression or variable that can have only a true or falsevalue.

14

do Used to declare a loop that will iterate a block of statements. 15 . continue This keyword is used for the continuation of the program at the end of the current loop body. catch This keyword is used to handle the exceptions that occur in a program preceding try keyword. char This Java keyword is used to declare an expression. const This keyword has been deprecated from Java programming language. Case This keyword is used to defines a group of statements. enum Enumerations extend the base class Enum. Double A 64-bit floating point value. The value defined by the enclosing switch statement should match with the specified value. A Java keyword used to declare an expression. This keyword is used to declare an expression. method return value. method return value. default If the value defined by the enclosing switch statement does not match any value specified by a case keyword in the switch statement. method return value.This Java keyword is used to declare an enumeratedtype. else It is used to define a statement or block of statements that are executed in the case that the test condition specified by the if keyword evaluates to false. class This keyword is used to define the implementation of a particular kind of object. The loop will execute once before evaluating the exit condition. or variable of type byte. The loop's exit condition is specified with the while keyword. or variable of type double-precision floating point number. or variable of typecharacter.byte This is 8-bit integer.

extends keyword is used.647. All methods in a final class are implicitly final. It is also used in an interface declaration to specify one or more superinterfaces. However for wider range of values use long.648 to 2. final It is used to define an entity once that cannot be altered nor inherited later. strictfp To get the precise results in Floating point calculations use strictfp keyword regardless of any operating system and hardware platform. finally This keyword is used when the finally block is executed after the execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught. 8 bits = 1 Byte 1024 B = 1 KB 1024 KB = 1 MB 1024 MB = 1 GB 1024 GB = 1 TB Data is stored in the form of electric signals. Memory Description Information is stored in the floppy disks as Bytes.483. a final method cannot be overridden. If followed by a label. 16 .147.extends To specify the superclass in a class declaration.147. Byte is the basic measuring unit Byte represents binary digits called bits. the program resumes execution at the statement immediately following the enclosing labeled statement or block. It ranges from -2. int It is a 32-bit signed two's complement integer data type.483. Moreover. break Used to resume program execution at the statement immediately following the current enclosing block or statement. and a final variable can occur at most once as a left-hand expression. a final class cannot be subclassed. Java Data Types There are eight primitive data types which are supported by Java language programming which is predefined.

math. unsigned Unicode character.40129846432481707e-45 to 3. short It is a 16-bit signed two's complement integer. short is used to save memory in large arrays.767.768 to 32. Use a float (instead of double) to save memory in large arrays. float The float data type is a single-precision 32-bit IEEE 754 floating point. They are not same as ints.372.854. For that we have to use java.372.94065645841246544e-324d to 1. We do not use this data type for the exact values such as currency.036.775. This data type is generally the default choice for decimal values. We use this data type for conditional statements.854.808 to 9. double This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from -9.BigDecimal class. It ranges from 0 to 65.79769313486231570e+308d (positive or negative). shorts etc.036.535.40282346638528860e+38 (positive or negative). The following table shows the default values for the data types: Keyword Byte short Int Long Description Byte-length integer Short integer Integer Long integer Size/Format 8-bit two's complement 16-bit two's complement 32-bit two's complement 64-bit two's complement 17 .223.byte It is an 8-bit signed two's complement integer. It ranges from -32. We can also use byte instead of int to increase the limit of the code. boolean The boolean data type is 1-bit and has only two values: true and false.807. char The char data type is a single 16-bit. Use this data type with larger range of values. They are defined constants of the language.223. true and false are not the same as True and False. It ranges from 4. It ranges from 1. It ranges from -128 to127 (inclusive). long The long data type is a 64-bit signed two's complement integer.775. We can save memory in large arrays using byte.

The values of the variable can be changed anywhere in the program if the variable is accessible in that scope. hexadecimal or octal format. The values of the constant can't be changed once its declared An electronic device can understand 1.Presence of voltage 0. Constant and Literal in Java Variable : You can assign the values to the variable once it has been declared. Similarly put the characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal format.Absence of voltage Are the machine languge instructions Java Literals Integer Literals Integer literals is a sequence of digits and a suffix as L. 659L 0x4a 057L Decimal integer literal of type long integer Hexadecimal integer literal of type integer Octal integer literal of type long integer Character Literals 18 .Variable. To indicate a decimal format put the left most digit as nonzero. To represent the type as long integer we use L as a suffix.Float Double Char boolean Single-precision floating point Double-precision floating point A single character A boolean value (true or false) 32-bit IEEE 64-bit IEEE 16-bit Unicode character true or false Java . We can specify the integers either in decimal. Constants: Constants are declared using the final keyword.

the default type when you write a floating-point literal is double. or a nonprintable character as a character literal use an escape sequence. Escape \n \t \b \r \f \\ \' \" \d \xd \ud Meaning New line Tab Backspace Carriage return Formfeed Backslash Single quotation mark Double quotation mark Octal Hexadecimal Unicode character It is very interesting to know that if we want to specify a single quote.4 * 1038 +/.8 * 10308 Precision in decimal digits 6-7 15 19 . The letter d such as in the octal.3. and '3'. The syntax begins with a single backslash character. An escape sequence uses a special syntax to represents a character.1. BooleanLiterals The values true and false are also treated as literals in Java programming. The table below shows the codes that can represent these special characters. hex etc represents a number. a backslash.We can specify a character literal as a single printable character in a pair of single quote characters such as 'a'. Floating-pointliterals Floating-point numbers are like real numbers in mathematics. '#'. Type Size Name bytes bits Float 4 32 Double 8 64 Range approximate +/.

use null literal.5E+32 (or 6. however) Unary minus operator.e. the compiler will destroy it and the free memory will be allocated to the other object. The type of the null literal is always null. We represent string literals as String myString = "How are you?". + Unary plus operator. We typically assign null literals to object reference variables.5E32) 7D . rather it is an object. indicates positive value (numbers are positive without this. Double-precision floating-point literal Double-precision floating-point literal Floating-point literal Operators Operators are symbols that performs some operations on one or more than one operands. negates an expression ++ Increment operator. increments a value by 1 -. Now.Decrement operator. In this example an object is referenced by s. We reduce the number of references to an object by assigning null to s. 6. decrements a value by 1 20 . In Java a string is not a basic data type.The following floating-point literals represent double-precision floating-point and floating-point values. For instance s = null. Null Literals We specify the Null literal in the source code as 'null'.01f String Literals The string of characters is represented as String literals in Java. as in this example the object is no longer referenced so it will be available for the garbage collection i. To reduce the number of references to an object. SimpleAssignmentOperator = Simple assignment operator Arithmetic Operators + * / % Additive operator (also used for String concatenation) Subtraction operator Multiplication operator Division operator Remainder operator Unary Operators: An operator may act on a single operand.

1 Binary Number System . Ex: for 45 we ‘ll get 101101. inverts the value of a boolean Equality and Relational Operators = = Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Conditional Operators && Conditional-AND || Conditional-OR ?: Ternary (shorthand for if-then-else statement) Type Comparison Operator(To test whether an object belongs to a class) instanceof Compares an object to a specified type Ex: emp instanceof Employee Bitwise and Bit Shift Operators ~ Unary bitwise complement << Signed left shift >> Signed right sift >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR  Bitwise Operator: These operators acts upon individual bits of numbers .Convert 45 into binary.0. 0 0 1 0 1 1 0 1 0+0+32+0+8+4+0+=45  Bitwise Complement Operator(~):This operator shows the complement of a number int x=-5 x=10 ~x4 ~x-11  This operator perfoms anding operation individual bits of two numbers 21 .  Convert 0010 1101 into decimal Rule: Multiply the digits by the posers of 2 and take the sum of the products. Rule: Divide the no successively by 2 and takes the remainders from bottom to top.! Logical compliment operator.

X 0 0 1 1 Y 0 1 0 1 X&Y 0 0 0 1 Truth table is table showing the relationship between input and output X=10 Y=11 X+Y=?(output=10) 0000 1010 0000 1011 _________ 0000 1010 Bitwise or( | ): This operator performs oring operation on individual bits. X 0 0 1 1 Y 0 1 0 1 X&Y 0 1 1 1 X=10 Y=11 0000 1010 0000 1011 __________ X|Y=?(output=11) 0000 1011  Bitwise XOR(^): carot/circumflex This operator performs exclusive OR operation on individual bits X 0 0 1 1 Y 0 1 0 1 X&Y 0 1 1 0 X=10 Y=11 0000 1010 0000 1011 __________ X^Y=?(output=1) 0000 0001 22 .

println(“~x=:”+ (~x)). Bitwise Left Shift(<<): This operator shift the bits towards left a specified number of positions X=10 0 0 0 0 1 0 1 0 X<<2 0 0 1 0 1 0 0 0  Bitwise right shift(>>): This operator shifts the bit towards right a specified number X=10 0 X>>2 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0  Bitwise zero fill right shift(>>>) First bit specifies the sign bit 0 +ve and 1 –ve The sign bit is not protected class Bits { public static void main(String ar[]) { byte x.println(“x^y=:”+ (x^y)). } }  Note: Bit wise operators are used in embedded system programs The rule to deal with equal precedence operators is that all binary operators except for the assignment operators are evaluated from left to right.println(“x<<2=:”+ (x<<2)).out.y. System.out.out. System. System.println(“x&y=:”+ (x&y)). 23 .println(“x>>2=:”+ (x>>2)).println(“x|y=:”+ (x|y)). x=10. System. assignment operators are evaluated from right to left. System.out. y=11. System.out.out.

+expr. |=. ceil() This is the ceil() function which returns you the smallest value but greater than the argument. PI This is also a field of the Method class which returns you a default pi value. the base of the natural logarithms. --expr. All the functions have been explained below with example : E This is E field of the Math class which returns you a default exponent value that is closer than any other to e. -expr ~ ! */% +<< >> >>> < > . 24 . There is not necessary to import any package for the Math class because this is already in java. >>. <<=.. expr-++expr. &=.Operators Postfix Unary Multiplicative Additive Shift Relational Equality bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical OR Ternary Assignment Precedence expr++. %=. the ratio of the circumference of a circle to its diameter. >>=. >= instanceof == . *=. abs() This is the abs() function which returns you the absolute number. <= .lang package. exp() This is the exp() function which returns you the exponential value raised to the power of a double value. floor() This is the floor() function which returns you the largest value but less than the argument. >= Java . -=. != & ^ | && || ?: = . /=. ^=. +=.Math class in Java The Math class is used to operate the calculations.

. .One method is needed to execute a java program i. Package : package is a sub directory containing group of class/interface Java library(group of packageclass/interfacemethodsjava. sqrt() This is the sqrt() function which returns you the square root of the specified value.langString System. random() This is the random() function which returns you the random number. max() This is the max() function which distinguishes the maximum value from the two given value.void main(String args[]) 25 .IEEEremainder() This is the IEEEremainder() which returns you the remainder for the given dividend and divisor. round() This is the round() function which returns you a value that is in the rounded form.# include copies all lines of the header file into a C program Thus is waste the memory & processor time also.Amethod needs some variables. Import statement directs the JVM to go to the package execute the code come back & substitute the result in the java program. rint() This is the rint() function which returns you a value closest to the given value. It is absolutely system generated.e main() . pow() This is the pow() function which returns you the number raised to the power of a first given value by the another one.Variables are memory locations to store values . package) Differences between #include and import . min() This is the min() function which distinguishes the minimum value from the two given value.A method performs a task having a group of statements . } Block: A group of statements written inside left and right curly braces. class First { Block of statements. Import does not copy the libraries and #include copies.

.println(“welcome”).So to avoid this or to break the chain we use static methods. void doesn’t allow to return a value) argsvariable in which we can store one string Values passed to main method area called command Line arguments JVM always starts execution from main() method Two steps are used to call a method: 1.Static void main(String args[]) Public means the method is available outside our program to other program(JVM) If public is not written the main method is not available to JVM. className objname=new className(). Hello world (First java program) Java is a case sensitive programming language.A static method is a method that is called and executed without an object. 2. 26 .main() when we call the main() method the main method is executed so for calling we need an object and for getting obj we need to run main(). } } . Obj.out.main(). class Test { void main(String args[]) { Test t=new Test(). Ex: Test t=new Test().System. Then call the method using ObjectName. .We cannot create an object to print stream class . Create an object to the class to which that method belongs.methodname().Out is a static variable . .- void (no value is returned.out is a method provided by Java software .out is an object of PrintStream class that object takes the input and gives the output on monitor. System. t.System.

To run the program issue the following command on command prompt: C:\javatutorial\example>java HelloWorld You will see the following result on the command prompt.println("Hello World!"). Go to the directory where you have saved the file ( in our case C:\javatutorial\example>) and issue the following command to compile the program: C:\javatutorial\example>javac HelloWorld. The file name should be match the class name and to save the file give the . class HelloWorld { public static void main(String[] args) { System. In this example we have saved the file in the "C:\javatutorial\example" directory.java Once the compilation is successful a new file will be created with the name HelloWorld. Hello World! Here is the screen shot of the above steps: 27 . } } Save the file and Please remember the location where you save your file.class. e.For Example hello world !=(not equal to) Hello World Write the following code into your note pad to run the Hello World program .java program.java Now open the command prompt to compile the HelloWorld.g. HelloWorld.java extension.out.

28 . ‘IsSizeOf’ is an operator but not a keyword Java is case sensitive In java every statement should end with .class file & displays the output. ‘NULL’ is not a keyword. Then it will quit from memory Escape Sequences: \n  next line \t  horizontal tab space \r  enter button \b  backspace button \\  displays \ \”  displays “ \’  displays ‘ Important Note: - Variables passed in the method is called ‘parameters’ Values passed to those variables are called ‘arguments’ Assignment can be done many times Initialization can be done only once.- println(): displays the result in the next line and throws the cursor to the next line print() : displays the result and keeps the cursor in the same line and at the same position. It will execute the . To find the address of particular memory location in java by using ‘hashcode’ of the object class.

swing 3. linked lists.Hashtable and etc 3. java. java.awt.It consists of Wrapper classes(used for creating objects) 2.Checkbox are examples of components) 10.servlet: Servlets are server side programs which can communicate with several clients at a time. this package got primary classes and interfaces essential for Java language.util: This package contains useful classes and interfaces like stack. 5. java. MAX_VALUE Java.applet: Smallest package in java. java.and utilize them in java 9. namely java. readLine() 4.net: client-server programming can be done using this package. 8.empName. java.io. 6.It uses TCP/IP internally 7. javax. java.awt: This package helps to develop GUI. java. Ex: String . 11. Variable names: also follow the above rule Ex: age. then each word start with a capital Ex: println(). java.String Buffer 4.- For classname we should start with capital letters Naming Conventions start the class Name with capital letters which is a rule.Other packages must be imported  Important Packages of JAVA 1.image 5. Method Names: start with a small letter. javax. java. Constant Variables: should be written using capital letters Ex: PI.getchars().It consists of 2 important packages. Naming Conventions in Java 2.awt.rmi: (Remote Method Invocation) The objects which exist on one computer in network can be invoked from another computer and can be used.RadioButton. Applets are some intelligent programs that comes from server which travel from one place to another pace on ternet.awt.swing: This package helps to develop GUI like java. 29 .io: This package handles files and input-output related tasks. 4. javax. DataInputStream 2.event and java.beans: Beans are software reusable components (ex: PushButton.sql: This package helps to connect to database like oracle.lang: is a package that is imported into every program by default.lang: In this package most of the classes are final.awt. Each word of class names and interface names starts with capital letter 3. java. Package Names: In java are written in all small letters Ex: java.

The type of value stored by identifier is defined by the special java keyword is termed as primitive data type. . return) Selection . . Primitive Data Types Keyword Description Integers Byte Short Int Long Size/Format Byte-length integer Short integer Integer Long integer 8-bit two's complement 16-bit two's complement 32-bit two's complement 64-bit two's complement Real numbers Float Double Single-precision floating point Double-precision floating point 32-bit IEEE 754 64-bit IEEE 754 Other types Char boolean A single character 16-bit Unicode character A boolean value (true or false) true or false Controlling the program We can control the program flow by using statements like decisionmaking statements (if-then. the looping statements (for. switch).The statement following the if will only be executed when the boolean expression evaluates to true.That is the if statement in Java is a test of any boolean expression. if-then-else.This code gets executed if and only if the test evaluates to true. 30 . and the branching statements (break.Identifier and Primitive Data Types in java Identifier is a simple variable name which is defined as the value container. continue. while.Java . if-then else and switch statements The if statement . do-while).In this section we will learn how to use if-then.

For instance.out. .out. The switch statement in Java is the best way to test a single expression against a series of possible values and executing the code.out. else statement2. Here is the general form of switch statement: switch (expression){ case 1: code block1 case 2: code block2 .println("b is smaller"). The general form of the if else statement is: if (condition) statement1.println(“AAA”). The above format shows that an else statement will be executed whenever an if statement evaluates to false.if(condition) System. . int b = 40. if (a<b){ System.println("a is smaller"). class compare{ public static void main(String[] args){ int a = 20.This means it allows any number of possible execution paths.It depends on the value of a variable or expression. default: code default. } else{ d System. } } } The switch statement . } 31 .

println("sunday"). It tests the loop control variable against a target value and hence works as a loop terminator.break. . The comparison of the values of the expression with each of the constants occurs after the case statements.println("Invalid week").iteration : It is an expression that increments or decrements the loop control variable. .out.println("tuesday"). break. switch (week){ case 1: System.- The execution of the switch statement takes place by comparing the value of the expression with each of the constants. condition. break. It executes only once.e. } } } The for Statement .println("monday"). break. break. . Here is the form of the for loop: for(initialization. class Switch{ public static void main(String[] args){ int week = 5.out. Otherwise. case 5: System. condition. case 2: System. case 6: System.println("wednesday").out. } } } { 32 .out. case 4: System.println("friday"). and iteration.initialization : It is an expression that sets the value of the loop control variable.out. i++){ System. break. break.condition : This must be a boolean expression.println("saturday"). iteration){ //body of the loop } class printDemo { public static void main(String[] args) for (int i = 0.out.For statement consists of tree parts i. the statements after the default statement will be executed. case 3: System.println("Hello World!"). default: System.out.out.out. i<10. case 7: System. break. initialization.println("thursday").

out.println(). 2. class DoWhileDemo { public static void main (String args[]) 33 .out. yielding true or false. // Increment Loop Counter } System. // Say Hello int i = 0. It evaluates the condition in parentheses.print(args[i]). It continues to execute the next statement if the condition is false and exit the while statement. // Declare and initialize loop counter while (i < args. Secondly.out. For example: class Bonjour{ public static void main (String args[]){ System. i = i + 1.out.length){ // Test and Loop System. Lastly.The while and do-while Statements while (expression) { statement(s) } Lets see the flow of the execution of the while statement 1. If the condition is true it executes each of the statements between the brackets and then go back to step 1. // Finish the line } } do-while statement Here is the syntax: do { statement(s) } while (expression).print(" "). 3. Firstly.print("Bonjour "). System. in steps: while statement continually executes a block of statements while a particular condition is true.

println(i).out.out. Using jumping statements like break and continue it is easier to jump out of loops to control other areas of program flow. i = i + 1. - In the above example. a labeled break terminates an outer statement. // Say Bonjour System.print("Bonjour"). You saw the labeled form in the above example i. an unlabeled break statement terminates the innermost loop like switch.println(" ").} } { int i = 0. } } } } - The break statement has two forms: labeled and unlabeled. for. if (i==3) { break . // Increment LoopCounter } while (i < 5). However. while. do{ System. or do- 34 . it will enter the loop without checking the condition first and checks the condition after the execution of the statements. i++) { System. while and do-while loops is not always the right idea to use because they are cumbersome to read.out.e. That is it will execute the statement once and then it will evaluate the result according to the condition. i < 5. The break Statement We use break statement to terminate the loop once the condition gets satisfied. class BreakDemo { public static void main(String[] args) { for (int i = 0. Jumping Using for.

.print("*").while statement . j<=i.Now observe the example of unlabeled form below. We have used two loops here two print '*'. class BreaklabDemo1 { public static void main(String[] args) { for (int i = 0. j++) { System. if we haven't use break statement thus the loop will continue and it will give the output as shown below. for (int j = 0. 35 . if (j==5) { // break. } } } The continue statement .Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. In this example.out.out. i < 10.There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions. i++) { System.print("\n").

the first index value.i<10.Object so an array is an instance of Object. //control will never reach here (after the continue statement). Here the first element is refrenced by a[0] i.println("chandan"). try { for (int i=1. Arrays are always a fixed length abstracted data structure which can not be altered when required.out. //a = I.lang. System. } t.sleep(1000). int a = 0.i++) { if(i == 5) { continue. } } catch(InterruptedException e){} } } Introduction to Java Arrays The java array enables the user to store the values of the same type in contiguous memory allocations. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "n-1" indexed value. Each element is holding a distinct value. The Array class implicitly extends java.e. We have filled the 12 distinct values in the array each referenced as: 36 . Structure of Arrays Suppose an array contains "n" integers.public class Continue { public static void main(String[] args) { Thread t = new Thread(). System.out. Presume an array that contains 12 elements as shown in the figure.println("Value of a : " + a).

e..By array's name. Array Declaration . we mean that we can give any name to the array. int[][] matrix.a[0]=1 a[1]=2 .To represent the variable as an Array.. . however it should follow the predefined conventions. //declares an array of integers String[]names.Below are the examples which show how to declare an array :- int[]array_name. for example: int[] array_name = new int[5]. Memory is assigned to set the size of the declared array.These two brackets are used to hold the array of a variable.As we declare a variable in Java.. .By type we mean the type of elements contained in an array. . Here is an example that creates an array that has 5 elements. a[11]=12 The figure below shows the structure of an Array more precisely. //this is an array of arrays - It is essential to assign memory to an array when we declare it. . 37 . . a[n-1]=n . .Array variable has a type and a valid Java identifier i. we use [] notation. An Array variable is declared the same way. the array's type and the array's name..

The correct way to use the "new" operator is String names[].println(sum). names = new String[10]. for (int i = 0.out. we use the [] operator. i++) sum += x[i]. public class Sum { public static void main(String[] args) { int[] x = new int [101]. i<x. int sum = 0. } } Array Usage We have already discussed that to refer an element within an array. Here. System.length. i<x. the new operator is followed by the type of variable and the number of elements to be allocated. memory is allocated to it. In this example [] operator has been used to place the number of elements to be allocated. 38 . i++ ) x[i] = i. for(int i = 0. We also know that the array indices start with zero. Lets see a simple example of an array. For Example ://get the 5th month (May) int month = months[4]. The [] operator takes an "int" operand and returns the element at that index.length.public class Array { public { } } int[] a = new int[5]. so the first element will be held by the 0 index.After declaring an array variable. static void main(String[] args) Array Initialization . The "new" operator is used for the allocation of memory to the array object.

Multi-dimensional arrays A multi-dimensional array of dimension n is a collection of items. "May". "Dec"}. 39 . "Feb".length. Two-dimensional arrays Two-dimensional arrays are defined as "an array of arrays". "Nov". "Apr". "Sep". "July". the expression x[i][j] is used to select the element from that array. To process a two-dimensional array.length. i < months. "Jun". we use nested for loops. "Mar". "Aug". The first element of this array will be indexed with the "0" value and the last integer will be referenced by "length-1" indexed value. The command int[][] A = new int[3][4] declares a variable. There is no array assignment operator. - In this loop int i = 0.Example: String months[] = {"Jan". indicates that the loop starts from the 0th position of an array and goes upto the last position which is length-1. The expression x[i] is used to select the one-dimensional array.println("month: " + month[i]). indicates the length of the array and i++ is used for the increment in the value of i which is i = i+1. i++ ) { System. A. of type int[][]. and it initializes that variable to refer to a newly created object.out. //use the length attribute to get the number //of elements in an array for (int i = 0. int[][] x = new int[3][5]. "Oct". Since an array type is a firstclass Java type. i < months.

out. } OOPs and Its Concepts in Java Object Oriented Programming or OOP is the technique to create programs based on the real world. c<a2[r]. polymorphism etc. Objects are the basic unit of object orientation with behavior. and identity of objects present within that class. here in the OOP programming model programs are organized around objects and data rather than actions and logic. and identity. 40 . The class definition describes all the properties. Abstraction . Class – - Object – - Methods - Methods define the abilities of an object. instant methods and class variable and class methods.int[][] a2 = new int[10][5]. abstraction.length. r++) { for (int c=0.println("").length. Objects in programming language have certain behavior. inheritance.out. // print array in rectangular form for (int r=0. Inheritance – Acquiring the properties of one class to the other is called Inheritance. } System. An object is expressed by the variable and methods within the objects. encapsulation.The process of abstraction in Java is used to hide certain details and only show the essential features of the object. r<a2. method. behavior. type.print(" " + a2[r][c]). In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other. c++) { System. Again these variables and methods are distinguished from each other as instant variables. properties. A set of objects with common behavior. identity. OOPs in Java include class. these are part of a class but are not the same.

When we don't write any access modifier then default is considered. default : Its not a keyword. protected members are available outside the class. class ClassName { Declaration of variables. Four types of Access Specifiers can be found in Java namely… 1. Public: public members of a class are available outside the class 2. Access-specifier return-type function-name(argument-list) { block of statements. . fields and methods accessible within the package only. the public fields and the public methods can be accessed from anywhere. protected: This modifier makes a member of the class available to all classes in the same package and all sub classes of the class.e.Default members are available outside the class. public keyword specifies that the public class.Encapsulation – making a class and object as a single element. Protected: Members are same as public. Access Specifiers Access specifiers are used to Controlling Access to Members of a Class. Polymorphism . private fields and methods can be accessed only within the same class. Defaults:When no access specifier is used Java compiler uses default access specifier.It describes the ability of the object in belonging to different types with specific behavior of each type. 3. private: This keyword provides the accessibility only within a class i. It allows the class. Private:Represents private members are not available outside the class 4. Programming Structure: package . } public static void main(String[] args) 41 . Access Modifiers Access Modifiers : Access modifiers are used to specify the visibility and accessibility of a class.

r. breadth=6.Area().out. 4. } public void Area() { a=length*breadth.a.*. class Rectangle { int length. } } // Example for Second Function prototype import java.println("Area of a Rectangle="+a). A function with arguments and with return statement. } } Function Prototypes: There are 4 types of function prototypes are available in java 1.{ Instantiation(creating an object). A function with arguments and without return statement.Rect().*. r. } public static void main(String[] args) { Rectangle r=new Rectangle(). System. A function with out arguments and without return statement A function with out arguments and with return statement. class Rectangle { 42 . public void Rect() { length=10. breadth. 2. //syntax to create an object : //ClassName object=new ClassName().io.io. 3. // Example for first function prototype import java.

r.Rect(10. public void Rect(int l. breadth. } } // Example for Fourth Function Prototype 43 . } public static void main(String[] args) { Rectangle r=new Rectangle(). breadth=6. System.println("Area of a Rectangle=" +a).*. } public int Area() { return(length*breadth). System. } public void Area() { a=length*breadth. class Rectangle { int length.io.a. breadth=b.7). public void Rect() { length=10.println("Area of a Rectangle="+r.int length. r.Area().int b) { length=l. } public static void main(String[] args) { Rectangle r=new Rectangle(). r. breadth.Area()).out.Rect(). } } // Example for Third function prototype import java.out.

} } // Over Loading a Method import java. } public void Rect(int l. breadth. } public int Area() { return(length*breadth).println("Area of a Rectangle=" +r.io. breadth=b.int b) { length=l. class Rectangle { int length. breadth=3. breadth.io. } public void Rect(int l) { length=breadth=l. breadth=b.a. } public static void main(String[] args) { Rectangle r=new Rectangle(). public void Rect() { length=8.*. r.import java. System.7). } public int Area() 44 .out.int b) { length=l.*. public void Rect(int l.Rect(10.Area()).a. class Rectangle { int length.

out. But there are many difference between the method(function) and the Constructor. Constructors are not required to call into main function explicitly.Area()).out. System. } public static void main(String[] args) { Rectangle r=new Rectangle(). 4. Types of Constructors: 1.Area()). Default Constructors: A constructor with out any parameters/arguments Parameterized Constructor: A constructor with parameters Copy of Constructor: Overloading Constructor:With the same Constructor name but different signatures(parameters) // Example for Default Constructor import java. r.Rect(). Constructor is the method which name is same to the class.println("Area of a Rectangle=" +r.println("Area of a Rectangle=" +r.*. r. 2. r.{ return(length*breadth).4).Area()). which is used to initialize the instance variables of a class. Constructor initiates(initialize) something related to the class’s methods. System.println("Area of a Rectangle=" +r. Constructor does not return any values. class Rectangle 45 .io. } } Constructor: Constructor creates an instance for the class.Rect(5). System.out.Rect(9. 3.

} } //Another Example: 46 .int b) { length=l. } public int Area() { return(length*breadth). } public int Area() { return(length*breadth).io. public Rectangle() { length=8. } public static void main(String[] args) { Rectangle r1=new Rectangle(8. } public static void main(String[] args) { Rectangle r1=new Rectangle(). System.out. class Rectangle { int length. breadth=b.Area()). breadth.{ int length. System.out. breadth.println("Area of a Rectangle=" +r1.Area()).*. } } // Example for Parameterized Constructor import java.println("Area of a Rectangle=" +r1.3). public Rectangle(int l. breadth=3.

breadth.*. public Rectangle(int length. 47 .out. System. } } Note: “this” is used to invoke a constructor of the same class. breadth.println("Area of a Rectangle=" +r1. this. breadth=b. class Rectangle { int length.breadth=breadth. breadth=3. public Rectangle() { length=8. } public Rectangle(int l.io.int breadth) { this. // Overloading Constructor import java.io.*.a. } public Rectangle(int l) { length=breadth=l.a.Area()).int b) { length=l.3).import java. } public int Area() { return(length*breadth). } public static void main(String[] args) { Rectangle r1=new Rectangle(8. class Rectangle { int length.length=length.

that the car has four wheels . } } Inheritance Acquiring the properties of one class to the other class is called Inheritance It is the concept that is used for reusability purpose.println("Area of a Rectangle=" +r2.out.out. System.println("Area of a Rectangle=" +r1.out. System. If we think technically to this example then vehicle is the super class (or base class or parent class) and car is the subclass or child class - 48 . To derive a class in java the keyword extends is used. It concludes from the example that car is a specific word and vehicle is the general word.Area()).println("Area of a Rectangle=" +r3. } public static void main(String[] args) { Rectangle r1=new Rectangle().} public int Area() { return(length*breadth). But the word car makes a more specific image in mind than vehicle.Area()).3). System. Inheritance is the mechanism through which we can derived classes from other classes. Rectangle r3=new Rectangle(9. Rectangle r2=new Rectangle(8). The derived class is called as child class or the subclass or we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class.Area()). When we hear the word vehicle then we got an image in our mind that it moves from one place to another place it is used for traveling or carrying goods but the word vehicle does not specify whether it is two or three or four wheeler because it is a general word.

eg. return(0). a. In case of single inheritance there is only a sub class and it's parent class. int q){ x=p.out.6).println("B").out.println(x). int get(int p. int y.Show(). The following kinds of inheritance are there in java. } void display(){ System. } void Show(){ System. } } class B extends A{ public static void main(String args[]){ A a = new A(). Single Inheritance Multilevel Inheritance Pictorial Representation of Simple and Multilevel Inheritance Single Inheritance Single Inheritance Multilevel Inheritance When a subclass is derived simply from it's parent class then this mechanism is known as single inheritance.because every car has the features of it's parent (in this case vehicle) class.get(5. y=q. class A { int x. } } 49 . a.

println(x). int y.out. Multilevel inheritance can go up to any number of level.get(5.Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.println("B"). . class A { int x. a.Show(). It is used for two purposes in java. } } Multiple Inheritance . } void Show(){ System. } public static void main(String args[]){ A a = new A().Multilevel Inheritance . } } class B extends A{ void Showb(){ System.g.println("C"). return(0). e. 50 .out.out. e. Suppose class A is the super class that has two instance variables as int a and float b.The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. super keyword The super is java keyword.When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. y=q. int get(int p. . int q){ x=p. a. } } class C extends B{ void display(){ System. It is used to access the members of the super class. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class.g.6).

then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command. class A{ int a. Here parameter list is the list of the parameter requires by the constructor in the super class. super(param-list). float b.println("b in super class: System.Show().- class B is the subclass that also contains its own data members named a and b. float q){ a = p.member. 5). This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. B( int p. void Show(){ System. super.b). } - The second use of the keyword super in java is to call super class constructor in the subclass. " + super. 51 .println("a in sub class: } public static void main(String[] args){ B subobj = new B(1.out. System. subobj.Show(). super must be the first statement executed inside a super class constructor. " + a).println("b in super class: } } class B extends A{ int a.out. } " + b).out. This functionality can be achieved just by using the following command.b = q. } void Show(){ super. super. float b. Here member can either be an instance variable or a method.

An abstract method one that have the empty implementation. b.out. int m.out.8. All the methods in any interface are abstract by default. int q. System. int c.out.println("d = " + d).println("c = " + c).- If we want to call the default constructor then we pass the empty parameter list. c=r.7).println("a = " + a). A(int p.println("b = " + b). b=q. } public static void main(String args[]){ B b = new B(4.3. d=o. System. int r){ a=p. int o){ super(l. B(int l. class A{ int a.n). Abstract Class abstract classes are those that works only as the parent class or the base class. System. int n.m.g. int b.out.Show(). } } class B extends A{ int d. public abstract abs_value(). One can extend and implement to these methods in their own classes according to the requirements. } } Abstract methods and classes Abstract Method e. } void Show(){ System. 52 . Abstract method provides the standardization for the " name and signature" of any method.

} } Interface Interface is the way just to say something to a media by using another media. A class cannot be both ‘final’ and ‘abstract’. All the methods in an interface are "public and abstract" by default. An interface is the specification of the method prototypes. Interface is nothing but the collection of methods with empty implementations and constants variables ( variables with static and final declarations ). Abstract classes are not instantiated directly. Since interfaces are abstract in nature so they cannot be directly instantiated. Abstract classes are generic in nature and implement to those methods that are used commonly by the subclasses with common implementation. All the abstract methods of abstract class should be implemented(body) in the subclass If any one abstract method is not implemented . First extend the base class and then instantiate (create objects).- Subclasses are derived to implement the methods inherited from the abstract class (base class). void show(){ System. No method body in interface. then that subclass should be declared as ‘abstract’. e. An interface contains all abstract methods. 53 . We can create an object to implementation class. Implementation class is a class where all the methods of an interface are implemented.g. Interfaces are similar to abstract classes but the major difference between these two is that interface have all the methods abstract while in case of abstract classes must have at least one abstract method. One single interface can have several implementation class. An abstract class should be declared with ‘abstract’ keyword.println("This is an abstract class"). To define the methods of an interface the keyword "implements" is used. We cannot create object to interface. abstract class A{ public abstract abs_value().out.

Example: TV Remote is the interface because it is the medium to give the command to a TV in order to change the channels or to ON/OFF the TV. Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class. public void changegear (int Obj). then a call to the method clone() on Myclass's object will give an error. Electric switch is also the interface's example. e.Marker Interfaces are implemented by the classes or their super classes in order to add some functionality. . public void stopcar (int Obj). public interface RacingCar{ public void startcar (int Obj). Interface Definition visibility mode interface interfaceName{ constant variable declarations abstract method declarations } e. public void incrrace (int Obj).Interfaces with no methods are known as marker interfaces. Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error.g. - - Difference between Interfaces and abstract classes 54 . to add this functionality one should implement the Clonable interface. Marker interfaces are Serializable. Event listener. While the Clonable is an empty interface but it provides an important functionality. This means. Clonable.g. } Marker Interface . SingleThreadModel.

String Handling Strings: A string represents a group of characters Note : String is a class in java. String str=new String(ch). (by implementing more than one interface at a time) Additional Functions If we add a method to anIn Abstract classes we can add a method interface then we will have towith default implementation and then we implement this interface by anycan use it by extending the abstract class.Internally JVM creates object 2. instance as well as static variables. The variables in interfaces areAbstract classes may contain both final and static. we can create a string by directly assigning a string literal to a string object Ex: String str=”Hello”. We can create a string class object using new operator Ex: String str=new String(“hello”)..lang package Creating a string: 1. Variables Multiple In java multiple inheritance isAbstract classes does not provide this Inheritance achieved by using the interfacefunctionality. Object: allocating memory to store data. We can convert a character array into String class object Ex: char ch[]={‘H’. 3.’o’}.’l’.Features Methods Interface Abstract Class An interface contains all theAn abstract class must have at least one methods with emptymethod with empty implementation. implementation. class.’e’.’l’. 55 .

n<0 if s1<s2 StringBuffer class in Java StringBuffer is mainly used for the dynamic string concatenation which enhances the performance. There are some functions used in the given example. char charAt(int index): returns the character at the specified location(from 0) 4. 2. append() This is the append() function used for the concatenate the string in string buffer. 3. n==0 if s1==s2. n>0 if s1>s2.concat receives one string object and returns string. String concat(String str) Concatenates the calling string with str.1. int length (): length gives no of characters in a string returns the length of a string String s1=”Hydera”. or 0 if the strings are equal Ex: String s1=”apple”. reverse() This is the reverse() function used to reverse the string present in string buffer.String str=new String(ch.String: 1. but can be modified. Java. String s2=”bad”. String s2=”grapes”. At any point of time it contains some particular sequence of characters. int compareTo(String str):returns a negative value if the string comes before string in dictionary order. but the length and content of the sequence can be changed through certain method calls. A string buffer is like a String. a positive value. insert() This is the insert() function used to insert any string or character at the specified position in the given string. Int n=s1. Note: + will do the same. int n=s1.length(). Ex: String s1=”Hydera”. String x=s1. A string buffer implements a mutable sequence of characters.lang.3). This is better to use for dynamic string concatenation. if the string comes after str. setCharAt() 56 .concat(s2).compareTo(s2).

io.append(str).*. System. String str. System. System. deleteCharAt() This is the deleteCharAt() function which is used to delete the specific character from the buffered string by mentioning that's position in the string. public class stringBuffer{ public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System. This is the example of SringBuffer class and it's functions.out. System. strbuf.append("Hello").println(strbuf).in)). System. strbuf.out. delete() This is the delete() function is used to delete multiple character at once from n position to m position (n and m are will be fixed by you.insert(5.println(strbuf).append("World").delete(0. //Create a object of StringBuffer class StringBuffer strbuf = new StringBuffer(). charAt() This is the charAt() function which is used to get the character at the specified position of the given string.str.print("Reversed string : "). import java.out.readLine().out.length()).print("Enter your name: "). str = in.out. //print HelloWorld //print Hello_Java World //reverse() strbuf. try{ System. strbuf.reverse(). substring() This is the substring() function which is used to get the sub string from the buffered string from the initial position to end position (these are fixed by you in the program). //print dlroW avaJ_olleH 57 .This is the setCharAt() function which is used to set the specified character in buffered string at the specified position of the string in which you have to set the given character.) in the buffered string.".out.println(strbuf)."_Java ").println(strbuf). //append() strbuf. length() This is the length() function is used to finding the length of the buffered string. str += ". //insert() strbuf. capacity() This is the capacity() function is used to know about the current characters kept which is displayed like : number of characters + 6.

length()). The following methods have been used in this program.out.setCharAt(5. else false. //print lo J //deleteCharAt() strbuf. //print Hello_Java World //prit Hello Java World //charAt() System.println(strbuf.out.out.println(e.println(strbuf).strbuf.print("Substring from position 3 to 6 : ").charAt(6)).delete(6.capacity()). //print 21 //delete() and length() strbuf. System.' '). //print J //substring() System.getMessage()).println(strbuf. 58 . System. } } } catch(StringIndexOutOfBoundsException e){ System. countTokens(): It gives the number of tokens remaining in the string. //setCharAt() strbuf.deleteCharAt(3).println(strbuf.out. In the program a string is passed into a constructor of StringTokenizer class. //print Helo java World //capacity() System.out.util. We are using while loop to generate tokens. System.println(strbuf). System.out.strbuf.out. System. System.reverse().println(strbuf).7)).print("Character at 6th position : "). System. } //no anything Making Tokens of a String Tokens can be used where we want to break an application into tokens.println(strbuf).substring(3. We have to break a String into tokens as well as we will know how many tokens has been generated.package. hasMoreTokens(): It gives true if more tokens are available.print("Capacity of StringBuffer object : ").out.out.out. nextToken(): It gives the next token available in the string.out. StringTokenizer is a class in java.

countTokens()). The following program construct a string buffer that has '0' capacity.out.- To break a string into tokens what we need first is to create a class named StringTokenizing.hasMoreTokens()){ System. This constructor constructs a string buffer that have no characters. By using the instance of StringTokenizer call the method countTokens() which gives the number of tokens remaining in the string. It takes following parameters: 59 . It is a method of StringTokenizer class.util. This program inserts the data in the string buffer using the insert() method that provides the facility for adding the data in any positions. String str): This method inserts the string into the object of StringBuffer. } } } - The StringBuffer is a class that implements multiple sequence of characters. public class StringTokenizing{ public static void main(String[] args) { StringTokenizer stringTokenizer = new StringTokenizer("You are tokenizing a string").out. If the object have more tokens available then it will call method hasMoreTokens() and print the tokens by using nextToken(). insert(int pos. Description of code: StringBuffer(int len): This is the constructor of StringBuffer class that implements multiple sequence of characters. This method inserts always last or end position.println("The total no.nextToken()). of tokens generated : " + stringTokenizer. System. Make an object of class StringTokenizer and pass one string inside the constructor which you want to break into tokens. The code of the program is given below: import java. while(stringTokenizer. But the append() method also add data in string buffer in ending position.println(stringTokenizer.*. Inside this class we will declare our main method. It takes initial capacity that have to initialized.

out. String s[]=new String[num].out."). "Raj")).append("Mohit")). //Always last System. i++) { System.println("Argument " + (i + 1) + " = " + args[i]).println(sb. //last position System. //First position System.out.println(sb.pos: This is the position that have to be used for inserting the data.lang. int len = sb. for (int i = 0. str: This is the string that have to inserted. If user forget enter string at run time on command line argument then the message "No values has been entered at the command line" will displayed on screen. } } else{ System.length(). append(String str): This is the method that inserts the string into string buffer.println(sb. i <num .println("No values has been entered at the command line.out.println("The values enter at argument command line are:"). Show these strings on console as output. Store these strings into an array string.insert(len.out.out. It always inserts a string at last position.insert(6. public class ArgumentPassingExample{ public static void main(String[] args){ int num=args. public class AppendInsert{ public static void main(String[] args) { System.out.length. } }} 60 .*. StringBuffer sb = new StringBuffer(0). "Deepak")). } } Passing Command Line Arguments Sequence of character from command line at run time. Here is the code of program import java. if(num>0){ System. //Six position System.out.println(sb. "vinod")).insert(0.println("StringBuffer insert and append example!").

and communicate aggregate data Collection Framework A collections framework is a unified architecture for representing and manipulating collections. 2. manipulate. retrieve. Interfaces allow collections to be manipulated independently of the details of their representation Implementations: These are the concrete implementations of the collection interfaces. algorithms. retrieve.Util Packages: A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. The Collections Framework consists of three parts 1. All implementations are serializable and cloneable 3. In essence. they are reusable data structures. interfaces. the predefined actions that can be defined on either the interfaces or their implementations. the concrete versions of these interfaces. 3. the abstract data types that the framework supports. manipulate. A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. All collections frameworks contain the following: Interfaces: These are abstract data types that represent collections. All implementations are unsynchronized. 2. and communicate aggregate data. implementations. Collections are used to store. Collections are used to store. The predefined algorithms for supporting the framework are found in the Collections and Arrays classes Interface type and its implementation 61 . 1. All implementations support having null elements.

In essence. The algorithms are said to be polymorphic: that is.Interface Type Set SortedSet List Queue Map SortedMap Implemented by HashSet. the same method can be used on many different implementations of the appropriate collection interface. LinkedHashSet. 62 . • Algorithms: These are the methods that perform useful computations. In essence. Stack. algorithms are reusable functionality. • The core collection interfaces encapsulate: These interfaces allow collections to be manipulated independently of the details of their representation. As you can see in the following figure. such as searching and sorting. on objects that implement collection interfaces. they are reusable data structures. the core collection interfaces form a hierarchy. LinkedHashMap. IdentityHashMap TreeMap What Is a Collections Framework? A collections framework is a unified architecture for representing and manipulating collections. HashMap. Interfaces allow collections to be manipulated independently of the details of their representation. EnumSet TreeSet Vector. All collections frameworks contain the following: Interfaces: These are abstract data types that represent collections. LinkedList Hashtable. LinkedList PriorityQueue. • Implementations: These are the concrete implementations of the collection interfaces. WeakHashMap. ArrayList.

63 . In a FIFO queue. and others do not. such as the courses making up a student's schedule. Some are ordered and others are unordered. Lists can contain duplicate elements. first-out) manner. This interface models the mathematical set abstraction and is used to represent sets. List Queue — a collection used to hold multiple elements prior to processing. Set — a collection that cannot contain duplicate elements. but do not necessarily. - — an ordered collection (sometimes called a sequence). such as Set and List. or the processes running on a machine. Note also that the hierarchy consists of two distinct trees — a Map is not a true Collection. A SortedSet is a special kind of Set. all new elements are inserted at the tail of the queue. Besides basic Collection operations. Some types of collections allow duplicate elements. order elements in a FIFO (firstin. The following list describes the core collection interfaces: • Collection — A collection represents a group of objects known as its elements.The core collection interfaces. extraction. each key can map to at most one value. Map — an object that maps keys to values. A Set is a special kind of Collection. Queues typically. A Map cannot contain duplicate keys. and inspection operations. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces. a Queue provides additional insertion.

Several additional operations are provided to take advantage of the ordering. a Set. //optional void clear(). //optional boolean removeAll(Collection<?> c).SortedSet — a Set that maintains its elements in ascending order. 64 . Sorted sets are used for naturally ordered sets. boolean add(E element). <T> T[] toArray(T[] a). which may be a List. //optional Iterator<E> iterator(). such as dictionaries and telephone directories. This idiom creates a new ArrayList (an implementation of the List interface). that you have a Collection<String> c. boolean isEmpty(). //optional boolean retainAll(Collection<?> c). public interface Collection<E> extends Iterable<E> { // Basic operations int size(). The following shows the Collection interface. SortedMap — a Map that maintains its mappings in ascending key order. initially containing all the elements in c. or another kind of Collection. List<String> list = new ArrayList<String>(c). The Collection Interface A Collection represents a group of objects known as its elements. Sorted maps are used for naturally ordered collections of key/value pairs. } - The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. The Collection interface is used to pass around collections of objects where maximum generality is desired. // Bulk operations boolean containsAll(Collection<?> c). boolean addAll(Collection<? extends E> c). boolean contains(Object element). //optional // Array operations Object[] toArray(). Example. //optional boolean remove(Object element).

65 . E next().println(o). The remove method removes the last element that was returned by next from the underlying Collection. Therefore. and the next method returns the next element in the iteration. the for-each construct is not usable for filtering.out. //optional } The hasNext method returns true if the iteration has more elements.It guarantees that the Collection will contain the specified element after the call completes. void remove(). Iterator. Traversing Collections There are two ways to traverse collections: (1) with the for-each construct and (2) by using Iterators. Use Iterator instead of the for-each construct when you need to: Remove the current element. assuming that it contains the element to start with. and to return true if the Collection was modified as a result. the remove method is designed to remove a single instance of the specified element from the Collection. Similarly. The for-each construct hides the iterator. and returns true if the Collection changes as a result of the call. so you cannot call remove. Collection Interface Array Operations The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. for-each Construct The for-each construct allows you to concisely traverse a collection or array using a for loop — for (Object o : collection) System. Iterators An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively.remove is the only safe way to modify a collection during iteration. public interface Iterator<E> { boolean hasNext().

For example. boolean contains(Object element). The simple form with no arguments creates a new array of Object.toArray(new String[0]). //optional void clear(). // Bulk operations boolean containsAll(Collection<?> c). boolean addAll(Collection<? extends E> c). String[] a = c. The following is the Set interface. //optional Iterator<E> iterator(). TreeSet. public interface Set<E> extends Collection<E> { // Basic operations int size(). //optional boolean remove(Object element). The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c. The Set Interface A Set is a Collection that contain duplicate elements. It models the mathematical set abstraction. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c. //optional boolean retainAll(Collection<?> c). <T> T[] toArray(T[] a). suppose that c is a Collection. } The Java platform contains three general-purpose Set implementations: HashSet. //optional boolean removeAll(Collection<?> c). //optional // Array Operations Object[] toArray(). Suppose that c is known to contain only strings (perhaps because c is of type Collection<String>). boolean add(E element). Object[] a = c. The Set interface contains only methods inherited from Collection and instances are equal if they contain the same elements.The array operations allow the contents of a Collection to be translated into an array. boolean isEmpty().toArray(). 66 . and LinkedHashSet.

public class FindDups { public static void main(String[] args) { Set<String> s = new HashSet<String>().) • s1. The iterator method returns an Iterator over the Set. orders its elements based on their values. LinkedHashSet. (s2 is a subset of s1 if set s1 contains all of the elements in s2.) • s1. it is substantially slower than HashSet.containsAll(s2) — returns true if s2 is a subset of s1. they perform standard set-algebraic operations. the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2. which is implemented as a hash table with a linked list running through it. Here's what bulk operations do: s1. (For example. Collection<Type> noDups = new LinkedHashSet<Type>(c).println(s. (The intersection of two sets is the set containing only the elements common to both sets. which stores its elements in a hash table.add(a)) System. } } Set Interface Bulk Operations Bulk operations are particularly well suited to Sets.) 67 .out. (The • union of two sets is the set containing all of the elements contained in either set.addAll(s2) — transforms s1 into the union of s1 and s2. TreeSet. Suppose s1 and s2 are sets. for (String a : args) if (!s. The add method adds the specified element to the Set if it's not already present and returns a boolean indicating whether the element was added.*.) • s1.HashSet.println("Duplicate detected: " + a).retainAll(s2) — transforms s1 into the intersection of s1 and s2. the remove method removes the specified element from the Set if it's present and returns a boolean indicating whether the element was present. Similarly. Set Interface Basic Operations The size operation returns the number of elements in the Set (its cardinality). import java. when applied. however it makes no guarantees concerning the order of iteration. System.util.size() + " distinct words: " + s).out.removeAll(s2) — transforms s1 into the (asymmetric) set difference of s1 and s2.

for (String a : args) if (!uniques.out. System. public class FindDups2 { public static void main(String[] args) { Set<String> uniques = new HashSet<String>(). It includes operations for the following: • Positional access — manipulates elements based on their numerical position in the list • Search — searches for a specified object in the list and returns its numerical position • Iteration — extends Iterator semantics to take advantage of the list's sequential nature • Range-view — performs arbitrary range operations on the list.println("Unique words: " + uniques). //optional void add(int index. public interface List<E> extends Collection<E> { // Positional access E get(int index).add(a)) dups. Collection<? extends E> c).println("Duplicate words: " + dups). //optional boolean addAll(int index. //optional // Search 68 .import java. } } The List Interface A List is an ordered Collection (sometimes called a sequence).removeAll(dups). System. //optional E remove(int index). Lists may contain duplicate elements. E element). Set<String> dups = new HashSet<String>().out.util. // Destructive set-difference uniques.add(a).*. The List interface follows. E element). //optional boolean add(E element). E set(int index.

insertElementAt. List<Type> list3 = new ArrayList<Type>(list1). The add and addAll operations always append the new element(s) to the end of the list. } The Java platform contains two general-purpose List implementations. Like the Set interface.addAll(list2). Note that the idiom. Here's a nondestructive form of this idiom. and removeElementAt) with one 69 . and LinkedList which offers better performance under certain circumstances. add and remove) behave just like their longer-named counterparts in Vector (elementAt. which is usually the better-performing implementation. now would be a good time to read The Collection Interface section. list1.addAll(list2). which produces a third List consisting of the second list appended to the first. int lastIndexOf(Object o). List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. // Iteration ListIterator<E> listIterator().int indexOf(Object o). Two List objects are equal if they contain the same elements in the same order. setElementAt. Also. Positional Access and Search Operations The basic positional access operations (get. // Range-view List<E> subList(int from. Vector has been retrofitted to implement List. ArrayList. Thus. set. int to). If you're not familiar with them from Collection. takes advantage of ArrayList's standard conversion constructor. the following idiom concatenates one list to another. The remove operation always removes the first occurrence of the specified element from the list. Collection Operations The operations inherited from Collection all do about what you'd expect them to do. in its nondestructive form. list3. ListIterator<E> listIterator(int index). assuming you're already familiar with them.

the Vector counterparts (setElementAt and removeElementAt) return nothing (void).shuffle(list. It's a bit subtle: It runs up the list from the bottom. randomly permutes the specified list using the specified source of randomness.out. import java. It should look familiar from Programming 101. tmp). } } 70 . This is a polymorphic algorithm: It swaps two elements in any List.set(i. i--) swap(list. for (String a : args) list. public class Shuffle { public static void main(String[] args) { List<String> list = new ArrayList<String>(). Here's a little method to swap two indexed values in a List. regardless of its implementation type. The elements are inserted in the order they are returned by the specified Collection's iterator. a.nextInt(i)).add(a). The search operations indexOf and lastIndexOf behave exactly like the identically named operations in Vector. Collections. i .get(j)). there's one big difference. The following program uses this algorithm to print the words in its argument list in random order.size()-1 swaps).size(). which is included in the Java platform's Collections class. assuming an unbiased source of randomness) and fast (requiring exactly list. System. int i. int j) { E tmp = a. Random rnd) { for (int i = list. The addAll operation inserts all the elements of the specified Collection starting at the specified position. public static <E> void swap(List<E> a. new Random()).set(j. Unlike most naive attempts at shuffling. a. repeatedly swapping a randomly selected element into the current position. } Of course.get(i).util.1. } This algorithm. a. rnd.println(list). This call is the positional access analog of Collection's addAll operation.*. Here's another polymorphic algorithm that uses the preceding swap method. public static void shuffle(List<?> list.noteworthy exception: The set and remove operations return the old value that is being overwritten or removed. it's fair (all permutations occur with equal likelihood. i > 1.

util. Here's the standard idiom for iterating backward through a list.shuffle(list).listIterator(list. the Iterator returned by List's iterator operation returns the elements of the list in proper sequence. System. which uses a default source of randomness. whereas the latter refer to the element after the cursor. //optional void add(E e). The resulting List is not a general-purpose List implementation. boolean hasPrevious().println(list). because it doesn't implement the (optional) add and remove operations: Arrays are not resizable. The former operations refer to the element before the (implicit) cursor. public interface ListIterator<E> extends Iterator<E> { boolean hasNext().asList and calling the library version of shuffle. The Arrays class has a static factory method called asList. List also provides a richer iterator.*. } } Iterators As you'd expect. for (ListIterator<Type> it = list. The previous operation moves the cursor backward.In fact. //optional void set(E e). Taking advantage of Arrays. E next(). //optional } The three methods that ListIterator inherits from Iterator (hasNext. Changes in the List write through to the array and vice versa. modify the list during iteration. whereas next moves it forward.asList(args). Collections. called a ListIterator. and remove) do exactly the same thing in both interfaces. next. int nextIndex().size()). import java. This method does not copy the array. E previous(). 71 . public class Shuffle { public static void main(String[] args) { List<String> list = Arrays. int previousIndex().out. you get the following tiny program whose behavior is identical to the previous program. and obtain the current position of the iterator. which allows you to traverse the list in either direction. which allows an array to be viewed as a List. The ListIterator interface follows. void remove(). this program can be made even shorter and faster. The hasPrevious and the previous operations are exact analogues of hasNext and next.

size(). the following is a possible implementation of List. the first call to next after a sequence of calls to previous returns the same element as the last call to previous. Intuitively speaking. Calls to next and previous can be intermixed. It should come as no surprise that the nextIndex method returns the index of the element that would be returned by a subsequent call to next. An initial call to previous would return the element whose index was index-1. ) { Type t = it. The five possible cursor positions..} it. and previousIndex returns the index of the element that would be returned by a subsequent call to previous. 72 . This implies the behavior of the two boundary cases: (1) a call to previousIndex when the cursor is before the initial element returns -1 and (2) a call to nextIndex when the cursor is after the final element returns list. Note the argument to listIterator in the preceding idiom. The List interface has two forms of the listIterator method. To make all this concrete. but you have to be a bit careful. In a list of length n. .hasPrevious(). from 0 to n.. The following figure shows the five possible cursor positions in a list containing four elements. These calls are typically used either to report the position where something was found or to record the position of the ListIterator so that another ListIterator with identical position can be created. there are n+1 valid values for index. Similarly. The index refers to the element that would be returned by an initial call to next. The first call to previous returns the same element as the last call to next. The n+1 valid index values correspond to the n+1 gaps between elements. the cursor is always between two elements — the one that would be returned by a call to previous and the one that would be returned by a call to next. The form with no arguments returns a ListIterator positioned at the beginning of the list.previous(). inclusive.indexOf. It should also come as no surprise that the number returned by nextIndex is always one greater than the number returned by previousIndex. from the gap before the first element to the gap after the last one. the form with an int argument returns a ListIterator positioned at the specified index.

E val. for (E e : newVals) it. The set method overwrites the last element returned by next or previous with the specified element. The following polymorphic algorithm uses set to replace all occurrences of one specified value with another.public int indexOf(E e) { for (ListIterator<E> it = listIterator(). ) if (val == null ? it. } The only bit of trickiness in this example is the equality test between val and it. This method is illustrated in the following polymorphic algorithm to replace all occurrences of a specified value with the sequence of values contained in the specified list. it.previousIndex(). this operation removes the last element returned by next or previous.next() == null : val.hasNext().equals(it.hasNext(). You need to special-case a val value of null to prevent a NullPointerException.add(e).remove().next() == null : val.equals(it. it. E val. // Element not found } Note that the indexOf method returns it.hasNext().equals(it. The ListIterator interface provides two additional operations to modify the list — set and add. The reason is that it. E newVal) { for (ListIterator<E> it = list.listIterator(). The add method inserts a new element into the list immediately before the current cursor position. public static <E> void replace(List<E> list. ){ if (val == null ? it. For ListIterator.next())) { it.next())) return it.next() == null : e.listIterator(). it.next())) it. List<? extends E> newVals) { for (ListIterator<E> it = list. return -1.previousIndex() even though it is traversing the list in the forward direction.set(newVal). The Iterator interface provides the remove operation to remove the last element returned by next from the Collection.nextIndex() would return the index of the element we are about to examine. ) if (e == null ? it. } 73 . and we want to return the index of the element we just examined. public static <E> void replace(List<E> list.next.

works with the List returned by subList. Any operation that expects a List can be used as a range operation by passing a subList view instead of a whole List.subList(fromIndex.. List<E> hand = new ArrayList<E>(handView). it returns a new List (the "hand") containing the specified number of elements taken from the end of the specified List (the "deck"). list. } As the term view implies. so changes in the former are reflected in the latter. int n) { int deckSize = deck.} } Range-View Operation The range-view operation. This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). int toIndex).clear(). toIndex). The elements returned in the hand are removed from the deck. the returned List is backed up by the List on which subList was called. return hand.subList(fromIndex. such as the replace and shuffle examples. handView.lastIndexOf(o). Note that the preceding idioms return the index of the found element in the subList. i < toIndex. for (int i = fromIndex. That is.clear(). toIndex). Any polymorphic algorithm that operates on a List. toIndex). i++) { . public static <E> List<E> dealHand(List<E> deck. to toIndex. List<E> handView = deck. int j = list. int i = list. subList(int fromIndex.. For example. Similar idioms can be constructed to search for an element in a range. Here's a polymorphic algorithm whose implementation uses subList to deal a hand from a deck. deckSize).subList(deckSize .n. inclusive.subList(fromIndex. exclusive. returns a List view of the portion of this list whose indices range from fromIndex. This half-open range mirrors the typical for loop.size(). not the index in the backing List.indexOf(o). the following idiom removes a range of elements from a List. } 74 .

Note that this algorithm removes the hand from the end of the deck. For many common List implementations, such as ArrayList, the performance of removing elements from the end of the list is substantially better than that of removing elements from the beginning. The following is a program that uses the dealHand method in combination with Collections.shuffle to generate hands from a normal 52-card deck. The program takes two command-line arguments: (1) the number of hands to deal and (2) the number of cards in each hand.
import java.util.*; class Deal { public static void main(String[] args) { int numHands = Integer.parseInt(args[0]); int cardsPerHand = Integer.parseInt(args[1]); // Make a normal 52-card deck. String[] suit = new String[] {"spades", "hearts", "diamonds", "clubs"}; String[] rank = new String[] {"ace","2","3","4","5","6","7","8", "9","10","jack","queen","king"}; List<String> deck = new ArrayList<String>(); for (int i = 0; i < suit.length; i++) for (int j = 0; j < rank.length; j++) deck.add(rank[j] + " of " + suit[i]); Collections.shuffle(deck); for (int i=0; i < numHands; i++) System.out.println(dealHand(deck, cardsPerHand)); } }

Running the program produces the following output.
% java Deal 4 5 [8 of hearts, jack of spades, 3 of spades, 4 of spades, king of diamonds] [4 of diamonds, ace of clubs, 6 of clubs, jack of hearts, queen of hearts] [7 of spades, 5 of spades, 2 of diamonds, queen of diamonds, 9 of clubs] [8 of spades, 6 of diamonds, ace of spades, 3 of hearts, ace of hearts]

Although the subList operation is extremely powerful, some care must be exercised when using it. The semantics of the List returned by subList become undefined if elements are added to or removed from the backing List in 75

any way other than via the returned List. Thus, it's highly recommended that you use the List returned by subList only as a transient object — to perform one or a sequence of range operations on the backing List. The longer you use the subList instance, the greater the probability that you'll compromise it by modifying the backing List directly or through another subList object. Note that it is legal to modify a sublist of a sublist and to continue using the original sublist (though not concurrently).

List Algorithms
Most polymorphic algorithms in the Collections class apply specifically to List. Having all these algorithms at your disposal makes it very easy to manipulate lists. Here's a summary of these algorithms, which are described in more detail in the Algorithms section. — sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.) • shuffle — randomly permutes the elements in a List. • reverse — reverses the order of the elements in a List. • rotate — rotates all the elements in a List by a specified distance. • swap — swaps the elements at specified positions in a List. • replaceAll — replaces all occurrences of one specified value with another. • fill — overwrites every element in a List with the specified value. • copy — copies the source List into the destination List. • binarySearch — searches for an element in an ordered List using the binary search algorithm. • indexOfSubList — returns the index of the first sublist of one List that is equal to another. • lastIndexOfSubList — returns the index of the last sublist of one List that is equal to another.
• sort

1. An array is a named set of same-type variables. 2. Each variable in the array is called an array element. 3. The first element will have an index of 0.
public class MainClass { public static void main(String[] arg) { int[] intArray = new int[10]; for (int i = 0; i < 10; i++) { intArray[i] = 100;

76

} for (int i = 0; i < 10; i++) { System.out.println(intArray[i]); } } }

Exception in Java
Exception are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language. Occurrence of any kind of exception in java applications may result in an abrupt termination of the JVM or simply the JVM crashes which leaves the user unaware of the causes of such anomalous conditions.

Exception Object
In java, when any kind of abnormal conditions occurs with in a method then the exceptions are thrown in the form of Exception Object i.e. the normal program control flow is stopped and an exception object is created to handle that exceptional condition. The method creates an object and hands it over to the runtime system. Basically, all the information about the error or any unusual condition is stored in this type of object in the form of a stack. This object created is called an exception object the process is termed as throwing an exception. The mechanism of handling an exception is called catching an exception or handling an Exception or simply Exception handling. As we have known that after throwing an exception it is handed off to the runtime system that finds a possible method from an ordered list of methods to handle it. The list of this type of methods is known as the call stack The exceptions are not errors rather they are some abnormal conditions that aren't necessarily errors. Therefore, the process of detecting the exceptions and responding to them as well is known as Exception handling.

-

Following are the advantages of Exception-handling in Java:

77

-

Exception provides the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. One of the significance of this mechanism is that it throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error. With the help of this mechanism the working code and the errorhandling code can be disintegrated. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks. Furthermore the errors can be propagated up the method call stack i.e. problems occurring at the lower level in the chain can be handled by the methods higher up the call chain .

Sample Code The basic syntax to handle an Exception looks like this:

String myException() { try { return myMethod(); } catch ( IOException e ) { return null; } } There are three types of Exceptions:

78

79 . . Remember that all the exceptions are checked exceptions unless and until those indicated by Error.Exception class These exceptional conditions should be anticipated and recovered by an application. NoSuchFieldException InstantiationException IllegalAccessException ClassNotFoundException NoSuchMethodException CloneNotSupportedException InterruptedException Unchecked Exceptions – .lang. Here is the list of checked exceptions.These exceptions extend the java.Unchecked exceptions are internal to the application and extend the java. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer.lang.lang. .The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. RuntimeException or their subclasses. .Furthermore Checked exceptions are required to be caught. .Unchecked exceptions are the exceptions which occur during the runtime of the program.Checked Exceptions – .These are the exceptions which occur during the compile time of the program.Exception class.RuntimeException that is inherited from java.

An Error indicates serious problems that a reasonable application should not try to catch. These type of exceptions are also called Runtime exceptions that are usually caused by data errors. These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from. IndexOutOfBoundsException ArrayIndexOutOfBoundsException ClassCastException ArithmeticException NullPointerException IllegalStateException SecurityException Error – The errors in java are external to the application. declared in java.lang. Most such errors are abnormal conditions.lang package as java. Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java. Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement. - - - 80 .Throwable. Here is the list of unchecked exceptions. such as logic errors or improper use of an API. Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions The hierarchy of exception classes commence from Throwable class which is the base class for an entire family of exception classes. This class can be instantiated and thrown by the program. This error will cause the program to terminate but if an application wants then the error might be caught.IOError would be thrown.io. A throwable contains a snapshot of the execution stack at the time it was created and also a message string that gives more information about the error. divide by zero etc.- These exceptions cannot be anticipated and recovered like programming bugs. like arithmetic overflow.

only the exceptions are thrown by your code and not the errors. Remember that they are a member of Exception family and can be of type Checked or Unchecked exception.e. Also Remember that they are a member of Error family. Well.Exceptions – Errors – - The throwable class is further divided into two subclasses :- Exceptions are thrown if any kind of unusual condition occurs that can be caught.lang package defines several classes and exceptions. The exception classes can be explained as well seeing the hierarchy structure: The java. EXCEPTIONS DESCRIPTION CHECKED UNCHECKED Arithmetic ArithmeticException errors such as aYES divide by zero ArrayIndexOutOfBoundsException Arrays index isYES 81 . Some of these classes are not checked while some other classes are checked. When any kind of serious problem occurs which could not be handled easily like OutOfMemoryError then an error is thrown. errors are not something which is thrown by you rather they are thrown by the Java API or by the Java virtual machine itself i. Sometimes it also happens that the exception could not be caught and the program may get terminated.

lang can be thrown if any method with an invalid argument is thrown . that indicates someone passed an illegal argument to a method. a subclass of RuntimeException in java. It depends upon the situation that whether to use an existing exception class from java. For example.ClassNotFoundException IOException IllegalArgumentException InterruptedException NoSuchMethodException NullPointerException NumberFormatException not within array. Objects of your own design could also be thrown provided that they should be the subclass of some member of the Throwable family. Moreover only those objects could be thrown whose classes are derived from Throwable. if a thrown exception object has class IllegalArgumentException. - 82 .lang or create any of your own.length Related Class YES not found InputOuput YES field not found Illegal argument when calling amethod One thread has been interrupted YES by another thread Nonexistent YES method Invalid use of null reference Invalid string for conversionto number YES - YES YES - Exceptions are Objects that means an object is thrown when you throw an exception. Such as IllegalArgumentException. Also the throwable classes which are defined by you must extend Exception class.

83 . Simply a statement is surrounded by the try block that may cause the exception to occur. The mechanism to catch an exception in Java is to use try and catch block. And if the exception occurs then this catch block specifies a code that should be executed.// In Source Packet in file except/ex1/SpeedException.java class VerySlowException extends SpeedException { } The various keywords for handling exceptions are below. catch and finally block is given below. Every catch block can handle only one type of exception however you can use more than one catch clause in a single try block. catch and finally clause. try catch finally throw throws The three exception handler components are used to catch and handle the exceptions.java class SpeedException extends Exception { } // In Source Packet in file except/ex1/VeryFastException. These are try. Using try and catch:The syntax for the usage of try.java class VeryFastException extends SpeedException { } // In Source Packet in file except/ex1/VerySlowException. Then the try block is followed by the catch block.

Lets have a look at the example which shows the implementation of the try. where each catch block acts as an exception handler and can handle the type of exception indicated by its arguments. catch and finally block. - 84 . the first step we need to do is to enclose the code that is likely to generate an exception inside a try block. If an exception occurs in the try block then it is handled by the exception handler associated with it.try{ ……… ……… } catch(<exceptionclass1> <obj1>) { ……… ……… } finally { ……… ……… } For using an exception handler in an application." which throws an exception if we write a name of a file which doesn't exist as shown in the output. Here we have used "fis = new FileInputStream (new File (args[0])). For doing this we need to have one or more catch blocks after the try block.

whether or not an exception thrown. class Test { public static void main(String args[]) { FileInputStream fis=null. try { fis = new FileInputStream (new File (args[0])). } catch (FileNotFoundException e) { System. The finally block executes if and only if the try block exits.io. you need to enclose the code in a try block that has multiple exit points.import java.*. 85 . try { fis = new FileInputStream (new File (args[0])). There are two steps to use the finally clause: First.close().io.e.println("File not found!"). Secondly after the try block exits place the code that must be executed in a finally clause. import java. } finally { fis. Other than exception handling the finally clause helps you in avoiding any cleanup code accidentally bypassed by a return etc. } } } Using finally: It is always a good practice to use finally clause after the try and catch block because the finally block always executes even if an unexpected exception occurs i. The statements within the finally block gets executed by the the runtime system without taking care of what happens within the try block. class Test { public static void main(String args[])throws IOException { FileInputStream fis=null.*.out.

try{ if(fis!=null){ fis. } catch (IOException e) { System.").int ch.println(). While the throw keyword (note the singular form) is used to force an exception. When we call a method from the java API that throws a checked exception. Add the throws clause to the surrounding method to pass the error up to the next level (or else write your own catch/try handler).read()) != -1) { System.out.print ((char) ch).out.out.").println("In finally. } finally{ System. System. 86 . then the exception can be declared to the method header using the throws keyword followed by the class name of the exception.println("File not found!").out.out.println("In finally. } } catch (IOException ioe) { System. } } catch (FileNotFoundException e) { System. If you decide that you can't handle the exception properly.println("Unable to read file!"). while ((ch = fis.out. } } } } Using throws: The other way to handle an exception is using the throws clause. you must either throw the exception or catch it.close().

import java. while ((ch = fis.int second) throws MyException{ if(second==0) throw new MyException("can't be divided by zero"). Note: The reference should be of type Throwable or one of its subclasses. As mentioned earlier Throwable objects are instances of any subclass of the 87 .io.print ((char) ch). We use throw statement to throw an exception or simply use the throw keyword with an object reference to throw an exception.*. class Test3 { public static void main(String args[]) throws FileNotFoundException. A single argument is required by the throw statement i. fis = new FileInputStream (new File (args[0])).out. class MyException extends Exception { public MyException(String msg) { super(msg).e. a throwable object. } } public class Test { static int divide(int first. int ch. } } How to Throw Exceptions Throwable class. Before catching an exception it is must to be thrown first.read()) != -1){ System.close(). } fis. return first/second. throw new VeryFastException().IOException { FileInputStream fis=null.

out.} public static void main(String[] args) { try { System. The runtime system proceeds to find a matching catch block that can handle the exception.println(divide(4. 88 . then the exception is dealt with by the default exception handler at the top level. If no handler is found. normal execution is suspended.0)). } catch (MyException exc) { exc.printStackTrace(). } } } Handling Multiple Catch Clauses We can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program The syntax for using this clause is given below:try{ ……… ……… } catch(<exceptionclass_1> <obj1>){ //statements to handle the exception } catch(<exceptionclass_2> <obj2>){ //statements to handle the exception } catch(<exceptionclass_N> <objN>){ //statements to handle the exception } When an exception is thrown.

try { res = num1/num2.public class Multi_Catch { public static void main (String args[]) { int array[]={20. Nested Try-Catch Blocks In Java we can have nested try and catch blocks. if the first catch block contains the Exception class object then the subsequent catch blocks are never executed.num2=0.out.println ("Can't be divided by Zero"). for(int ct =2. It means that.println("Error…. This exception class being the super class of all the exception classes and is capable of catching any types of exception. Array is out of Bounds"). int res=0. 89 .30}.out.println("The result is" +res). This is known as Unreachable code problem. a try statement can be inside the block of another try. } catch (ArithmeticException e) { System. the last catch block in multiple catch blocks must contain the generic class object that is called the Exception class. } } } Handling the Unreachable Code Problem The multiple catch blocks can generate unreachable code error i.out. int num1=15.10.ct >=0.out. ct--) { System.e. } } catch (ArrayIndexOutOfBoundsException e) { System. System. To avoid this.println("The value of array are" +array[ct]).

io.println("The result is"+res). { try{ FileInputStream fis=null. This continues until one of the catch statements succeeds. } catch (Exception1 e) { //statements to handle the exception } } catch (Exception 2 e2) { //statements to handle the exception } Lets have an example that uses the nested try-catch blocks import java.*.- - If an inner try statement does not have a matching catch statement for a particular exception. System.. } } catch (FileNotFoundException e){ System. then the Java run-time system will handle the exception.out.out. the control is transferred to the next try statement’s catch handlers that are expected for a matching catch statement.println("divided by Zero").out. } catch(ArithmeticException e){ System. try{ res=num/0. public class NestedTry{ public static void main (String args[])throws IOException int num=2. If no one catch statements match. } catch(Exception e){ 90 .. The syntax of nested try-catch blocks is given below: try { try { // .println("Array index is Out of bound! Argument required"). or until all of the nested try statements are done in.out.println("File not found!"). fis = new FileInputStream (new File (args[0])).res=0. } catch(ArrayIndexOutOfBoundsException e){ System.

println(e. } catch(ArithmeticException e) { System. i--) System. For instance..println(e. 91 .getMessage()). } catch(ExceptionType1 e) { System.out. We have already learned that to catch an exception we use try and catch block.println("Error. try { int x = 50. } Catching Normal Exceptions The exceptions that are generated by methods are referred to as normal exceptions. i >= 0.out."+e). } Catching Runtime Exceptions The exceptions which are not easily traced are known as Runtime Exceptions. And if we won't handle the exception the program will end up with the termination.out.println(x / i). try { myTestException().getMessage()). } The above code displays a for loop trying to divide a number by zero in its last iteration which would result in runtime exception.out. for (int i = 15.println(e. This approach sometimes causes a mess so its always better to avoid the problems which land you up with the troubles. We have used try block to handle this exception and a corresponding handler by means of a catch clause.} } System. } catch(Exceptiontype2 e) { System.out. The disadvantage in handling the runtime exception is that we need to put the doubtful code inside a try block.getMessage()).

try { String str="amit".io.out.*. } } public class ExcepDemo { public static void main(String args[])throws MyException.println("Enter the your name").IOException { String temp="".*. BufferedReader br=new BufferedReader(new 92 . class MyException extends Exception { private String nm="". import java. First is called default constructor that doesn't accept any arguments. Another constructor accepts a string argument that provides the additional information about the exception. public String getMessage(String s) { nm=s.util. System. return ("you are not permitted to enter inside "+nm). - public class ExceptionClassName extends Exception { public ExceptionClassName(){ } public ExceptionClassName(StringMessage) { super(message). you can code a class that defines an exception that is more appropriate and that mechanism of handling exception is called Custom or User Defined Exception. In Java API all exception classes have two type of constructor. } } Lets see an example that has the implementation of User Define Exception: import java.Making Custom (User Define Exceptions) If you can't find the appropriate exception in the Java API.

if(!temp. Exception chaining (also known as "nesting exception") is a technique for handling the exception. } catch(Exception e) { System. Therefore chained exceptions help the programmer to know when one exception causes another. Typically the second exception is caused by the first exception. Java provides new functionality for chaining exceptions.InputStreamReader(System. else System.println(e). 93 . getMessage() Returns the message string of the Throwable object. - The constructors that support chained exceptions in Throwable class are: Throwable initCause(Throwable) Throwable(Throwable) Throwable(String.println("Welcome to India"). } catch(MyException e) { System. which occur one after another i. } } } What are Chained Exceptions? Whenever in a program the first exception causes an another exception. that is termed as Chained Exception.err.getMessage(temp)).in)).readLine(). most of the time is given by an application to response to an exception by throwing another exception.out.err.println(e.e. Throwable) Throwable getCause() The methods of the Throwable class are: METHOD DESCRIPTION Returns the exception followed by a message string (if toString() one exit) . temp=br.equals(str)) throw new MyException().

err. System.*. import java. } } } How to Print a Stack Trace Message Java provides a method getMessage() method that is used with an object of the Exception class to print errors to debug the process. The syntax for using a chained exception is as follows in which a new TestException exception is created with the attached cause when an IOException is caught.println(e.util.getCause()).err.*.println(e. } } public class ChainExcep{ public static void main(String args[])throws MyException.printStackTrace() GetCause() InitCause() Returns the full name of the exception class and some additional information apart from the information of first two method. Returns the exception that caused the occurrence of current exception. 94 . throw new MyException("Chained ArithmeticException"). Thus the chain exception is thrown to next level of exception handler.io. e). try { } catch (IOException e) { throw new TestException("Other IOException". class MyException extends Exception{ MyException(String msg){ super(msg). } catch(Exception e) { System. } Lets see an example having the implementation of chained exceptions: import java. Returns the current exception due to the Throwable constructors and the Throwable argument to initCause. IOException{ try { int rs=10/0.getMessage()).

.ct>=0..Try { // .. In multitasking only one CPU is involved Multitasking allow processes (i. programs) to run concurrently on the program. } } catch(Exception e) { e.length() .. } } } MultiThreading Multitasking Multitasking allow to execute more than one tasks at the same time. } catch (IOException e) { // . 95 ..print(sbuf.. for(int ct=len. For Example running the spreadsheet program and you are working with word processor also.printStackTrace(). int len=0.ct--){ System. Public class PrintStack{ public static void main (String args[]){ String str = "Exception" . Multitasking is running heavyweight processes by a single OS.out...getMessage())......out.println("Got an IOException: " + e. try{ StringBuffer sbuf = new StringBuffer(str). len = str. a task being a program.e.charAt(ct)).. } - Instead of this method you can get more information about the error process if you print a stack trace from the exception using the printStackTrace() method That is the method of the Throwable class and prints the stack trace to the console and provides the line numbers of statements that called the methods in the current stack.. Lets see an example that prints an exception's message. System.

It exists in a common memory space and can share both data and code of a program. Thus several processes may be associated with the same program. For example. program counter and lifetime. while a process with multiple threads is referred to as a multi-threaded process.e. drawing. Reduces the computation time. operations are executes sequentially i. thread is a sequential path of code execution within a program. Several threads of execution may be associated with a single process. associated with this program. Using threads we can increase the speed of any application. It is a collection of instructions which are executed simultaneously at the rum time. A thread is a lightweight process which exist within a program and executed to perform a special task. next operation can execute only when the previous one is complete. Cost of communication between threads is relatively low.Multithreading : Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). Context switching between threads is usually less expensive than between processes. to check the spelling is a single process in the Word Processor program and you can also use other processes like printing. In Java Programming language. It allows a process to run its tasks in parallel mode on a single processor system Advantages of multithreading over multitasking : Process A process is an instance of a computer program that is executed sequentially. Threads share the same address space so it saves the memory. Thread - 96 . In single threaded runtime environment. etc. Improves performance of an application. formatting. Each thread has its own local variables. Thus a process that has only one thread is referred to as a singlethreaded process.

At this point. Runnable (Ready-to-run) state – .A thread start its life from Runnable state. the thread is considered not alive. but the program will keep running until the all threads have complete its execution Different states of a thread are : New state – After the creations of Thread instance the thread is in this state but before the start() method invocation.- Diagram shown below in which a thread is executed along with its several operations with in a single process. then program terminates when the main() method complete its execution. 97 . The main() method execution can finish. If no other threads are created by the main thread. called the main thread. The main thread creates some other threads called child threads. it firstly execute the main() method runs in a one thread. Main Thread When any standalone application is running.

. If any thread comes on this state that means it cannot ever run again. if a particular event occurs. Running state – . sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. the thread is still alive but it is not runnable. Different states implementing Multiple-Threads are: Sleeping – - A running thread can enter to any non-runnable state. firstly it goes to runnable state.There are several ways to enter in Runnable state but there is only one way to enter in Running state: . the method sleep( ) can be used to stop the running state of a thread.A thread is in running state that means the thread is currently executing. Dead state – Blocked – A thread can enter in this state because of waiting the resources that are hold by another thread. A thread cannot enters directly to the running state from non-runnable state. On this state a thread sleeps for a specified amount of time. On this state. static void sleep(long millisecond) throws InterruptedException 98 . Now lets understand the some non-runnable states which may be occur handling the multithreads.- A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running. depending on the circumstances. A thread can be considered dead when its run() method completes.the scheduler select a thread from runnable pool. it might be return to runnable state later. waiting.

Waiting for Notification – - A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread. final void wait(long timeout) throws InterruptedException final void wait(long timeout, int nanos) throws InterruptedException final void wait() throws InterruptedException Blocked on I/O – - The thread waits for completion of blocking operation. - A thread can enter on this state because of waiting I/O resource. - In that case the thread sends back to runnable state after availability of resources. Blocked for joint completion – - The thread can come on this state because of waiting the completion of another thread. Blocked for lock acquisition – - The thread can come on this state because of waiting to acquire the lock of an object. Methods that can be applied on a Thread: Some Important Methods defined in java.lang.Thread are shown in the table: Return Method Description Type currentThread( Returns an object reference to the thread in which it is Thread ) invoked. getName( ) String Retrieve the name of the thread object or instance. start( ) void Start the thread by calling its run method. This method is the entry point to execute thread, like run( ) void the main method for applications. Suspends a thread for a specified amount of time (in sleep( ) void milliseconds). This method is used to determine the thread is isAlive( ) boolean running or not. This method returns the number of active threads in a activeCount( ) int particular thread group and all its subgroups. The method interrupt the threads on which it is interrupt( ) void invoked. By invoking this method the current thread pause its yield( ) void execution temporarily and allow other threads to execute.

99

join( )

void

This method and join(long millisec) Throws InterruptedException. These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.

-

Thread can be implemented through any one of two ways: 1. Extending the java.lang.Thread Class 2. Implementing the java.lang.Runnable Interface

Extending the java.lang.Thread Class
For creating a thread by this procedure - Extend the java.lang.Thread Class. - Override the run( ) method in the subclass from the Thread class to define the code executed by the thread. - Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor. - Invoke the start( ) method on the instance of the class to make the thread eligible for running. The following program demonstrates a single thread creation extending the "Thread" Class:

class MyThread extends Thread{ String s=null; MyThread(String s1){ s=s1; start(); } public void run(){ System.out.println(s); } } public class RunThread{ public static void main(String args[]){

100

MyThread m1=new MyThread("Thread started...."); } }

II. Implementing the java.lang.Runnable Interface A Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object. Create an object of Thread Class by passing a Runnable object as argument. Invoke the start( ) method on the instance of the Thread class.

class MyThread1 implements Runnable{ Thread t; String s=null; MyThread1(String s1){ s=s1; t=new Thread(this); t.start(); } public void run(){ System.out.println(s); } } public class RunableThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); } }

-

There are two reasons for implementing a Runnable interface preferable to extending the Thread Class: If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you implement Runnable interface then you can do this. The class implementing the Runnable interface can avoid the full overhead of Thread class which can be excessive. join() & isAlive() methods:

The following program demonstrates the join() & isAlive() methods:
class DemoAlive extends Thread { int value; public DemoAlive(String str){ super(str); value=0; start();

101

} public void run(){ try{ while (value < 5){ System.out.println(getName() + ": " + (value++)); Thread.sleep(250); } } catch (Exception e) {} System.out.println("Exit from thread: " + getName()); } } public class DemoJoin{ public static void main(String[] args){ DemoAlive da = new DemoAlive("Thread a"); DemoAlive db = new DemoAlive("Thread b"); try{ System.out.println("Wait for the child threads to finish."); da.join(); if (!da.isAlive()) System.out.println("Thread A not alive."); db.join(); if (!db.isAlive()) System.out.println("Thread B not alive."); } catch (Exception e) { } System.out.println("Exit from Main Thread."); } }

Several

constructors

are

available

for

creating

new

Thread

instances.

Thread() Thread(String) Thread(Runnable) Thread(Runnable,String) Thread(ThreadGroup,String) Thread(ThreadGroup,Runnable) Thread(ThreadGroup,Runnable,String) Thread(ThreadGroup, Runnable, String, long) ThreadGroup– - All threads belongs to an instance of the ThreadGroup Class. - ThreadGroup is used to represent a group of threads. - There is only one root ThreadGroup that contains all other thread and groups and each subgroups can contain other groups and threads. - All thread have only one thread group. 102

getThreadGroup() – This method is used to know the thread is belong to which thread group. Then newly formed group3 comes under the group2.“group3”). String gname=g. Some important methods are: getName() – This method is used to retrieve the name of particular group. When a new ThreadGroup is created. getParent() – This method is used to retrieve the name of parent threadgroup of sub group. activeGroupCount() – This method returns the number of active thread group in a particular thread group and all its subgroups. int size=group.- And all thread groups (except the root thread group) belongs to exactly one parent thread group.getParent(). it is added as a member of existing ThreadGroup. ThreadGroup g=new ThreadGroup(“RoseIndia”). ThreadGroup group=threadx. If you want a parent group other than default then you have to specify the parent group at the time of creation.activeGroupCount(). and executes the code: ThreadGroup group2=new ThreadGroup(“group2”). ThreadGroup group=group3. ThreadGroup group2=new ThreadGroup(group2. Then the newly formed group2 comes under group1. 103 . Threads can access only belonging thread group. If a thread x in group1.getName().getThreadGroup().

}catch(Exception e){} } } } public class MultiThread1{ public static void main(String args[]){ System. Constant Description The maximum priority of Thread.Thread gets the ready-to-run state according to their priorities. MyThread m1=new MyThread("My Thread 1").In Java. . thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads .println("Thread Name :" +Thread.currentThread().NORM_PRIORITY thread (an int value of 5) The methods that are used to set the priority of thread shown as: Method Description 104 .MAX_PRIORITY).NORM_PRIORITY).MIN_PRIORITY any thread (an int value of 10) The minimum priority of Thread.i++){ System. } } Thread Priorities .out.sleep(1000). try{ Thread.class MyThread extends Thread{ MyThread(String s){ super(s).The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.getName()).currentThread(). . MyThread m2=new MyThread("My Thread 2").i<5.out.Priorities are integer values from 1 (lowest priority given by the constant Thread.MAX_PRIORITY any thread (an int value of 1) The normal priority of any Thread.The default priority is 5(Thread. } public void run(){ for(int i=0. . . start().println("Thread Name :" +Thread.getName()).MIN_PRIORITY) to 10 (highest priority given by the constant Thread.

it inherits its priority from the thread that created it.i++){ Thread cur=Thread. after completion the time. In Java runtime system.Lets see.currentThread().println("Thread Priority :"+cur). } - 105 .currentThread(). This method is used to get the getPriority() priority of thread.i<3. current thread indicates to the another thread to enter it in the runnable state. Time-Sliced (Round-Robin) Scheduling – . } public void run(){ for(int i=0.can also set a thread's priority at any time after its creation using the setPriority method.getName()). int p=cur. .println("Thread Name :"+Thread. System. setPriority() When a Java thread is created. start(). how to set and get the priority of a thread. On the other hand.out. - Thread Scheduler In the implementation of threading scheduler usually applies one of the two following strategies: Preemptive scheduling – . class MyThread1 extends Thread{ MyThread1(String s){ super(s). the runtime system chooses the runnable thread with the highest priority for execution.If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state.A running thread is allowed to be execute for the fixed time. preemptive scheduling algorithm is applied.This is method is used to set the priority of thread. cur. If at the execution time a thread with a higher priority and all other threads are runnable then the runtime system chooses the new higher priority thread for execution.getPriority(). .out. System. if two threads of the same priority are waiting to be executed by the CPU then the round-robin algorithm is applied in which the scheduler chooses one of them to run according to their round of time-slice. when multiple threads are ready to be executed.setPriority(Thread.MIN_PRIORITY).

System. But Thread1 need to printer that is hold up by the Thread2. cur. likewise Thread2 need the keyboard that is hold up by the Thread1.MAX_PRIORITY). } } } public class ThreadPriority{ public static void main(String args[]){ MyThread1 m1=new MyThread1("My Thread 1").} } class MyThread2 extends Thread{ MyThread2(String s){ super(s). int p=cur. Lets see a situation in the diagram shown below where the deadlock condition is occurred - - In this diagram two threads having the Printing & I/O operations respectively at a time.setPriority(Thread.currentThread().out. MyThread2 m2=new MyThread2("My Thread 2").i<3.i++){ Thread cur=Thread.out. } } DeadLock A situation where a thread is waiting for an object lock that holds by second thread.println("Thread Name :"+Thread.currentThread().getName()).getPriority(). and this second thread is waiting for an object lock that holds by first thread.println("Thread Priority :"+cur). 106 . start(). } public void run(){ for(int i=0. System. this situation is known as Deadlock.

In this situation the CPU becomes ideal and the deadlock condition occurs because no one thread is executed until the hold up resources are free. The following program demonstrates the deadlock situation:
public class DeadDemo{ public static void main(String args[]){ String s1="Dead"; String s2="Lock"; MyThread1 m=new MyThread1(s1,s2); MyThread2 m1=new MyThread2(s1,s2); } } class MyThread1 extends Thread{ String s1; String s2; MyThread1(String s1, String s2){ this.s1=s1; this.s2=s2; start(); } public void run(){ while(true){ synchronized(s1){ synchronized(s2){ System.out.println(s1+s2); } } } } } class MyThread2 extends Thread{ String s1; String s2; MyThread2(String s1,String s2){ this.s1=s1; this.s2=s2; start(); } public void run(){ while(true){ synchronized(s2){ synchronized(s1){ System.out.println(s2+s1); }

-

} }

} }

107

Synchronized Threads In Java, the threads are executed independently to each other. These types of threads are called as asynchronous threads. But there are two problems may be occur with asynchronous threads. Two or more threads share the same resource (variable or method) while only one of them can access the resource at one time. If the producer and the consumer are sharing the same kind of data in a program then either producer may produce the data faster or consumer may retrieve an order of data and process it without its existing. Suppose, we have created two methods as increment( ) and decrement( ). which increases or decreases value of the variable "count" by 1 respectively shown as:

public void increment( ) { count++; } public void decrement( ) { count--; } public int value() { return count; } When the two threads are executed to access these methods (one for increment( ),another for decrement( )) then both will share the variable "count". in that case, we can't be sure that what value will be returned of variable "count". We can see this problem in the diagram shown below:

-

108

To avoid this problem, Java uses monitor also known as “semaphore” to prevent data from being corrupted by multiple threads by a keyword synchronized to synchronize them and intercommunicate to each other. General form of the synchronized statement is as: synchronized(object) { // statements to be synchronized }

-

Lock: Lock term refers to the access granted to a particular thread that can access the shared resources. At any given time, only one thread can hold the lock and thereby have access to the shared resource. Every object in Java has build-in lock that only comes in action when the object has synchronized method code. By associating a shared resource with a Java object and its lock, the object can act as a guard, ensuring synchronized access to the resource. Only one thread at a time can access the shared resource guarded by the object lock. Since there is one lock per object, if one thread has acquired the lock, no other thread can acquire the lock until the lock is not released by first thread. Acquire the lock means the thread currently in synchronized method and released the lock means exits the synchronized method.

Remember the following points related to lock and synchronization: Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized. Each object has just one lock.All methods in a class need not to be synchronized. A class can have both synchronized and non-synchronized methods. If two threads wants to execute a synchronized method in a class, and both threads are using the same instance of the class to invoke the method then only one thread can execute the method at a time. If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods.

-

109

-

If you have methods that don't access the data you're trying to protect, then you don't need to synchronize them. Synchronization can cause a hit in some cases (or even deadlock if used incorrectly), so you should be careful not to overuse it.

Note : If a thread goes to sleep, it holds any locks it has,it doesn't release them. A thread can acquire more than one lock. Constructors cannot be synchronized There are two ways to synchronized the execution of code: Synchronized Methods Synchronized Blocks (Statements) Synchronized Methods: wait. Synchronized methods are useful in those situations where methods are executed concurrently, so that these can be intercommunicate manipulate the state of an object in ways that can corrupt the state if .
class Share extends Thread{ static String msg[]={"This", "is", "a", "synchronized", "variable"}; Share(String threadname){ super(threadname); } public void run(){ display(getName()); } public synchronized void display(String threadN){ for(int i=0;i<=4;i++) System.out.println(threadN+msg[i]); try{ this.sleep(1000); }catch(Exception e){} } } public class SynThread1 { public static void main(String[] args) { Share t1=new Share("Thread One: "); t1.start(); Share t2=new Share("Thread Two: "); t2.start(); } }

Synchronized Blocks (Statements) - Another way of handling synchronization is Synchronized Blocks (Statements).

110

i++) System. synchronized (object reference expression) { // statements to be synchronized } The following program demonstrates the synchronized block that shows the same output as the output of the previous example: class Share extends Thread{ static String msg[]={"This". "synchronized". }catch(Exception e){} } } public class SynStatement { public static void main(String[] args) { Share t1=new Share("Thread One: "). } public void display(String threadN){ synchronized(this){ for(int i=0. t1.start(). The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object. "a".lang" package and can only be called within synchronized code shown as: 111 . a thread is paused running in its critical region and another thread is allowed to enter (or lock) in the same critical section to be executed.out. } } - Inter-Thread Communication A process where. } public void run(){ display(getName()).i<=4. This technique is known as Interthread communication which is implemented by some methods. Share t2=new Share("Thread Two: "). Share(String threadname){ super(threadname).start().println(threadN+msg[i]).sleep(1000). try{ this. These methods are defined in "java.Synchronized statements must specify the object that provides the native lock. "is". t2. "variable"}.

notify(). The highest priority thread will run first. notifyAll( Wakes up (Unloack) all the threads that called wait( ) on ) the same object. synchronized int get() { if (value==false) try { wait(). } this. return num. notify(). System.println("InterruptedException caught").out. Method 112 . } synchronized void put(int num) { if (value==true) try { wait(). Lets see an example implementing these methods : class Shared { int num=0. } System. value=false. this. boolean value = false. value=false. } catch (InterruptedException e) { System. Producer(Shared s) { this.start().out.println("consume: " + num).println("InterruptedException caught"). } } class Producer extends Thread { Shared s. It wakes up the first thread that called wait() on the same notify( ) object.out.Description It indicates the calling thread to give up the monitor and go Wait( ) to sleep until some other thread enters the same monitor and calls method notify() or notifyAll(). } catch (InterruptedException e) { System.s=s.println("Produce: " + num). All these methods must be called within a try-catch block.out.num=num.

new Consumer(s).out. s. Consumer(Shared s) { this. The following program demonstrates the Daemon Thread: public class DaemonThread extends Thread { public void run() { System. new Producer(s). try { System. } } public class InterThread{ public static void main(String[] args) { Shared s=new Shared(). Daemon threads are used for background supporting tasks and are only needed while normal threads are executing.get(). setDaemon(true/false) – This method is used to specify that a thread is daemon thread.println("Entering run method"). If normal threads are not running and remaining threads are daemon threads then the interpreter exits. } } Daemon Threads Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. public boolean isDaemon() – This method is used to determine the thread is daemon thread or not. this.currentThread()).println("In run Method: currentThread() is" + Thread. } } class Consumer extends Thread{ Shared s.} public void run() { int i=0.put(++i).out. } public void run() { s. 113 .start().s=s.

out.sleep(3000). } catch (InterruptedException x) { } System. t. The java. The classes in the package are primarily abstract classes and streamoriented that define methods and subclasses which allow bytes to be read from and written to files or other input and output sources. } } Files (IOStreams) Introduction The Java Input/Output (I/O) is a part of java. } catch (InterruptedException x) { } System.out.out.start().setDaemon(true).println("Leaving run Method").out. try { Thread. The java.println("In run method: woke up again").while (true) { try { Thread.println("Entering main Method").println("Leaving main method"). DaemonThread t = new DaemonThread(). } } public static void main(String[] args) { System. respectively. t.io package.io package contains a relatively large number of classes that support input and output operations.sleep(500). } } finally { System.io package can be categories along with its stream classes in a hierarchy structure shown below: 114 . The InputStream and OutputStream are central classes in the package which are used for reading from and writing to byte streams.

It is an abstract class that defines the programming interface for all input streams that are inherited from it. close a stream with the close( ) method. The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown below: - 115 . An input stream is automatically opened when you create it. An input source can be a file. a string. or memory that may contain the data.InputStream: The InputStream class is used for reading the data such as a byte and array of bytes from an input source.

or memory containing the data. For example. . an output source can be anything such as a file.The OutputStream class is a sibling to InputStream that is used for writing byte and array of bytes to an output source. . 116 .Explicitly close an output stream with the close( ) method. OutputStream: . or let it be closed implicitly when the object is garbage collected.InputStream is inherited from the Object class.Similar to input sources. an InputStream can flow the data from a disk file to the internal memory and an OutputStream can flow the data from the internal memory to a disk file. an output stream is automatically opened when you create it. a string. The classes inherited from the OutputStream class can be seen in a hierarchy structure shown below: OutputStream is also inherited from the Object class. How Files and Streams Work: Java uses streams to handle I/O operations through which the data is flowed from one location to another.Like an input stream. .

This class provides read text from character input stream and buffering characters. arrays and lines. Classes and Interfaces of the I/O Streams Classes: The following listing of classes are provided by the java. ByteArrayInputStream ByteArrayOutputStream It contains the internal buffer and read data from the stream. It implements a buffered output stream. It supports the mark and reset methods. The working process of the I/O streams can be shown in the given diagram. arrays and lines. It also reads characters. This class used for data is written into byte array. When we work with a text file. BufferedWriter This class provides write text from character output stream and buffering characters.io package shown in the table: Class Description BufferedInputStream It used for creating an internal buffer array. This is implement in output stream BufferedReader 117 . we use a character stream where one character is treated as per byte on disk. BufferedOutputStream This class used for writes byte to output stream.- The disk-file may be a text file or a binary file. we use a binary stream. It also writes characters. When we work with a binary file.

It provides the permission to access a file or directory. This class writes the primitive data types from the output stream in machine format.CharArrayReader CharArrayWriter DataInputStream DataOutputStream File FileDescriptor FileInputStream FileOutputStream FilePermission FileReader FileWriter FilterInputStream FilterOutputStream FilterReader FilterWriter InputStream InputStreamReader LineNumberReader ObjectInputStream ObjectInputStream. It reads the data from the filtered character stream.GetField ObjectOutputStream class. This class access to president fields read form input stream. This class also implements a character buffer and it uses an writer. It reads bytes and decodes them into characters. This class reads the primitive data types from the input stream in a machine format. This class represents an input stream of bytes. This class used for reading characters file. This class overrides all methods of OutputStream and contains some other output stream. This class uses for create a FileInputStream and FileOutputStream. It uses for writing data to a file and also implements an output stream. This class used for write the primitive data types and also write the object to read by the ObjectInputStream. It used for char input stream and implements a character buffer. This class has a line numbers This class used for recover the object to serialize previously. 118 . This class overrides all methods of InputStream and contains some other input stream. It contains the input byte from a file and implements an input stream. This class used for writing characters files. It writes data from the filtered character stream. This class shows a file and directory pathnames.

It has character read source. This class also connected into a piped output stream. This class also communicates the piped input stream into piped output stream. It creates communication between both. Interfaces: 119 . It uses for writing to character stream. This class adds the functionality of another output stream. It is a piped character-output stream. This class adds the functionality of another input stream. This class represents an output stream of bytes. It used for reading character stream. This class describes the serializable field. This is a character string class. In this class the data bytes are written into piped output stream. It supports both reading and writing to a random access file. It represents the logical concatenation of other input stream.GetField ObjectStreamClass ObjectStreamField OutputStream OutputStreamWriter PipedInputStream PipedOutputStream PipedReader PipedWriter PrintStream PrintWriter PushbackInputStream PushbackReader RandomAccessFile Reader SequenceInputStream SerializablePermission StreamTokenizer StringReader StringWriter Writer This class access to president fields write in to ObjectOutput. It uses to shows the output in the buffer. This is also a character string class. It is a piped character-input stream. This is a serializable permission class. This is a character stream reader and reads the data push back into the stream. It takes an input stream and parse it into "tokens" . It also include the another function of input stream.ObjectOutputStream. The token to be allowed at the read time. Serialization's descriptor for classes. It writes bytes and decodes them into characters. Such as: "push back" or "unread" one byte.

in the Externalizable FileFilter FilenameFilter ObjectInput ObjectInputValidation ObjectOutput ObjectStreamConstants Serializable Exceptions Classes: The following summary of the exception classes provided by the java.Serializable interface.io package shown in the table: Exceptions Description CharConversionException It provides detail message in the catch block to associated with the CharConversionException EOFException This exception indicates the end of file.The following summary of Interfaces provided by the java. It can be used for Filtering the Pathnames. This interface implementing java. It save and store it's contents. When the file input stream to be end then EOFException to be occuted. 120 .io. FileNotFoundException When the open file's pathname does not find then this exception to be occured. DataOutput This interface can be used for writing the byte stream and converting data from the java primitive data types. This interface used for writing of objects and it extends the DataOutput interface. This is written in Serializable Stream. This interface used for reading of objects and it extends the DataInput interface.io package shown in the table: Interface Description DataInput This interface can be used for reading byte stream and reconstructing the java primitive data types. It allows the validation of objects within a graph. This interface used for Constants writing into Serialization Objects Stream. This interface used for Filter the Filenames. This is a Callback interface.

It is belonging to the serialized object OptionalDataException StreamCorruptedException It thrown when the control information that was read form an object stream vioaltes internal consistency checks. When the I/O operations to be failed then it occurs. SyncFaieldException UnsupportedEncodingException UTFDataFormatException The sync operation is failed SyncFaieldException to be occure. it implemented by data input interface. then The Character Encoding is not supported. The Serialization or deserialization operations are not active then it occurs. A molformed UTF-8 has been read in a data input stream. This is a supper class of all exception class. Any problems to be created with class. WriteAbortedException 121 . When the reading data operations to failed then it these exception occurs. InvalidObjectException IOException NotActiveException NotSerializableException ObjectStreamException When the de-serialized objects failed then it occurs.InterruptedIOException InvalidClassException When the I/O operations to interrupted from any causes then it becomes. when the Serializing runtime to be detected. It used for specific to Object Stream Classes. This exception when the instance is required to a Serializable interface. In this exception to be thrown by the ObjectStreamException during a write operating.

InputStreamReader inp = new InputStreamReader(system. The following diagram shows a class-hierarchy of the java. These objects are defined automatically and do not need to be opened explicitly. . Java also supports three Standard Streams: Standard Input: Accessed through System. Standard Error: Accessed through System. the Reader class is further categorized into the subclasses.The only methods that a subclass must implement are read(char[].in within the InputStreamReader as an argument. they read input from the keyboard and write output to the display. . .Reading Text from the Standard Input Standard Streams: Standard Streams are a feature provided by many operating systems.Reader class. Standard Output: Accessed through System. They also support I/O operations on files. - 122 . having error output separately so that the user may read error messages efficiently. . . Working with Reader classes: Java provides the standard I/O facilities for reading text from either the file or the keyboard on the command line.in).Standard Output and Standard Error. both are to write output. int) and close().io.It acts as an abstract class for reading character streams.err which is used to write error output to be display.System.in is a byte stream that has no character stream features.To use Standard Input as a character stream. wrap System.in which is used to read input from the keyboard. By default. int.out which is used to write output to be display.io package.The Reader class is used for this purpose that is available in the java. .

Thus.in) BufferedReader : The BufferedReader class is the subclass of the Reader class.e. - For example the constructors of the BufferedReader class shown as: BufferedReader(Reader in):Creates a buffering character-input stream that uses a default-sized input buffer. or the default size may be used that is large enough for text reading purposes. BufferedReader class provides some standard methods to perform specific reading operations shown in the table. It reads character-input stream data from a memory area known as a buffer maintains state. . When you create an InputStreamReader. The buffer size may be specified. All methods throws an IOException. BufferedReader(Reader in. additional functionality. most subclasses override some of the methods in order to provide higher efficiency. int sz): Creates a buffering character-input stream that uses an input buffer of the specified size. if an I/O error occurs. where the unbuffered stream object is passed to the constructor for a buffered stream class. this class reads characters from a byte input stream. BufferedReader converts an unbuffered stream into a buffered stream using the wrapping expression.However. or both. 123 . InputStreamReader: An InputStreamReader is a bridge from byte streams to character streams i. it reads bytes and decodes them into Unicode characters according to a particular platform. The syntax of InputStreamReader is written as: InputStreamReader <variable_name> = new InputStreamReader(system.

it is easier to write platform-independent code that examines and manipulates files using the File class. 124 .readLine(). A line is considered to be terminated by ('\n'). import java.println("Enter text : "). This program illustrates you how to use standard input stream to read the user input. The File class deals with the machine dependent files in a machineindependent manner i.File is the central class that works with files and directories.out.Method read( ) read(char[] cbuf.. the system doesn't check to the existence of a corresponding file/directory.e.io. public class ReadStandardIO{ public static void main(String[] args) throws IOException{ InputStreamReader inp = new InputStreamReader(System. we will learn how to work with a file using the non-stream file I/O.lang package. String str = in. Read a line of text. } } System. Working With File Streams don't support all the operations that are common with a disk file In lesson. int len) readLine( ) close( ) int off. System.println("You entered String : "). The java. This class is available in the java. Return Type int int String void Description Reads a single character Read characters into a portion of an array.println(str). When a File object is created.out.in) BufferedReader br = new BufferedReader(inp). System.io.*. Closes the opened stream.out.

Create File object for directory. fname) Thus the statement can be written as: File f = new File("<filename>"). f. f.fname) File(dir. File(dirpath. Method Description f. f. f.renameTo(f2) Renames f to File f2.isHidden() Returns true if file is hidden.getPath() path name. f.isFile() Returns true if this is a normal file. f.getName() Returns name of the file or directory.- If the file exist. Create a File Introduction A file is used to store the data. Returns true if successful. File is a collection of stored information that are arranged in string. This method returns a boolean value true if the file is created otherwise return false.exists() Returns true if file exists. The methods that are used with the file object to get the attribute of a corresponding file shown in the table.lastModified() Returns time of last modification. f. f. f.length() Returns number of bytes in file. such as renaming it.isDirectory() true if "f" is a directory.createNewFile() Creates a file and may throw IOException. 125 . reading from or writing to it. For creating a new file File. columns and lines etc. The constructors of the File class are shown in the table: Constructor Description File(path) Create File object for default directory (usually where program is located). Create File object for directory path given as string. f.createNewFile( ) method is used. a program can examine its attributes and perform various operations on the file. rows.delete() Deletes the file. deleting it.

createNewFile().exists()){ f.txt\" has been created to the current directory").separator + "myfile. System. Java supports the following I/O file streams.out. f=new File("myfile. import java.println("New file \"myfile.*.txt\" has been created to the specified location"). which is helpful for mapping local file name with the actual path of the file using the constructing filename path technique.Java Tutorial Introduction will learn how to write java program to read file line by line. public class CreateFile1{ public static void main(String[] args) throws IOException{ File f.println("The absolute path of the file is: " +f. f. FileInputstream 126 .getAbsolutePath()). import java.- If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true. } } Java read file line by line . if(!f.println("New file \"myfile. Lets see an example that checks the existence of a specified file.io.txt").txt").out. f=new File("example" + File. public class PathFile{ public static void main(String[] args) throws IOException{ File f. System. } } } Constructing a File Name path In Java.createNewFile().out.io.*. System. it is possible to set dynamic path.

this class is used with an InputStreamReader and BufferedReader class. DataInputStream: This class is a type of FilterInputStream that allows you to read binary data of Java primitive data types in a portable way. The following program demonstrate. The read() method of this class reads a byte or array of bytes from the file.FileOutputStream FileInputstream: This class is a subclass of Inputstream class that reads bytes from a specified file name . 127 . DataInputStream(FileOutputstream finp). FileOutputstream(File filename). You can use the constructor of this stream as: FileInputstream(File filename). FileOutputStream: This class is a subclass of OutputStream that writes data to a specified file name. To write text. In other words. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. how the contains are read from a file. It returns -1 when the end-of-file has been reached. To read text data. The write() method of this class writes a byte or array of bytes to the file. An application uses a DataOutputStream to write data that can later be read by a DataInputStream. This program reads the bytes from file and display it to the user. if the specified file is not exist. the DataInputStream class is used to read binary Java primitive data types in a machine-independent way. we typically use it with a PrintWriter. BufferedWriter and an OutputStreamWriter class. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. This class throws FileNotFoundException.

length()<0) System.println("The specified file is not exist").readLine()) != null) { // Print the content on the console System.out. if(!f. import java. } } } The another program use DataInputStreams for reading textual input line by line with an appropriate BufferedReader.err.read(). }catch (Exception e){//Catch exception if any System. BufferedReader br = new BufferedReader(new InputStreamReader(in)).getMessage()). String strLine.println (strLine). } } } 128 .out. f=new File("myfile. public class ReadFile{ public static void main(String[] args) throws IOException{ File f. } //Close the input stream in.io. class FileRead { public static void main(String args[]) { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("textfile.txt"). } while(b!=-1).import java.println("Error: " + e.txt"). else{ FileInputStream finp=new FileInputStream(f).*. //Read File Line By Line while ((strLine = br. byte b.close(). do{ b=(byte)finp.print((char)b).*. System.io.out.exists()&& f.close(). // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream). finp.

The FileWriter class creates an internal FileOutputStream to write bytes to the specified file 129 . System. You create a FileWriter by specifying the file to be written to. } else System.Java Write To File . If the file exist. Lets see an example that writes the data to a file converting into the bytes.out. FileOutputStream fop=new FileOutputStream(f).Java Tutorial Introduction FileOutputStream class is used to write data to a file. public class WriteFile{ public static void main(String[] args) throws IOException{ File f=new File("textfile1. when the data should be appended to the end of an existing file instead of overwriting that file. } } The another way for writing data to a file.out. FileWriter : FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file. fop. fop.exists()){ String str="This data is written through the program". or optionally.write(str.close(). the class FileWriter and BufferedWriter are used. the data is written to the file through the object of the FileOutputStream class.io. if(f.flush().*.txt").getBytes()). import java. This program first check the existence of the specified file.println("The data has been written").println("This file is not exist"). fop.

exit(0).println("File created successfully. Following code creates the object of FileWriter and BufferedWriter: FileWriter fstream = new FileWriter(file_name).println("File already exists. System. import java. Lets see an another example that writes the text input by the user using the FileWriter and the BufferedWriter class.out.BufferedWriter : The BufferedWriter class is used to write text to a character-output stream."). } } } 130 .out.readLine()).*. System.print("Please enter the file name to create : "). File file = new File(file_name).write(read_the_Buffered_file_name). if (!exist) { System. String file_name = in. BufferedWriter out = new BufferedWriter(fstream).io.").close(). public class FileWriter{ public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System. arrays and strings.write(in. Following code write data into new file: out.createNewFile(). System. } else { FileWriter fstream = new FileWriter(file_name). boolean exist = file. out. buffering characters so as to provide for the efficient writing of single characters.out. out. The constructor of the FileWriter class takes the file name which has to be buffered by the BufferedWriter stream. The write( ) method of BufferedWriter class is used to create the file into specified directory.in)).readLine(). BufferedWriter out = new BufferedWriter(fstream).

getMessage()). About the methods that can be used to get the file size. class FileWrite { public static void main(String args[]) { try{ // Create file FileWriter fstream = new FileWriter("out. If you give the text based file then the program tells you the number of characters otherwise it will give you the file size in bytes.txt". out.e. BufferedWriter out = new BufferedWriter(fstream). BufferedWriter The BufferWriter class is used to write text to a character-output stream. 131 . This constructor simply overwrite the contents in the file by the specified string but if you put the boolean value as true with the file name (argument of the constructor) then the constructor append the specified data to the file i. }catch (Exception e){//Catch exception if any System.*. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. Program takes the file name through the keyboard and checks whether the file exists.println("Error: " + e. the pre-exist data in a file is not overwritten and the new data is appended after the pre-exist data.close().write("Hello Java"). //Close the output stream out.Java Tutorial Introduction . } } } Getting the Size of a File in Java Introduction How to get the size (in bytes) of a specified file.the class FileWriter and BufferedWriter to append the data to a file.true). arrays. and strings.Append To File . buffering characters so as to provide for the efficient writing of single characters. import java.io. FileWriter The FileWriter is a class used for writing character files.err.

it takes a file name with its extension from a particular directory and checks it using the exists() method.out.println("File does not exists. it will count lines of a particular file otherwise it will display a message "File does not exists!". File f = new File(in.length().This is the constructor of FileReader class that is reliable for reading a character files.exit(0).If the file exists. rows. public static void main(String[] args) throws IOException{ System. .in)). - 132 .At the execution time of this program. File is a collection of stored information that are arranged in string.- If the file exists then the length( ) method of the instance of the File class gives you size of the file.print("Enter file name : "). Description of program: .*. A file is read before counting lines of a particular file. columns and lines etc.io. public class FileSize{ import java. .exists()){ long file_size = f."). } else{ System. BufferedReader in = new BufferedReader(new InputStreamReader(System.println("Size of the file : " + file_size). Count lines of a particular file Count the availability of text lines in the particular file.out.out. System.It constructs a new FileReader and takes a file name that have to be read. if(f. } } } System.readLine()). Description of code: FileReader(File file) .

in)).FileNumberReader(): This is the constructor of FileNumberReader class. String str = bf. System. } System. } } catch(IOException e){ e. BufferedReader bf = new BufferedReader(new InputStreamReader(System.println("Getting line number of a paritcular file example!"). LineNumberReader ln = new LineNumberReader(fr). import java. It constructs a new line-numbering reader.out.println("Please enter file name with extension:").println("File does not exists!"). public class NumberOfLine{ public static void main(String[] args) { try{ System.readLine() != null){ count++. if (file. } else{ System. It reads characters and puts into buffer. By default the numbering of line begins from '0'.exists()){ FileReader fr = new FileReader(file).readLine(). File file = new File(str).out.close().io.printStackTrace().out. 133 .*.out. int count = 0.println("Total line no: " + count). ln. while (ln.

println("Modification is successfully!"). System. public class ChangeFileDate{ public static void main(String[] args) { try{ System.out. String str = bf.*. import java.println("Change file timestamp example!").setLastModified(date. System. } else{ System.parse(strDate).println("Enter file name with extension:"). File file = new File(str). String strDate = bf.io. Date date = sdf.util. 134 .*.println("Enter last modified date in 'dd-mm-yyyy' format:").out. System. import java.exists()){ file. SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy").println("File does not exists!").out.readLine(). if (file. } } catch(Exception e){ e.printStackTrace().} } } Change a file timestamp import java. BufferedReader bf = new BufferedReader(new InputStreamReader(System.out.in)).getTime()).*.text.out.readLine().

Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining. Applets are designed for the client site programming purpose while the applications don't have such type of criteria.} } } Applets Introduction Applet is java program that can be embedded into HTML pages. Applets can run in our browser's window or in an appletviewer. 135 . it will be downloaded from internet and will take time Its difficult to desing and build good user interface in applets compared to HTML technology Applet versus Application Applets as previously described. are the small programs while applications are larger programs. Advantages of Applet: • • • • • • Applets are cross platform and can run on Windows. Mac OS and Linux platform Applets can work all the version of Java Plugin Applets runs in a sandbox. so the user does not need to trust the code. Applets don't have the main method while in an application execution starts with the main method. so it can work without security approval Applets are supported by most web browsers Applets are cached in most web browsers. Java applets runs on the java enabled web browsers such as mozila and internet explorer . so will be quick to load when returning to a web page User can also have full access to the machine if user allows Disadvantages of Java Applet: • • • • Java plug-in is required to run applet Java applet requires JVM so first time it takes significant startup time If applet is not already cached in the machine. To run the applet in an appletviewer will be an advantage for debugging.

136 . - On the other hand applet have the accessibility criteria of the resources. Here are the lifecycle methods of an Applet: init(): This method is called to initialized an applet start(): This method is called after the initialization of the applet. The key feature is that while they have so many differences but both can perform the same purpose. This means that the applet neither can access nor place anything locally. stop(): This method can be called multiple times in the life cycle of an Applet. Applications are designed to exists in a secure area. Introduction Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and destroyed.- Applets are designed just for handling the client site problems.Applet class while the java applications start execution from the main method. Applets are not capable of reading and writing the user's file system. But accessing a remote server is not possible. Applications are not too small to embed into a html page so that the user can view the application in your browser. destroy(): This method is called only once in the life cycle of the applet when applet is destroyed. The conclusion is that the java applets provides a wide variety of formats for program execution and a very tight security model on the open environment as on the Internet. Applets are created by extending the java. while the java applications are designed to work with the client as well as server. Applications and applets have much of the similarity such as both have most of the same features and share the same resources. while the applets are typically used. Applets are not capable of communicating the server than one from which they are originating.applet. There are the cases in which an encryption key is used for the verification purpose for a particular applet to a server.

The init() method is basically called to read the PARAM tag in the html file. Start () method: The start method of an applet is called after the initialization method init(). For Example if the user wants to return to the Applet. in this situation the start Method() of an Applet will be called by the web browser and the user will be back on the applet. For example the stop() method is called by the web browser on that time When the user leaves one applet to go another applet and the start() method is called on that time when the user wants to go back into the first program or Applet. There is only miner difference between the start() method and stop () method. destroy() method: The destroy() method is called only one time in the life cycle of Applet like init() method. Java-compatible browsers ignore this extra HTML code. alternateHTML If we use this <applet> tag in an HTML page to be viewed by the browser. Applets read user-specified values for parameters with the getParameter() method. probably the browser will ignore the <APPLET> and <PARAM> tags that doesn't understand the <APPLET> tag. - < PARAM NAME = appletParameter1 VALUE = value > The only way to specify applet-specific parameters is to use the <PARAM> tags.- init () method: The life cycle of an applet is begin on that time when the applet is first loaded into the browser and called the init() method. This method may be called multiples time when the Applet needs to be started or restarted. Stop () method: The stop() method can be called multiple times in the life cycle of applet like the start () method. Or should be called at least one time. The init() method is called only one time in the life cycle on an applet. The init () method retrieve the passed parameter through the PARAM tag of html file using get Parameter() method After the initialization of the init() method user can interact with the Applet and mostly applet contains the init() method. In the start method user can interact within the applet. Instead of interpreting any other HTML code between the <APPLET> and </APPLET> tags. This method is called only on that time when the browser needs to Shut down. 137 .

The two steps of passing parameters to applets are: 1. Moreover all parameter values are converted to strings. Don't forget that the parameter names are case-sensitive when passing parameters to applets.awt.*. This function is commonly called in the applet's init() method. 2. These parameters allow the user to customize the applet's operation. Parameters are to applets what command-line arguments are to applications.40. import java. It run on the java enabled web browser such as Netscape navigator or Internet Explorer. public class FirstApplet extends Applet{ public void paint(Graphics g){ g. The method syntax is the following: String getParameter(String name).drawString("Welcome in Java Applet. making the applet work in multiple situations without recoding and recompiling it. import java. add necessary code to the applet to retrieve these parameter values. by defining the parameters. APPLET parameters stored in the PARAM tag actually have little directly to do with HTML. We can increase the applet's flexibility.20).applet. It is the responsibility of the applet to check the parameter values and respond accordingly. Lets see how to Pass Parameters to the Applet <PARAM NAME=param_name VALUE=param_value> Retrieving Parameters Within the Applet Introduction An applet is a program written in java programming language and embedded within HTML page. } } 138 . Second. add the PARAM tag (with values) to the HTML source file.<APPLET> Tag Parameters: The <PARAM> Tag These are the parameters passed directly to a Java applet.*. First. These parameter values are retrieved by Java applets using the getParameter() method.".

int X_to_coordinate.awt. Graphics.class" WIDTH="800" Java .drawString() :The drawSring() method draws the given string as the parameter. The Applet class is a super class of any applet.Drawing Shapes Example in java Introduction Applet is a program to run on the browser and it is embedded on the web page. Graphics. Here is the syntax of the drawOval() method : g. int Y_coordinate.*. int Y_to_coordinate).Here is the HTML code of the program: <HTML> <HEAD> </HEAD> <BODY> <APPLET ALIGN="CENTER" HEIGHT="500"></APPLET> </BODY> </HTML> CODE="FirstApplet. Graphics. int Y_from_coordinate. int Wdth. package have been used to draw the appropriate shape.drawLine():The drawLine() method has been used in the program to draw the line in the applet.drawOval():The drawOval() method draws the circle. Here is the syntax of the drawRect() method : : 139 . int Y_coordinate). There are different types of methods for the Graphics class of the java. int X_coordinate.drawOval(int X_coordinate. Graphics.drawRect() The drawRect() method draws the rectangle. This program is not system level program but it is a network level program. int height). Here is the syntax for the drawLine() method drawLine(int X_from_coordinate. Here is the syntax of the drawString() method : drawString(String string. Applet viewer is used to view or test the applet whether the applet is running properly or not.

y=100. int Wdth.*.100).color_name).class" WIDTH="800" HEIGHT="500"></APPLET> </div> </BODY> </HTML> Java . int Y_coordinate.drawRect(int X_coordinate. 140 . This method sets the color for the object by specified color.200. package.g.r=50.100. g.drawOval(x-r.color_name).awt.100).drawString("Rectangel". g.300.450.applet. public class CircleLine extends Applet{ int x=300.100).fillColor(Color.50. public void paint(Graphics g){ g.fillOval() : This is the fillOval() method used to fill the color inside the oval by specified color. g. } } Here is the HTML code of the program: <HTML> <HEAD> </HEAD> <BODY> <div align="center"> <APPLET CODE="CircleLine.100). g.y-r.drawString("Line". Graphics.Drawing Shapes Example using color in java Introduction Graphics.drawLine(3. Here is the syntax of the setColor() method : g. import java. g.setColor() : This is the setColor() method which is the Graphics class method imported by the java.100).*.10). Here is the syntax of the fillColor() method : g.200.awt.100.drawString("Circle".setColor(Color.drawRect(400. int height) import java.275.*.

int Y_coordinate. g. Here is the syntax of the fillRect() method : g.100. 141 .100). //Fill the yellow color in circle g. g. So.applet.setColor(Color.y-r.200.red).10).100).yellow).Graphics.class" WIDTH = "800"> HEIGHT = Applet –Passing Parameter in Java Applet Introduction Java applet has the feature of retrieving the parameter values passed from the html page.magenta).*. } } Here is the HTML code of the program: <HTML> <HEAD> </HEAD> <BODY> <div align="center"> <APPLET ALIGN = "500"></APPLET> </div> </BODY> </HTML> "CENTER" CODE = "ShapColor.275. public class ShapColor extends Applet{ int x=300.300.200. 200.fillRect() : This is the fillRect() method used to fill the color inside the rectangle by specified color.setColor(Color. //Fill the yellow color in rectangel g.*.450. public void paint(Graphics g){ g.100.100).fillRect(int X_coordinate. //Drawing line color is red g. int Wdth. g.fillOval( x-r.setColor(Color.y=100. g.drawRect(400. you can pass the parameters from your html page to the applet embedded in your page.magenta). import java.drawString("Circle". g.drawString("Line". 100 ).50.y-r. int height) import java. 100. g.fillRect( 400.awt.yellow). 50.r=50.setColor(Color.drawString("Rectangel". 100 ).100).drawLine(3. g.magenta). g.setColor(Color.setColor(Color.100).drawOval(x-r. g. g.

getParameter("Message").getParameter("Message").*. 25).drawString(strParameter. we prints the parameter value to test the value passed from html page. In this example. a example is given below.awt. we will see what has to be done in the applet code to retrieve the value from parameters."> </APPLET> </BODY> </HTML> 142 . g." message. Here is the code for the Java Program : import java.applet. code: String strParameter = this. For the illustration about the concept of applet and passing parameter in applet. if (strParameter == null) strParameter = strDefault. import java. Applet will display "Hello! Java Applet" if no parameter is passed to the applet else it will display the value passed as parameter. Value of a parameter passed to an applet can be retrieved using getParameter() function. 50. public void paint(Graphics g) { String strParameter = this. public class appletParameter extends Applet { private String strDefault = "Hello! Java Applet.class" width="800" height="100"> <PARAM name="message" value="Welcome in Passing parameter in java applet example.- The param tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. E.".*. Printing the value: Then in the function paint (Graphics g).g. In our case applet should display "Welcome in Passing parameter in java applet example. } } Here is the code for the html program : <HTML> <HEAD> <TITLE>Passing Parameter in Java Applet</TITLE> </HEAD> <BODY> This is the applet:<P> <APPLET code="appletParameter.

go to command prompt and type appletviewer appletParameter.exit() function to terminate you web browser.swing. Compile the program : javac appletParameter. extended. They are also prevented from starting other programs on the client. A web browser uses only one class loader that’s established at start up. But if it can define native method calls then that would give the applet direct access to underlying computer • • • What is Java Swing? The Java Swing provides the multiple platform independent APIs interfaces for interacting between the users and GUIs components. 143 . Applet is not allowed to create the reference of their own class loader.class file. - Security Issues with the Applet Some security issues to applet are following : • Applets are loaded over the internet and they are prevented to make open network connection to any computer. package. All Java Swing classes imports form the import javax.html Appletviewer will run the applet for you and and it should show output like Welcome in Passing parameter in java applet example.- There is the advantage that if need to change the output then you will have to change only the value of the param tag in html file not in java code. replaced.java Output after running the program : To run the program using appletviewer. They cant load the libraries or define the native method calls.*. Then the system class loader can not be overloaded. overridden. Alternatively you can also run this example from your favorite java enabled browser. Because the html page come from the host or the host specified codebase parameter in the applet tag. Applets are loaded over the net. Applets are not allowed to invoke any program to list the contents of your file system that means it cant invoke System. except for the host. And they are not allowed to manipulate the threads outside the applets own thread group. which provided the . with codebase taking precedence.

JComboBox. combo boxes. ListCellRenderer This interface used for paint the cell in the list with the help of "rubber stamps" . checkboxes. ComboBoxModel This interface represents the data model in a list model with the selected items. buttons. BoundedRangeModel This interface defines the data model of components like: sliders and progressBars. The JInternalFrame implements in the JDesktopPane with the help of DesktopManager. ButtonModel It defines the state model for the buttons like: radio buttons. ComboBoxEditor In this interface. The Java Swing supports the plugging between the look and feel features. ListSelectionModel This interface indicates the components. JDialog etc. which are stable or not. DesktopManager This interface has JDesktopPane object. CellEditor This interface used by the developer for creating the new editor and it has the new components implement interfaces. Interfaces Action Descriptions This interface performed the action with the ActionListener where the multiple controls are used for same purposes. Icon This interface used to graphical representation of the components. ListModel This interface used for JList components method.KeySelectionManager This interface has KeySelectionManager and used for the combo box data model. for viewing it into the several types of window. It gets the value of each cell of list. panels and sliders etc. check boxes etc. JWindow. The CellEditor implements the wrapper based approach. It has fixed size picture. MenuElement This interface used where the any components are 144 . The look and feel that means the dramatically changing in the component like JFrame. All AWT flexible components can be handled by the Java Swing. the editor component used to JComboBox components.- Java provides an interactive features for design the GUIs toolkit or components like: labels. Here the following APIs interfaces and classes are available: The following interfaces and it's descriptions to be used by the Java swing. text boxes.

MutableComboBoxModel Renderer RootPaneContainer Scrollable ScrollPaneConstants SingleSelectionModel SwingConstants UIDefaults. The following classes and it's descriptions to be used by the Java swing. This class defines the nature of buttons and menu items. It provides a list and contents of the data model. This interface has two methods setDefaultCloseOperation and getDefaultCloseOperation and provides the window close opration. 145 .createValue() method. This interface uses the RootPane properties and it has the components like: JFrame. This class extends from Object and creates the Border instance in the factory.ActiveValue UIDefaults. Classes AbstractAction AbstractButton AbstractCellEditor AbstractListModel ActionMap BorderFactory Box Descriptions This class handles the any types of action and provides JFC Action interface. This class works with InputMap and performs any action when the key is pressed.LazyValue WindowConstants implements in the menu. This interface used to select the one index in a model. This interface provides the scrolling to show the large amount of data with the help of JScrollPane. JInternalFrame and JWindow etc. It constructs the DefaultListCellRenderer. It is a mutable version of ComboBoxModel. It defines the requirements of an object for displaying the values. It provides the fixed spaces between two components and uses the BoxLayout object of the layout manager. This class defines the data model which provides the list with its contents. This enables one to store an entry in the default table. This interface extends from the ComboBoxModel. The entered value is not constructed until first time is a real value is created through it using LazyValue. This interface used for JScrollPane components. You can set the components on the screen to own requirements.

DefaultButtonModel This class implements the generic ButtonModel.UIResource This extends the DefaultListCellRanderer and implementing in the UIResource. DebugGraphics It extends from the Graphics and used to debug the graphics DefaultBoundedRangeModel This class provides the implementation of default BoundedRangeModel. JTable and JTree. DefaultListModel It extends the AbstractListModel and implementing the java. DefaultSingleSelectionModel This class provides the default SingleSelectionModel. CellRandererPane This class used to insert the components like: JList. ImageIcon This class implements the Icon and paints the icons from the images. It bounds data between the input event and an object. The Box container uses this class.Vector. FocusManager It handles all focus like: gainedFocus and lostFocus. DefaultListCellRanderer It implements the default ListCellRanderer. InputMap This class uses the ActionMap to performed the action when you press any key of keyboard. GrayFilter It extends the RGBImageFilter and used for disabling the image through the button.Filler This class participates in the Layout and uses the lightweight components. DefaultCellEditor It implements the TableCellEditor and TreeCellEditor for the table and tree cells. 146 . ComponentInputMap This class has ComponentInputMap constructor and creates the components with the help of InpuMap. DefaultListCellRanderer. The DesktopManager has the JInternalFrame for creating the internal fame in a frame.Box. ButtonGroup This class used to create the multiple buttons in a ButtonGroup object.util. BoxLayout This class uses the arranging the multiple components either horizontally or vertically. DefaultDesktopManager It implements the DesktopManager. DefaultComboBoxModel It provides the default model for combo boxes. DefaultListSelectionModel This class used for select the list in a data model. DefaultFocusManager It provides the implementing the FocusManager.

The JInternalFrame added into the JDesktopPane. This class extends the Applet and implements the Accessible and RootPaneContainer. you choose and manipulate the colors. It has JFC/Swing container that can be used to 147 . But combo box is a combination of multiple text or buttons etc. It provides the drop-down list where user select only one item or value at a time. This class extends the JToggleButton and implements the check box in which buttons are selected or deselected. It edits the component by the EditorKit. This class provides the facility to choosing the file. Here. closing. All components are used the JComponent except the top-level containers like: JFrame. resizing and menu bar of the internal frame. JDialog etc.InputVerifier JApplet Jbutton JCheckBox JCheckBoxMenuItem JColorChooser JComboBox JComponent JDesktopPane Jdialog JEditorPane JFileChooser Jframe JInternalFrame JInternalFrame. It extends the Frame and supports the swing components architecture. This class used to create the dialog window and when you want to create the custom dialog window with the help of JOptionPane method. The JDesktopPane has DesktopManager. It extends the JMenuItem and determines the items which is selected or deselected. This class extends from the JComponent and provides the facility to dragging. This class used to show the small text and image. It extends the JComponent and implementing the Accessable. This class extends the AbstractButton and you can create the new button. It extends the Dialog. This class extends the JTextComponent. In java swing. It displays the desktop icon and create the instance of JInternalFrame and iconify. This class extends the JLayeredPane and when you create the object of JInternalFrame to be maintained in the JDesktopPane.JDesktopIcon Jlabel JLayeredPane This class helps you when you works with the text fields through the focus. This class extends the JComboBox.

It implements the radio button and shows the state of an item selected or deselected. for providing the task-orientation and functionality. don't available the original characters but view type indication characters are available. It extends the JMenuItem and implements the radio button menu item This class provides the component behind the scenes by JFrame. Here the popup menu and the separator are available. It extends the JComponent and used to create a new panel. error dialog box etc. It provides small window where the various types of choices are available. It provides the view content area where you show the content to scroll this. This class provides a control to represent a numeric value by dragging the slider. It used to create a new menu bar where the JMenu objects are added. It provides the scrollable view components. This class use the separator among the components. This class used to divides the two components graphically like: top and button. It used to create some different types of dialog box like: message dialog box. This class used to create a popup menu. This class used to create a list where you select the one or more than objects. JWindow. It provides the single line text editing. When you select the item then shows the popup menu items in the JMenuBar. This class used to create a scroll bar. It shows the integer types values in percent within a bounded range to determine the working process. This class used to create a new menu where you add the JMenuItems. JDialog etc.Jlist Jmenu JMenuBar JMenuItem JOptionPane Jpanel JPassworkField JPopupMenu JPopupMenu. 148 .Separator JProgressBar JRadioButton JRadioButtonMenuItem JRootPane JScrollBar JScrollPane JSeparator Jslider JSplitPane overlap the components to each other. This class used to create new menu items in the mebus. left and right. Here.

JTextArea It provides the multi line plain text area. JTree.ToggleButtonModel It extends the DefaultButtonModel and provides the ToggleButton model.JTabbedPane This class provides the tab component through which you can switch from one component to another component regarding to the specific tab button by clicking on that. JToolBar. JViewPort It gives you about the underlying information. LayoutFocusTraversalPolicy This class conducts the sorting objects according to their size. JToolBar It provides set of command buttons icons that performs the different actions or controls. ProgressMonitorInputStream This class creates a progress monitor to monitor the progress of reading input from the input stream. position or orientation. It cleanups all the rights when the stream 149 . type. JToolTip It shows the tool tips related to it's components. JToggleButton It implements two state button that means selected or deselected. JTextPane This class provides the component like JTexArea for multiple lines text with more capabalities. Jtree It shows the data in a hierarchical way. LookAndFeel It provides the dramatically changes in the component like frame related to the graphics for the application. MenuSelectionManager It has menu selection hierarchy. JTextField It provides the facility to editing the text in a single line. JToggleButton. JWindow It extends window and shows the any location or area on the desktop. KeyStroke This class controls the key events on the keyboard for the equivalent device. It couldn't any title bar and window management buttons. JTree.Separator It provides the tool bar separator.DynamicUtilTreeNode This extends the DefaultMutableTreeNode and create children nodes. Jtable It provides the user interface component and represents the two dimensional data. OverlayLayout The layout manager arrange the components.EmptySelectionModel It does not allows the any selection. ProgressMonitor This class is used to monitoring the progress of any operation to be done. Through this the application can be done very efficient and easier.

It implements the LayoutManager and defines the policy for the layout. Example of binding of key is array of pressing key information (e. It extends the ScrollPaneLayout and implements the UIResource. This class has track of the current look and feel details.RepaintManager ScrollPaneLayout ScrollPaneLayout.ProxyLazyValue UIManager UIManager.LookAndFeelInfo ViewportLayout is closed. This class manage and override the repaint requests.LazyInputMap UIDefaults. This class has utilities methods for swing. This is the nested class of UIManager class i. It implements the LayoutManager and manage the components like: scroll bar. column header etc.e. Descriptions This exception occurred when the look and feel UnsupportedLookAndFeelException classes are not supported to user's system. This class creates a Input Map through it's createValue() method.UIResource SizeRequirements SizeSequence SwingUtilities Timer ToolTipManager UIDefaults UIDefaults. Exception 150 . row header. It extends the Hashtable and you set/get the value with the help of UIManager. The array of key after binding is passed to the constructor of this. Actions perform the predefined rate. ctrl + c or alt + f). used for getting information about all the look and feels installed with the software development kit.g. It represents the order list of size and it's positions. It manages the all tool tips. The following Exceptions and it's description to be used by the Java swing. This class is used to create a lazy value which is used to delay loading of the class to create instance for that. It calculates the size and positions of components.

400). The frame initially are not visible and to make it visible the setVisible(true) function is called passing the boolean value true.setVisible(true).*. For creating java standalone application you must provide GUI for a user. frame.swing.setDefaultCloseOperation(JFrame. The most common way of creating a frame is. import javax. In this example we have changed this behavior to window close operation by setting the setDefaultCloseOperation() to EXIT_ON_CLOSE value. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE). The close button of the frame by default performs the hide operation for the JFrame.EXIT_ON_CLOSE): Above code sets the operation of close operation to Exit the application using the System exit method. setSize (400. Other user interface are added by constructing and adding it to the container one by one.Creating a Frame : Swing Tutorials In the Java Swing.setSize(400. setVisible(true): Above method makes the window visible. top-level windows are represented by the JFrame class. frame. } } 151 . frame. The argument of the constructor is the title of the window or frame. Java supports the look and feel and decoration for the frame. 400): Above method sets the size of the frame or window to width (400) and height (400) pixels. using single argument constructor of the JFrame class. public class Swing_Create_Frame{ public static void main(String[] args){ JFrame frame = new JFrame("Frame in Java Swing").

This way of inputting or outputting works very efficiently in the Swing Applications.Swing Dialogs Message dialog box is used to display informative messages to the user. The JOptionPane class has three methods as follows: • showMessageDialog(): First is the showMessageDialog() method which is used to display a simple message. The window for showing message for input or output makes your application very innovative. "No" and "Cancel" 3.*. "Ok".in class for input or output some text or numeric values but now in the swing application we can use JOptionPane to show the output or show the message. JOptionPane class is available in the javax.e.) "Ok".) "Yes".swing. 152 .) "Yes" and "No" 2. A message dialog box which has two or three buttons.Show Dialog Box in Java . Our program display "Click Me" button on the window and when user clicks on it program displays Message box with "OK" button and message "Welcome". This type of message dialog box is used only for showing the appropriate message and user can finish the message dialog box by clicking the "Ok" button. Program description: JOptionPane Class: In non-swing application we were using System. In this section we will use JOptionPane class to display the message Dialog box. and "Cancel" A input dialog box which contains two buttons "Ok" and "Cancel". package. You can set several values for viewing several message dialog box as follows: 1. This class provide various types of message dialog box as follows: • • • • • A simple message dialog box which has only one button i.

import java.event. If you click on the "Yes" button then the method returns 1 otherwise 0. This method return a numeric value either 0 or 1. } } } Swing Input Dialog Box Example . } public class MyAction implements ActionListener{ public void actionPerformed(ActionEvent e){ JOptionPane. } public ShowDialogBox(){ frame = new JFrame("Show Message Dialog"). button.setDefaultCloseOperation(JFrame."Welcome").*.• • showInputDialog(): Second is the showInputDialog() method which is used to display a prompt for inputting. How program Works: This program illustrates you how to show a message dialog box when you click on the button.EXIT_ON_CLOSE). public class ShowDialogBox{ JFrame frame. frame. frame. showConfirmDialog(): And the last or third method is the showConfirmDialog() which asks the user for confirmation (Yes/No) by displaying message.setSize(400. 400). This is being used with two arguments in the program where the first argument is the parent object in which the dialog box opens and another is the message which has to be shown.awt. import javax.showMessageDialog(frame.setVisible(true). showMessageDialog(): This method is used to show a message dialog box which contains some text messages.add(button).addActionListener(new MyAction()).Swing Dialogs 153 .swing. frame. public static void main(String[] args){ ShowDialogBox db = new ShowDialogBox(). This method returns a String value which is entered by you. JButton button = new JButton("Click Me").*. frame.

in for inputting anything from user.e.add(panel).showMessageDialog(null. import java. "You entered the text : " + str. 400).event. this shows a button labeled by "Show Input Dialog Box" on the frame. frame.". " Welcome ".*. } } Drawing with Color in Java drawRect(): This is the method of the Graphics class (The Graphics class is used to drawing different-different type of shapes).awt. Here is the code of the program: import javax.- Input dialog box is very important and interactive feature of Java Swing. "You pressed cancel button. first is the "Ok" button and another is the "Cancel" button When you run the given program. Welcome ". frame. "Enter some text : ".add(button).swing.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ String str = JOptionPane.EXIT_ON_CLOSE).setVisible(true).setDefaultCloseOperation(JFrame. frame. JPanel panel = new JPanel(). the Input Dialog Box. " Welcome ". 1).showMessageDialog(null. } }).*. Java Swing provides the facility to input any thing (whether the text or the numeric values) in a normal window i. You have been using the System. public class ShowInputDialog{ public static void main(String[] args){ JFrame frame = new JFrame("Input Dialog Box Frame"). The input dialog box contains two buttons. JButton button = new JButton("Show Input Dialog Box"). button. If you click on the "Ok" button of the input dialog button then a message dialog box is seen which has the message "You entered the text : entered_text" otherwise it will display a message dialog box that has the message "You pressed cancel button.setSize(400. 1). This method draws the rectangle. panel. if(str != null) JOptionPane. It takes some integer 154 .". If you click on the button then a input dialog box will open.showInputDialog(null. frame. 1). else JOptionPane.

height. fillRect(): This is the method of the Graphics class which is used to fill rectangle with the specified color which is set before using the setColor() method of the Graphics class.setDefaultCloseOperation(JFrame.This is the variable represents the row no. g. In this method first come the width and then height is specified. 155 .red).11. height.19.red). g.setSize(400.gray).drawOval(250. frame.*.400). width).height. x .setColor(Color.add(new MyComponent()).fillOval(249. g.drawRect(x. or the x . frame. drawOval(): This is the method of the Graphics class which draws the oval on the frame.value as parameter.EXIT_ON_CLOSE). fillOval(): This is also the method of the Graphics class which is used to fill the oval with color specified in the setColor() method before. import java. frame. g.awt.height.width).width).This is also a variable represents the column no. y . } public class MyComponent extends JComponent{ public void paint(Graphics g){ int height = 200.. Here is the code of program: import javax.magenta).setColor(Color.coordinate.setVisible(true). g. frame. public class DrawingColor{ public static void main(String[] args) { DrawingColor d = new DrawingColor().coordinate. height.width).fillRect(11. It also takes argument same as the drawRect() method. int width = 120.20. g. } public DrawingColor(){ JFrame frame = new JFrame("Drawing with Alpha"). or the y . y.*.drawRect(10. This method takes argument same as the drawRect() method.10. g.setColor(Color. This method is written like : Graphics. g.getContentPane().setColor(Color. This method also takes argument same as the drawOval() method.swing.width).

add(chk). This program displays a simple combo box on the frame which contains multiple items like: BCA.setDefaultCloseOperation(JFrame. MCA.} } } Creating Check Box in Java Swing This section illustrates you how to create a Check Box component in Java Swing. Combo Box can be whether editable or only non-editable means only readable. In this section. is added to the frame using the add(component) method of the JFrame class.swing. you will learn about the JComboBox Component of swing in java. public class CreateCheckBox{ public static void main(String[] args){ JFrame frame = new JFrame("Check Box Frame"). you can learn simply creating the Check Box in Java Swing.*. frame. Here is the code of the program: import javax. This component of the javax. PPC etc.setSize(400.setVisible(true). The JComboBox is used to display drop-down list. It provides you options to select an item from the item list. frame.*. Check Boxes are created in swing by creating the instance of the JCheckBox class using it's constructor which contains the string which has to be shown beside the check box on the frame or window like this: This is written like: JCheckBox chk = new JCheckBox("This is the Check Box"). 400). JCheckBox chk = new JCheckBox("This is the Check Box"). You can never select more than one items from a combo box.swing. The background color of this combo box is gray and 156 . } } Create a JComboBox Component in Java In this section. frame. frame.EXIT_ON_CLOSE).

gray).setVisible(true).setDefaultCloseOperation(JFrame.foreground color is red. combo. frame. When you select the item from the combo box then the selected item is displayed in the text box. import java.setText(str).red). frame.add(panel). JPanel panel = new JPanel(). frame. public static void main(String[] args) { ComboBox b = new ComboBox(). combo. public class ComboBox{ JComboBox combo.*.awt. combo."PPC". frame.add(combo). panel. panel.awt."MCA". JTextField txt. Here is the code of program: import javax. Image of the result for the given program is as follows in the pictorial form: APIs used in the program: JComboBox: This is the class which is used to create a combo box in swing using it's constructor.add(txt).EXIT_ON_CLOSE).400).swing.*. itemStateChanged(): This is the method which receives the ItemEvent generated by the addItemListener() method of the JComboBox class.setForeground(Color. } } 157 .setBackground(Color. the background color of the combo box and the foreground color is set using the setBackground(Color) and setForeground(Color) method of the JComboBox class."CIC"}. txt = new JTextField(10). } public ComboBox(){ String course[] = {"BCA".addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent ie){ String str = (String)combo. Here.event.getSelectedItem(). The event is generated when you select item from the combo box. import java. } }).*. txt.setSize(400. JFrame frame = new JFrame("Creating a JComboBox Component"). combo = new JComboBox(course).

package. This program shows a text field.swing. The above code has been used to create a combo box in this program. This specification of position the item in the combo box is held by the getItemAt() method as a parameter. addItem(String): This is the method of the JComboBox class which adds items to the combo box. getItemCount(): This is the method of the JComboBox class which return the number of the items present is the combo box. you will learn how to add items to the combo box. removeItemAt(index): This is the method of the JComboBox class which remove the item at the specified 158 .Combo Box operation in Java Swing In this section. remove items from the combo box.". a combo box and two command buttons.*. package. Following is the image for the result of the given program: This program has used various java APIs for doing required are explained as follows: JComboBox combo = new JComboBox(items). This method holds two argument in this program in which first is the parent object name and another is the message text which has to be displayed. first is for the adding items to the combo box and another is for the removing items from the combo. This constructor holds the string array in which items for the combo box are kept. This method displays some messages in the special dialog box. This method takes a string argument which is to be used to add to the combo box. you can learn how to operate the Combo Box component.swing.*. When you click on the add command button then the text of the text box is added to the combo box if the text box is not blank otherwise a message box will display with the message "Please enter text in Text Box". The JComboBox instance combo is created using the constructor of the JComboBox class of the javax. But when you click on the remove button the item at the 0th (zero) position of the combo box will be remove from the combo box if the combo box has one item at least otherwise a message box will display with the message "Item not available. getItemAt(index): this is the method of the JComboBox class which returns the name of the item of the combo box at the specified position. showMessageDialog(): This the method of the JOptionPane class of javax.

")."Combo has already this item.*. } } if (a == 1) JOptionPane. i++){ if(combo. button1. "JSP".swing.equals("")){ int a = 0. else combo.showMessageDialog(null. "PHP". JPanel panel1 = new JPanel(). public static void main(String[] args){ AddRemoveItemFromCombo ar = new AddRemoveItemFromCombo(). txtBox = new JTextField(20)."Please enter text in Text Box").add(txtBox).getItemAt(i).getItemCount(). JPanel panel = new JPanel(). This method holds the integer value for the position number of he of the item in combo box to remove it.getText(). } else{ JOptionPane.getItemCount() > 0) combo.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if (!txtBox. break. JButton button1 = new JButton("Add").equals(txtBox. panel. "C".*.showMessageDialog(null.showMessageDialog(null. String items[] = {"Java".event.position of the combo box. button2.removeItemAt(0).add(combo). panel."Item not available"). } public AddRemoveItemFromCombo(){ JFrame frame = new JFrame("Add-Remove Item of a Combo Box"). "C++"}. JTextField txtBox. Here is the code of the program: import javax.getText())){ a = 1. import java. } } }). 159 . } }).addItem(txtBox. i < combo.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if (combo. for(int i = 0. public class AddRemoveItemFromCombo{ JComboBox combo.getText()). panel. else JOptionPane. JButton button2 = new JButton("Remove"). combo = new JComboBox(items).add(button1).awt.

*. This is class is used by creating a instance of if using it's constructor.EXIT_ON_CLOSE). which is used to create a group of radio buttons from which you can select only one option from that group of the radio buttons. you will learn how to create a radio button in java swing. If you pass true value then the radio button will be selected otherwise the radio button is not selected.add(panel1). frame.setDefaultCloseOperation(JFrame. Following is the image for the result of the given program: The creation of JRadioButton are completed by the following methods: ButtonGroup: This is the class of the javax.setSize(400. frame. 160 . This method takes a boolean value either true or false. package. Radio Buttons are added to the specified group using the add(JRadioButton) method of the ButtonGroup class. frame. setSelected(): This method sets the value of the radio button. Radio Button is like check box.swing.setVisible(true). frame. You can select only one radio button at once from a group of the radio button. frame. 2. JRadioButton: This is the class has been used to create a single radio button for the application. You can check or uncheck the check box but you can on check the radio button by clicking it once. you will see the JRadioButton component creation procedure in java with the help of this program.add(panel). This example provides two radio buttons same ButtonGroup.add(button2). You can checks multiple check boxes at once but this can never done in the case of radio button. } } Create a JRadioButton Component in Java In this section. Differences between check box and radio button are as follows: 1. 400).// panel. 3. Check Boxes are separated from one to another where Radio Buttons are the different-different button like check box from a same ButtonGroup. Here. These radio buttons represent the option for choosing male or female.

frame. buttonGroup. } public CreateRadioButton(){ JRadioButton Male. JPanel panel = new JPanel().setSize(400. You can enter the item name in the text box and click on the "Add" button.add(panel).setSelected(true). This text show the information about that component. frame. JFrame frame = new JFrame("Creating a JRadioButton Component").Here is the code of program: import javax.awt.*. you can add more and more items.*. Male = new JRadioButton("Male"). Male. In this program. panel.add(Female).Female.400). public class CreateRadioButton{ public static void main(String[] args) { CreateRadioButton r = new CreateRadioButton(). frame.add(Female). it shows the specific item name as a tool tip text like the following image: 161 . frame. you will learn how to set the tool tip text for items present in the JList component of the Java Swing.EXIT_ON_CLOSE). panel. ButtonGroup buttonGroup = new ButtonGroup(). buttonGroup.add(Male). Tool Tip text is the help text of any component for user. When you rest the mouse cursor on the component then at that point a message which small font and yellow background stay there for few seconds.setVisible(true). } } Setting Tool Tip Text for items in a JList Component In this section. This program has used the tool tip text for items present in the JList component in Java Swing.swing. import java.add(Male). When you move the mouse pointer around the items in the list.setDefaultCloseOperation(JFrame. Female = new JRadioButton("Female").

This class is used to create a list model which is helpful for adding items for the list.*. Here is the code of the program: import javax.awt.Following are some methods and APIs are explained as follows: JScrollPane: This is the class of javax.swing. getModel(): This is the method of JList class which holds the list of item which are shown in the JList component of Java Swing.*. This class has used own method to add items in the list.awt.*. as parameter. It returns the list model. It creates scroll bar using it's constructor which holds the component name for which the scroll bar has to be created.event. DefaultListModel: This is the class of javax. package of Java. import java. addElement(String): This is the method of DefaultListModel class which adds the item into the list. This program has used this for creating scroll bar for the text area.swing. This class is used to create scroll bar (Horizontal or Vertical) for any component. import java.swing. package of Java.*. getElementAt(index): This is the method of DefaultListModel class which gets the item from the returned list model by getModel() method according to the given integer index no.multi.*. locationToIndex(): This is the method of the MultiListUI class which is imported from the javax. 162 . This method takes a integer value for locating item from the list according to the given point. package of Java Swing. This method locate the item to the index where the mouse pointer points.swing.plaf.*.

getElementAt(index).addElement(data). panel. JButton button = new JButton("Add"). panel. frame. model = new DefaultListModel(). else{ model.add(panel. frame.CENTER).add(txtItem). } public TooltipTextOfList(){ JFrame frame = new JFrame("Tooltip Text for List Item"). txtItem = new JTextField(10).setSize(400. i++) model. button. panel. } public class MyAction extends MouseAdapter implements ActionListener{ public void actionPerformed(ActionEvent ae){ String data = txtItem. JTextField txtItem. return item.EXIT_ON_CLOSE). JOptionPane. list = new JList(model){ public String getToolTipText(MouseEvent e) { int index = locationToIndex(e. frame. } } } } Disabling Keyboard Editing in a JSpinner Component 163 .getText(). BorderLayout."). 400). String[] str_list = {"One". if (data."Item added successfully.").add(list).setVisible(true).length. txtItem.equals("")) JOptionPane.add(button). DefaultListModel model. "Four"}."Please enter text in the Text Box.getPoint()). i < str_list.showMessageDialog(null.setDefaultCloseOperation(JFrame. } } }. "Two". if (-1 < index) { String item = (String)getModel().setText(""). public static void main(String[] args){ TooltipTextOfList tt = new TooltipTextOfList(). for(int i = 0. } else { return null. JList list. "Three".showMessageDialog(null.addElement(str_list[i]).public class TooltipTextOfList{ private JScrollPane scrollpane = null.addActionListener(new MyAction()). JPanel panel = new JPanel(). frame.

swing.setEditable(false). The JSpinner component. frame.*. BorderLayout. Through the given program you can only increase and decrease the value nor write the value directly in the Spinner component of java. You can increase it's value by clicking up and down button. 164 .setSize(400.add(spinner). Here is the code of the program: import javax.NORTH).DefaultEditor)spinner.In this section. frame. The Spinner has been disabled for editing using setEditable() method.*. tf.swing. This method is used to get the editor which has been using for the JSpinner component.getTextField(). the syntax is written like: JFormattedTextField tf = ((JSpinner. JFormattedTextField tf = ((JSpinner. This is defined in the JSpinner. getTextField(): This method creates a JFormattedTextField for edit in the specified format. package which creates formatted text field for edit text in the specified format. public class DesableEditingSpinner{ public static void main(String[] args){ JFrame frame = new JFrame("Desabling editing Spinner"). JPanel panel = new JPanel(). getEditor(): This is the method of JSpinner class. which is disable for the keyboard editing looks like the following image: In this program. spinner. 400).getEditor()).*.DefaultEditor)spinner.add(panel. Some following methods and APIs are explained as follows: JFormattedTextField: This is the class of javax. panel.awt.setValue(new Integer(100)). For creating a JFormattedTextField. import java.getTextField().DefaultEditor class. a Spinner component has been created and set for editing mode of the Spinner. JSpinner spinner = new JSpinner().getEditor()) . you will see how to create a non editable Spinner component of Java Swing.

Methods and APIs are as follows: JSlider: This is the class which creates the slider for the swing application. There is minimum chances of being mistake to illegal input values. JSlider Component of Java Swing In this section. If you increase or decrease the slider by selecting then the actual position of the slider will be displayed on a label.} } frame. you will learn how to create a JSlider component of Java Swing. some methods and APIs have been used to create a JSlider component and performs various tasks related to the slider.setDefaultCloseOperation(JFrame. frame. events on the JSlider component have also been shown. 165 . ChangeListener: This is the interface of which is used to call stateChanged() method which receives the event generated by the slider using addChangeListener() method of the JSlider class. The figure for the result of the given program is followed below: Before touch the JSlider Component: After drag the JSlider Component: For these purposes.setVisible(true).EXIT_ON_CLOSE). In this program. For creating the slider this class creates a instance using it's constructor JSlider(). A Slider is a Swing tool which you can use for selecting a range. ChangeEvent: This is the class which handle the event generated by the JSlider component on change the state.

panel. label.EXIT_ON_CLOSE). frame.setSize(400. frame. } public CreateSlider(){ JFrame frame = new JFrame("Slider Frame").CENTER).setValue(70). label = new JLabel("Roseindia. java.toString(value). } public class MyChangeAction implements ChangeListener{ public void stateChanged(ChangeEvent ce){ int value = slider.event. String str = Integer. slider.awt. javax.getValue().add(label). public class CreateSlider{ JSlider slider. java.setText(str). Here is the code of the program: import import import import javax. } } } Progress Bar in Java Swing 166 .net").*. slider.swing. 400).*.add(panel.add(slider).swing.setDefaultCloseOperation(JFrame.addChangeListener(new MyChangeAction()).awt. BorderLayout.addChangeListener(object): This is the method of the JSlider class which is used to handle event on change the selected state of the JSlider component. public static void main(String[] args){ CreateSlider cs = new CreateSlider().setVisible(true). JPanel panel = new JPanel().event. frame.*. panel. slider = new JSlider(). frame.*. JLabel label.

first is the initial value of the progress bar which is shown in the starting and another argument is the counter value by which the value of the progress bar is incremented. the value of the progress bar is incremented by 20. Through the given example you can understand how the progress bar is created for showing your work is in progress. This message on the label has been used only for showing in output of the program.event.swing..*. It takes a boolean value as a parameter.. When you click on the "Start" button progress bar is started to progress the completed process in percent and the label which holds the text "Roseindia." in green color and the button is disabled.awt.*. setStringPainted(boolean): This is the method of the JProgressBar class which shows the complete process in percent on the progress bar." in red color and "Start" button is enabled. When the value of the progress bar is become 100% then the label text of the label is changed with the text "Downloading completed. The constructor JProgressBar() takes two argument as parameter in which.swing. Time is started using the start() method of the Timer class. The label display the information about the Downloading process whether completed or not. This section shows you how the progress bar starts and stops with the timer. If you pass the true then the value will be seen on the progress bar otherwise not seen. you can learn how to handle progress bar in java swing. java. But here. Timer(): This the constructor of the Timer class which starts the timer for timing..awt.. setValue(): This is the method of the JProgressBar class which sets the value to the progress bar.. there are some methods and APIs are used in the program has been explained as follows: JProgressBar: This is the class which creates the progress bar using it's constructor JProgressBar() to show the status of your process completion. javax. a progress bar and another is the label which has been used to display some messages. nothing is downloading through the program.*. 167 . This constructor takes two argument as parameter first is the interval (in milliseconds) of the timer and second one is the listener object.*.In this section. For completion the process.net" is change to with the label text "Downloading is in process.html. Here. Here is the code of the program: import import import import java. javax. This program shows you a frame in which a button labeled by the string "Start".text.

JProgressBar pb. 20)).getDefaultToolkit().add(panel. pb = new JProgressBar(0. label = new JLabel("Roseindia. frame.beep().setStringPainted(true). panel.NORTH).setContentPane(panel1). } })." + "</b>" + "</font>" + "</html>". String str = "<html>" + "<font color=\"#008000\">" + "<b>" + 168 .setDefaultCloseOperation(JFrame.setText(str).createEmptyBorder(20.add(pb).setVisible(true).setValue(0). 20. } i = i + 1. pb. } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { button. frame. timer. new ActionListener() { public void actionPerformed(ActionEvent evt) { if (i == 20){ Toolkit. frame.setLayout(new BorderLayout()). JButton button. JPanel panel = new JPanel(). panel1. BorderLayout. //Create a timer.net").CENTER). panel1.setValue(0). button.setEnabled(false).setValue(i). panel1.pack(). int i.setBorder(BorderFactory. 20). frame.stop(). String str = "<html>" + "<font color=\"#FF0000\">" + "<b>" + "Downloading completed. panel1.setEnabled(true). pb. public SwingProgressBar() { JFrame frame = new JFrame("Swing Progress Bar"). button. panel. pb. Timer timer.EXIT_ON_CLOSE).add(label. pb. label. i = 0. JLabel label.addActionListener(new ButtonListener()).add(button). timer = new Timer(interval. button = new JButton("Start"). 20. JPanel panel1 = new JPanel(). BorderLayout.public class SwingProgressBar{ final static int interval = 1000.

menus. you will learn about creation of menus. } } public static void main(String[] args) { SwingProgressBar spb = new SwingProgressBar(). timer. Similarly.start(). For pictorial representation. Here. The Separator divides the menu items in a separate groups like same types of menu Items are divided into a individual parts."Downloading is in process.... submenus and Separators in Java Swing. Menu bar contains a collection of menus. the image for the result of the given program is given below: This program shows how to create menu bar." + "</b>" + "</font>" + "</html>". } } Create menus and submenus in Java In this section.setText(str).. Each menu can have multiple menu items these are called submenu. submenus and Separators.. all items shows on a frame with the help of following methods and APIs: 169 . label. all menus have multiples menu items..

add(fileItem1). JSeparator(): This is the constructor of JSeparator class which adds an extra line between menu items. filemenu. filemenu.add(fileItem4). Here is the code of program: import javax. JMenuItem(String): This is the constructor of JMenuItem class which constructs new menu items for the specific menu. JMenuItem editItem3 = new JMenuItem("Paste").add(fileItem2). JMenuItem editItem1 = new JMenuItem("Cut").*. JMenuItem fileItem2 = new JMenuItem("Open"). filemenu.EXIT_ON_CLOSE). JMenuItem editItem4 = new JMenuItem("Insert"). public class SwingMenu{ public static void main(String[] args) { SwingMenu s = new SwingMenu(). setJMenuBar(): This method is used to set the menu bar to the specified frame. This constructor constructs the new menu. editItem2. } public SwingMenu(){ JFrame frame = new JFrame("Creating a JMenuBar. editmenu. filemenu.add(new JSeparator()). JMenuBar menubar = new JMenuBar().add(editItem1).swing. 170 . JMenuItem and seprator Component"). editmenu.add(fileItem3).add(new JSeparator()). JMenu. JMenuItem fileItem3 = new JMenuItem("Close"). JMenu editmenu = new JMenu("Edit"). JMenuItem editItem2 = new JMenuItem("Copy"). JMenu filemenu = new JMenu("File"). It takes the object of the JMenuBar class. It takes string types value which is the label for the menu item.add(new JSeparator()). It takes the string type value which is the name label for the menu.JMenuBar: This is the class which constructs a menu bar that contains several menus. fileItem3. frame. JMenuItem fileItem1 = new JMenuItem("New"). filemenu.add(new JSeparator()). JMenu(String): This is the constructor of JMenu class. This line. only separates the menu items.setDefaultCloseOperation(JFrame. JMenuItem fileItem4 = new JMenuItem("Save").

add(filemenu).add(editmenu).awt. editmenu. Following figure shows the popup menu when you right click on the frame: This program illustrates you about the creation of the popup menu.add(editItem4). package. editmenu.add(editItem2).setJMenuBar(menubar). Create a Popup Menu in Java Here.*. mouseReleased This is the method of the FormView. Following methods and APIs have been used in this program for getting popup menu: JPopupMenu: This is the class which constructs the popup menu using it's constructor.add(editItem3).MouseEventListener class which is imported from 171 .} } editmenu. menubar. you will learn how to create a Popup menu in Java.event. isPopupTrigger(): This is the method of the MouseEvent class of the java. This method returns true if the event is generated when the popup is triggered. frame. This method returns a boolean type value either true or false. frame.400).setSize(400. Popup menu is the list of menu which is displayed at that point on the frame where you press the right mouse button. menubar. frame.setVisible(true). This class is helpful to add the object of the JMenuItem class which creates a particular menu.

getX(). import java.swing.event. This method returns the source component of the generated event. menuItem = new JMenuItem("Cut"). me. Pmenu. menuItem = new JMenuItem("Delete"). Pmenu. This method receives the generated mouse event when the object is release by clicking the mouse. frame. menuItem = new JMenuItem("Undo").*. getY(): This is also the method of the the MouseEvent class.*.add(menuItem). Pmenu = new JPopupMenu(). public class PopUpMenu{ JPopupMenu Pmenu.add(menuItem). } public PopUpMenu(){ JFrame frame = new JFrame("Creating a Popup Menu").event. Pmenu. frame. This method returns the vertical positions of the y-coordinate for the source component where you click the mouse. public static void main(String[] args) { PopUpMenu p = new PopUpMenu(). JMenuItem menuItem. This method returns the integer type value which is the position on the x-axis for the source component where you click the mouse.getY()): This is the method of JPopupMenu class which displays the popup menu where you press the right mouse button on the specified location or positions.event.awt. me. getComponent(): This is the method of the ComponentEvent class of the java.addMouseListener(new MouseAdapter(){ 172 .*.setDefaultCloseOperation(JFrame. package. package. menuItem = new JMenuItem("Copy"). getX(): This is the method of the MouseEvent class which is imported from the java.swing.*.awt. Here is the code of program: import javax.text.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){} }).html. menuItem.awt.add(menuItem).*.EXIT_ON_CLOSE).add(menuItem).the javax.getComponent().add(menuItem). This positions calculated by the getX() and getY(). package. Pmenu. Pmenu. show(me. menuItem = new JMenuItem("Paste").

frame.} } public void mouseReleased(MouseEvent Me){ if(Me. frame. This program has used various tools of swing to implement the JTabbed component of Java. } } }).setVisible(true). first is the title for the tab and another is the component name which is specified for a particular tab to show for that.400). Me.getY()).show(Me.getComponent(). you will learn how to create the JTabbedPane container in Java Swing.isPopupTrigger()){ Pmenu. The following figure shows the JTabbedPane component of Java Swing: These are explained as follows: JTabbedPane: This is the class of javax.*. all the things related to the creation of JTabbedPane container have been illustrated in efficient manner. This method takes different-different types of arguments but in this program this method has taken two argument. 173 .setSize(400. add(): This is the method of JTabbedPane class which is used to add container component to the JTabbedPane component of Java Swing.swing. package which creates the JTabbedPane component of Java Swing which contains separate button for the separate tab. The example for illustration is given in which. You can also container component with the specific tab.getX(). Me. Creating a JTabbedPane Container in Java Swing In this section.

tab. radio buttons and menus etc. The KeyboardFocusManager receives the KeyEvents 174 CompositeContext ItemSelectable KeyEventDispatcher KeyEventPostProcessor . button). This interface allows the existence of several context simultaneously for a single composite object. This package provides following interfaces and classes as follows: Interfaces and Descriptions of AWT Package: ActionEvent Adjustable This interface is used for handling events.setDefaultCloseOperation(JFrame. This interface is used for maintaining zero or more selection for items from the item list. checkboxes.add("Tab 2".CENTER). It contains all classes to write the program that interface between the user and different windowing toolkits. frame.EXIT_ON_CLOSE). JTabbedPane tab = new JTabbedPane(). It handles the state of the operations.add("Tab 1".awt.400).setVisible(true). frame.swing. frame.Here is the code of the program: import javax. button). } } AWT in Java AWT stands for Abstract Windowing Toolkit. AWT package is used to develop user interface objects like buttons.*. This interface also implements the current KeyboardFocusManager.add(tab. button = new JButton("2"). frame. The KeyEventDispatcher implements the current KeyboardFocusManager and it receives KeyEvents before despatching their targets. This interface takes numeric value to adjust within the bounded range. JButton button = new JButton("1"). BorderLayout.setSize(400. public class CreateTabbedPane{ public static void main(String[] args){ JFrame frame = new JFrame("Tabbed Pane Frame").*. import java. tab.

This interface provides print a graphics context for a page. This class uses to arranging the components. The AWT events defined in the java. This interface has all menu containers.event package. This interface used for represent the geometric shapes. This class defines the basic set of rendering attributes for using outlines of graphics. It defines the interface class and it has layout containers. This interface is used to color pattern. It has five 175 AWTEvent AWTEventMulticaster AWTKeyStroke AWTPermission BasicStroke BorderLayout .LayoutManager LayoutManager2 MenuContainer Paint PaintContext PaintGraphics Shape after that dispatching their targets. This interface also used the color pattern. Classes and Descriptions of AWT Package: AlphaComposite This class implements the basic alpha compositing rules. It provides an important color for the Graphics2D operation and uses the ColorModel. It used for the Graphics2D operations. This class uses for the AWT permissions. This is a supper class of all AWT Events.awt. This class implements threadsafe multi-cast event and it is despatching for the AWT event. This is the interface extends from the LayoutManager and is subinterface of that. This class used to key action on the keyboard or equivalent input devices. It combines the source and destination pixels to achieve transparency effects to graphics and images.

This class represents the checkbox and also include the menu. Color library specify the all color.. It also used the order the element of component or text. west. It contains after page-flipping. A generic AWT container object has other AWT components. It displays on the screen. This is a graphical representation to interacted by user.FlipContents Button Convas CardLayout Chaeckbox CheckboxGroup CheckboxMenuItem Choice Color Component ComponentOritentation Container ContainerOrderFocusTraversalPolicy components such as: east. This class has a type-safe enumeration of buffer. It determines the traversal 176 . It is a graphical component. It has two states.BufferCapabilities BufferCapabilities. This class represents pop-up menu to user's choice. This class has colors. True state that means "on" or false sate that means "off". This class encapsulates the language-sensitive orientation. north. This class used to create a label button It represents the blank rectanglular area on screen. It can draw or trap input events from the user. The default color is RGB color. it identified by ColorSpace. This class to be used together multiple checkbox buttons. south and the center. It is a layout manager for a comtainer. This class has properties of buffers.

It has title and border. This class used for handle the AWT applecations. This class describe the height and width of a component in a single object. This is a top label window. This class defines the order in which components traverse particular focus cycle root. This class represents the bitmap representation of the mouse cursor. It encapsulate the information and rendering the 177 . This class determines the traversal order on the order of child components of container. This class defines fonts and it uses render text that is visible. It uses to write lines in a paragraph. height. It is a platform independent class. width and refresh rate of a GraphicsDevice. It has both classes underlying peer class and trusted application class.Cursor DefultFocusTraversalPolicy DefultKeyboardFocusManager Dialog Dimension DisplayMode Event EventQueue FileDialog FlowLayout FocusTraversalPolicy Font FontMetrics order based on the order of child components in a container. This class arrange the components and flow the left to right. It can be used for taking a some input of users. Here user can be select the file. This class available only for the backwards compatilibility. This class displays dialog window. This class encapsulates the bit depth. This class defines font matrix object..

rectangle etc. images and printers etc. It has compabilities and . This class is a collection of GraphicsDevices object and Font objects. It extends form the Graphics class. With the help of GradientPaint you fill any shapes. This class defines top-level window and it designs the any area of border. This class contains a valid GraphicConfiguration. This class is a supper class of all graphical images. This class describes the characteristics of graphics destination such as printer and monitor. It has rectangular grid components.Frame GradientPaint Graphics Graphics2D GraphicsConfigTemplate GraphicsConfiguration GraphicsDevice GraphicsEnvironment GridBagConstraints GridBagLayout GridLayout Image ImageCompabilities 178 paritcular fonts. This class uses the layout manager and uses the vertically and horizontally components. This class describes the graphics devices and it available particular graphics environment. color management etc. This class is a layout manager. coordinate transformation. This class uses to drawing all types of graphics such as: oval. This class specify the constraint for components by using the GrideBagLayout class. The GraphicsDevices objects are screen. This class controls all geometry.

This component uses by the uses and it choose the list of item. It has default selection states and extends from the java. It is a utility class. It has pull-down menu components that displayed as like menu bar. It possible for the job destinations and extends form the java.awt.AttributeValue package. 179 . It displays the user dialog and extends from the java. blank space and titles.MultipleDocumentHandlingType JobAttributes.Insets JobAttributes JonAttributes.AttributeValue package.awt. This class manage the current focus owner. This class represents all types of border's container.AttributeValue package. This class has the concept of menu bar and it also bounded into a frame.awt. It includes borders. This class handles the multiple copy states and extends form the java. This class control the print job.DestinatinType JobAttributes.AttributeValue package. active and focused windows It is a component which contains the text in container.DialogType JobAttributes. It uses multi-page impositions and extends from the java.SidesType KeyboardFocusManager Label List MediaTracker Menu MenuBar properties of images.DefaultSelectionType JobAttributes.AttributeValue package. This class has status of a number of media objects.awt.awt.

MediaType PageAttributes.AttributeValue package. It handles the print qualities and extends from the java.awt. y) space. It extends the Menu and specify the positions of components. It controls the output of the printed page.OrientationRequestedType PageAttributes.AttributeValue package. It handles the color states and extends form the java. It includes components and other panels.awt.awt. It extends Point2D.OriginType PageAttributes. It has two dimensional region and it bounded by the multiple number of lines. It extends Container and implements to Accessible.awt. This class executes a print job .awt.AttributeValue package.AttributeValue package. It handles the possible orientations and extends from the java.MenuComponent MenuItem MenuShortcut PageAttributes PageAttributes.ColorType PageAttributes.PrintQualityType Panel Point Polygon PopupMenu PrintJob 180 This is supper class of all menu related components. It handles the paper size and extends from the java. It handles the origins and extends from the java. This class represents the handling MenuItem through help of keyboard . The point represents the location of coordinate (x. This is a simplest container class. This is a supper class and it represents the item of menu.AttributeValue package.

This class represents the state of horizontal and vertical scrollbar of ScrollPane. Which implements the Adjustable interface. The value depends on the actual value of RGB. It provides a way to fill a shape with a texture and specify by the BufferedImage. This class represents the system's color through the symbolic representation color. A rectangle object has length and width and it also specify an area in a coordinate space. It has text component and It allows to editing a single line of text.Key Robot Scrollbar ScrollPane ScrollPaneAdjustable SystemColor TextArea TextComponent TextField TexturePaint and extends from the Object. This is a supper class of any component. It allows to editing the some text. It displays multi line text. This class used to control the randering and imaging pipelines. The horizontal and vertical state represented by the ScrollPaneAdjustable objects. 181 .Rectangle RenderingHints RenderingHints. It extends Rectangle2D. This class provide the user interface components and also include the scroll bar. This class contains rendering hints by using the Graphics2D class. It includes the horizontal and vertical scrolling for a single child components. This class used to generate the native system input events and it automatically test the java platform implementations.

Check Boxes : The syntax of the definition of Checkbox is as follows : CheckBox checkbox_name = new Checkbox ("Optional check box 1". This component is generally used to show the text or string in your application and label never perform any type of action. false). 182 . Justification of label can be left. Only one Checkbox from a Checkbox Group can be selected at a time. WindowClosed. Label label_name = new Label ("This is the label text.getLabel() method.Labels : This is the simplest component of Java Abstract Window Toolkit.").CENTER).". Java AWT Components Introduction Following some components of Java AWT are explained : 1.setLabel(String) and Button. Label. Changing the Button's label or get the label's text by using Button. It capable for generating the window events like: WindowOpend. Above declaration used the center justification of the label using the Label. get the checkbox's label using the setLabel (String) and getLabel() method. Defined Checkbox is added to it's container using add (checkbox_name) method.CENTER. right or centered. Buttons are added to the it's container using the add (button_name) method. The syntax of defining the button is as follows : Button button_name = new Button ("This is the label of the button. We can also set and get the state of the checkbox using the setState(boolean) and getState() method provided by the Checkbox class. Radio Button : This is used as a group of checkboxes which group name is same. Label label_name = new Label ("This is the label text. It is a top-level window. the 3. . It has not borders and menubar. Buttons : Used to trigger actions and other events required for your application. Above code constructs the unchecked Checkbox by passing the boolean valued argument false with the Checkbox label through the Checkbox() constructor.").Toolkit Window This is a supper class of all Abstract Windowing Toolkit. 2.

This is declared as follows : TextField txtfield = new TextField(20). TextArea can be declared as follows: . } } Here is the HTML code: 183 . import java. chkgp. chkgp.*. import java. add(button). add (new Checkbox ("One". "Two" and "Three".applet. 5. add (new Checkbox ("Two". If you mention more than one true valued for checkboxes then your program takes the last true and show the last check box as checked.awt. Text are set in the text area using the setText(string) method of the TextArea class. false). public class MyButton extends Applet { public void init() { Button button = new Button("SUBMIT"). Text Field: This component contains single line and limited text information. The text area is by default in editable mode. The Text Area contains plain text. In the above code we are making three check boxes with the label "One". Text Area: This is the text container component of Java AWT package. 4. false).TextArea txtArea_name = new TextArea().- Syntax for creating radio buttons is as follows : CheckboxGroup chkgp = new CheckboxGroup(). Make the Text Area editable or not using the setEditable (boolean) method. Pass the boolean valued argument false then the text area will be non-editable otherwise it will be editable.Applet.

-100. 100). add(sb). The subtraction of scrollbar width from the maximum setting gives the maximum value of the Scrollbar.*.awt. 0. '8' is the width of the scrollbar.Applet.<HTML> <BODY> <APPLET ALIGN="CENTER" CODE="MyButton" WIDTH="400" HEIGHT="200"></APPLET> </BODY> </HTML> Scrollbar A scrollbar is represented by a "slider" widget. The characteristics of it are specified by integer values which are being set at the time of scrollbar construction. 8. } } TextField A scrollable text display object with one row of characters is known as the TextField.applet.VERTICAL.awt. public class TextFieldDemo extends Applet{ public void init(){ TextField tf = new TextField("Type in the box").Applet. Both the types of Sliders are available i. public class ScrollbarDemo extends Applet { public void init() { Scrollbar sb = new Scrollbar (Scrollbar.shtml initial value of the scrollbar. } } Common Component Methods The common methods of AWT components are as follow: 184 .*. import java.applet. horizontal and vertical. add(tf). '0' is the <<<<<<< scrollbar. import java. import java. In the program code. import java.e.

This method is used to change the background/foreground colors of the component. as a Dimension. it is always advisable to use getWidth() and getHeight() methods to directly access the width and height while working on Java 2 platform. setEnabled(boolean) . if set to false then the component will not appear hence no user interaction will be there. There is a Panel which is used for running the programs.This method is used to toggle the state of the component.width.This method is used for the visibility state of the component. int width = d. 5.getHeight(). 8. 185 . The component appears on the screen if setVisible() is set to true and if its set to false then the component will not appear on the screen. getBounds() . The usage of the method is shown below. int width = r. int height = d.getWidth(). int height = r. This Panel is known as Class Applet which is used for running the programs within the Browser.1. The component will appear if set to true and it will also react to the user. 7. 2. int width = someComponent.height. 6.setVisible(boolean) . Dimension d = someComponent.getSize(). setBackground(Color)/setForeground(Color) .This method is used to change the font of text within a component.This method is used to get the current bounding Rectangle of component.This method is used to get the current size of component. Again. setFont(Font) .getBounds().height. int height = someComponent. Containers Container is a component that can be nested.width. Rectangle r = someComponent. getSize() .

gif"). } } Different types of event in Java AWT Introduction There are many types of events that are generated by your AWT Application. ScrollPane The ScrollPane container provides an automatic scrolling of any larger component.add(new Scrollpane(mg)). 0.SCROLLBARS_ALWAYS).Common Container Methods All the subclasses of the Container class inherit the behavior of more than 50 common methods of Container. getComponent(int).CENTER). Some of the methods of container which are most widely used are as follow: getComponents(). } public void paint(Graphics g) { if (image != null) g. getComponentCount(). BorderLayout. public Scrollpane(Image m) { image = m.applet. import java. SC. } } public class ScrollingImageDemo extends Applet { public void init() { setLayout(new BorderLayout()). Image mg = getImage(getCodeBase(). class Scrollpane extends Component { private Image image.*.drawImage(image. this). import java. ScrollPane SC = new ScrollPane(ScrollPane. The example below shows the Scrollpane.awt.*. add(SC. 0. These subclasses of the container mostly override the method of component. 186 . add(). "cute-puppy.

e.- These events are used to make the application more effective and efficient. KeyEvent 9. MouseEvent 10. It indicates the component-defined events occurred i. ContainerEvent: The ContainerEvent class extends from the ComponentEvent class. 4. AdjustmentEvent 3. These are as follows : 1. WindowEvent These are twelve mentioned events are explained as follows : 1. 3. FocusEvent 6. there are twelve types of event are used in Java AWT. 2. changed and it's states (visibility of the object). ContainerEvent 5. TextEvent 12. This class only performs the notification about the state of the object. AdjustmentEvent: This is the AdjustmentEvent class extends from the AWTEvent class. This is a low-level event which is generated when container's contents changes because of addition or removal of a components. the event generated by the component like Button. PaintEvent 11. ComponentEvent: ComponentEvent class also extends from the AWTEvent class. FocusEvent: 187 . Checkboxes etc. The generated event is passed to every EventListener objects that receives such types of events using the addActionListener() method of the object. 3. Generally. ActionEvent: This is the ActionEvent class extends from the AWTEvent class. ActionEvent 2. ItemEvent 8. When the Adjustable Value is changed then the event is generated. This class creates the low-level event which indicates if the object moved. InputEvent 7. ComponentEvent 4.

The PaintEvent class only ensures that the paint() or update() are serialized along with the other events delivered from the event queue. KeyEvent: KeyEvent class extends from the InputEvent class. That contains the information whether mouse is clicked or not if clicked then checks the pressed key is left or right. 10. 5. This class indicates about the focus where the focus has gained or lost by the object. TextEvent: 188 . The MouseEvent class handle all events generated during the mouse operation for the object. This event class handles all the component-level input events. whether selected or not. This type of events check whether the pressed key left key or right key. MouseEvent: MouseEvent class also extends from the InputEvent class. The generated event is passed to every ItemListener objects that is registered to receive such types of event using the addItemListener() method of the object. 7. The generated event is passed to every objects that is registered to receive such type of events using the addFocusListener() method of the object.e. 8. 6. 9.- The FocusEvent class also extends from the ComponentEvent class. This class acts as a root class for all component-level input events. InputEvent: The InputEvent class also extends from the ComponentEvent class. The ItemEvent class handles all the indication about the selection of the object i. ItemEvent: The ItemEvent class extends from the AWTEvent class. PaintEvent: PaintEvent class also extends from the ComponentEvent class. The KeyEvent class handles all the indication related to the key operation in the application if you press any key for any purposes of the object then the generated event gives the information about the pressed key. 'A' or 'a' etc.

e. activated. nothing happens when an event takes place if there is no listener. addActionListener() method is used for any action to be performed. Events are the integral part of the java platform.- TextEvent class extends from the AWTEvent class. where XXX is the event type. For example. one for key release. closed. Any class can act like a Listener class permitted by the Event sources. There is another method by which you can remove the listener class which is removeXXXListener() method. WindowEvent : WindowEvent class extends from the ComponentEvent class. For any event to occur. deactivated or any other events are generated). 11. AWTEvent Most of the times every event-type has Listener interface as Events subclass the AWTEvent class. There are three methods which are required to be implemented for Key events and to register them i. No matter how many listeners there are.e. the objects registers themselves as listeners. 189 . 3. each and every listener is capable of processing an event. ActionListener can be implemented by any Class including Applet. There are some special classes as well which are known as adapters that are used to implement the listener interfaces and stub out all the methods. If the window or the frame of your application is changed (Opened. No event takes place if there is no listener i. When anything interesting happens then the subclasses of AWTEvent are generated by the component. these adapter classes can be sub classed and and can override the necessary method. where Action is the event type. A listener type has to be implemented for an event handling such as ActionListener. The step by step procedure of Event handling is as follow: 1. 2. Events Java awt. The generated events are passed to every TextListener object which is registered to receive such type of events using the addTextListener() method of the object. WindowEvent is generated. 4. call AWTEvent. key typed and one for key press.consume() method whenever you don't want an event to be processed further. TextEvent is generated when the text of the object is changed.

clicking. pressing. dragging. deactivating. The different event sources are represented by the following table. or releasing. hiding. If a component is an event source for something then the same happens with its subclasses. closing. pressing. moving. Used for Getting/losing focus. FocusEvent MouseEvent ContainerEvent KeyEvent WindowEvent ComponentEvent Semantic Events - Used for moving. Used for opening. or typing (both) a key. Iconifying. exiting. Types of Low-level events are mouse movement. a key press etc. resizing.- PaintEvent and InputEvent don't have the Listener interface because only the paint() method can be overriden with PaintEvent etc. 190 . Used for Adding/removing component. Low-level Events A low-level input or window operation is represented by the Low-level events. Used for value adjusted. Used for entering. deiconifying. The different type of low-level events and operations that generate each event are show below in the form of a table. really closed. Used for do the command. The different events generated by different components is shown below. window opening. Used for releasing. selecting a button etc. ItemEvent ActionEvent TextEvent AdjustmentEvent Event Sources - Used for state changed. Used for text changed. showing. The interaction with GUI component is represented by the Semantic events like changing the text of a text field.

The Listener interfaces and their methods are as follow: Interface Methods windowActivated(WindowEvent e) windowDeiconified(WindowEvent e) windowOpened(WindowEvent e) windowClosed(WindowEvent e) windowClosing(WindowEvent e) windowIconified(WindowEvent e) windowDeactivated(WindowEvent e) WindowListener 191 .Low-Level Events Window Container WindowListener ContainerListener ComponentListener FocusListener KeyListener MouseListener MouseMotionListener Component Semantic Events Scrollbar TextArea TextField Button List MenuItem TextField Choice Checkbox Checkbox CheckboxMenuItem List AdjustmentListener TextListener ActionListener ItemListener Event Listeners Every listener interface has at least one event type.

Thus. the methods which you do not want to care about can have empty bodies. If you want to use only one method out of these then also you will have to implement all of them. To avoid such thing. Adapter classes help us in avoiding the implementation of the empty method bodies. That is some of the listener interfaces contain more than one method. the MouseAdapter class implements the MouseListener interface. 192 . mousePressed. An adapter class can be used by creating a subclass of it and then overriding the methods which are of use only. mouseReleased etc. For instance. we have adapter class.ActionListener actionPerformed(ActionEvent e) adjustmentValueChanged(AdjustmentEvent AdjustmentListener e) mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) MouseListener mouseExited(MouseEvent e) mousePressed(MouseEvent e) mouseReleased(MouseEvent e) focusGained(FocusEvent e) FocusListener focusLost(FocusEvent e) ItemListener itemStateChanged(ItemEvent e) KeyListener keyReleased(KeyEvent e) keyTyped(KeyEvent e) keyPressed(KeyEvent e) componentHidden(ComponentEvent e) componentMoved(ComponentEvent e) ComponentListener componentShown(ComponentEvent e) componentResized(ComponentEvent e) MouseMotionListener mouseMoved(MouseEvent e) mouseDragged(MouseEvent e) TextListener textValueChanged(TextEvent e) ContainerListen er componentAdded(ContainerEvent e) componentRemoved(ContainerEvent e) Event Adapters There are some event listeners that have multiple methods to implement. the MouseListener interface contains five methods such as mouseClicked. Generally an adapter class is there for each listener interface having more than one method. For instance.

- Hence avoiding the implementation of all the methods of the listener interface.*. import java. .add(b = new Button("Good Day"). public class ButtonPressDemo { public static void main(String[] args){ Button b. f.CENTER).setActionCommand("Good Morning")..event. */ ublic void mouseExited(MouseEvent e) { } /* Empty method definition. f. import java.NORTH). b.addMouseListener(this).awt.addActionListener(a).addActionListener(a). b..add(b = new Button("Bonjour").awt. Frame f = new Frame("Java Applet"). */ public void mouseEntered(MouseEvent e) { } /* Empty method definition.. ActionListener a = new MyActionListener(). BorderLayout. public class MyClass implements MouseListener { . BorderLayout. b. someObject. /* Empty method definition. 193 .*. */ public void mousePressed(MouseEvent e) { } } } Button Pressing Example The following program demonstrates the event generated by each button. The following example shows the implementation of a listener interface directly..

} } class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent ae) { String s = ae. import java.add(b = new Button("Aurevoir"). } }). aw.*.equals("Bonjour")) { System.exit(0).awt.println(s + " clicked"). b. import java. } public static void main(String[] args){ ApplicationWindow aw = new ApplicationWindow().setActionCommand("Exit"). The Frame consists of a Window with a title. setSize(200.SOUTH).out.equals("Exit")) { System.getActionCommand().f. } else if (s.println("Good Morning"). f.out. } } } GUI-based Applications In this section you will learn about how to create a window for your application. 200). Define a subclass of Frame to create a window for your application. BorderLayout. addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ setVisible(false). and border. } else { System. if (s.pack(). One point to remember here is that Applications respond to events in the same way as applets do.addActionListener(a).*. f. System.exit(0). dispose().awt.setVisible(true).event. } } 194 . menubar. public class ApplicationWindow extends Frame{ public ApplicationWindow(){ super("ApplicationWindow").show(). b.

MenuBar mb = new MenuBar(). 2.. mb. mi. You need to create a MenuBar first with the help of the following method.Menus As a name indicates a Menu consists of Menu objects. Now you can add the Menu to the MenuBar from left to right using mi. } 195 . 4..add(new MenuItem("Open")).*. These Menu objects comprise of MenuItem objects which can be selected by the user with a click of a mouse. creates an application window with a menu bar. mi. Now the MenuItem options can be added to the Menu from top to bottom. MenuBar mb = new MenuBar().awt.*. setSize(400.event. using the following methods. separator. Following are the steps to add menus to any Frame: 1. checkbox. mport java.awt. you need to add the MenuBar to the Frame by calling the setMenuBar() method. mb. A MenuItem may be a String. Finally. 400). addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exit(). import java.add(helpMenu). 5. The program code given below. public class MainWindow extends Frame { public MainWindow() { super("Menu Window"). HelpMenu helpMenu = new HelpMenu(this). 3.add(m). setMenuBar(mb). menu etc.add(new CheckboxMenuItem("Type here")). FileMenu fileMenu = new FileMenu(this).add(fileMenu). Then you need to create a Menu using Menu m = new Menu("File").

add(mi = new MenuItem("Basics")).addActionListener(this). 196 .addActionListener(this). subMenu. System.addActionListener(this). mw = m. } public void exit() { setVisible(false).addActionListener(this). add(mi = new MenuItem("Advanced")). MenuItem mi. } public static void main(String args[]) { MainWindow w = new MainWindow(). subMenu.exit(0). add(mi = new CheckboxMenuItem("Manual")).add(mi = new MenuItem("Other Option")). mi. public HelpMenu(MainWindow m) { super("Help"). } } class FileMenu extends Menu implements ActionListener { MainWindow mw. Menu subMenu = new Menu("Miscellaneous").equals("Exit")) mw. mi. mi.exit(). dispose(). } public void actionPerformed(ActionEvent e) { String item = e. mi. else System. if (item. add(mi = new MenuItem("Exit")). public FileMenu(MainWindow m) { super("File"). } } class HelpMenu extends Menu implements ActionListener { MainWindow mw.}). add(mi = new MenuItem("Close")).println("Selected FileMenu " + item).out.getActionCommand().addActionListener(this). addSeparator(). w. mw = m.addActionListener(this). mi. mi. mi. MenuItem mi.setVisible(true).addActionListener(this). add(mi = new MenuItem("Open")).add(mi = new MenuItem("Help")).

awt.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ m.equals("Help")) System.println("Basics").} mi. e.Applet.getY()). addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ if (e. msg = new TextField().*.out. 200). m = new PopupAppMenu(this).show(e. add(msg.getComponent(). BorderLayout. msg.setEditable(false).getActionCommand(). The Pop-up Menu can be popped over any component while generating the appropriate mouse event rather than letting it appear at the top of a Frame. 20. e. public PopupMenuDemo(){ setSize(200. add(b.equals("Basics")) System. public class PopupMenuDemo extends Applet{ Button b. } }). 197 .isPopupTrigger()) m. b = new Button("Pop-up Menu"). } } Pop-up Menus A PopupMenu is similar to a Menu as it contains MenuItem objects. add(subMenu). BorderLayout. e. PopupAppMenu m.getComponent(). if (item.getX().addActionListener(this). To add it to the Applet you need to use the Swing component set. b. TextField msg.show(b.*.SOUTH). import java.NORTH). e. add(m). import java.show(e. public void actionPerformed(ActionEvent e) { String item = e. } public void mouseReleased(MouseEvent e){ if (e. else if (item.applet. import java.out.awt. } }).event. 20).getY()).getX(). Menu class can only be added to a Frame and not to the Applet.println("Help").isPopupTrigger()) m.

add(mi = new MenuItem("Open")).setText("Option Selected: " + item). mi.addActionListener(this). Java supports the look and feel and decoration for the frame.ref = ref. The most common method of creating a frame is by using single argument constructor of the Frame class that contains the single string argument which is the title of the window or frame.addActionListener(this).} public static void main(String[] args){ PopupMenuDemo app = new PopupMenuDemo(). app. mi. this. Then you can add user interface by constructing and adding different components to the container one by one. add(mi = new MenuItem("Cut")).This method has been used to add the label to the frame. } public void actionPerformed(ActionEvent e){ String item = e. mi. public PopupAppMenu(PopupMenuDemo ref){ super("File").setVisible(true). Method add() adds a component to it's container. MenuItem mi. The frame initially invisible.CENTER. add(mi = new MenuItem("Copy")).getActionCommand().addActionListener(this). add(lbl): . } } class PopupAppMenu extends PopupMenu implements ActionListener{ PopupMenuDemo ref.msg. ref. so after creating the frame it need to visualize the frame by setVisible(true) method. add(mi = new MenuItem("Paste")). top-level windows are represented by the Frame class. height): 198 . setSize (width. mi. } } Create a Frame in Java Introduction In the Java AWT. The center alignment of the label has been defined by the Label.addActionListener(this).

} } Setting the Icon for the frame in Java Introduction Toolkit class has been used to get the image and then the image is used to display as frame icon. frame.getDefaultToolkit(). If the security manager installed then the getImage() method first check whether the specified file name has the permission to use and then retrieves the image in pixels format.400).- This is the method of the Frame class that sets the size of the frame or window. frame. } } 199 .Label. setVisible(boolean): . height (int).setVisible(true).setSize(400. Label lbl = new Label("Welcome to Tutorial.jpeg or . public class AwtSetIconOfFrame{ public static void main(String[] args){ Frame frame = new Frame("Icon setting for the Awt Frame").*.add(lbl). This method takes two arguments width (int). frame. Image icon = Toolkit.CENTER). frm.". public class AwtFrame{ public static void main(String[] args){ Frame frm = new Frame("Java AWT Frame").This is also a method of the Frame class sets the visibility of the frame.setIconImage(icon). . The frame will be invisible if you pass the boolean value false otherwise frame will be visible. frm. getImage(url or filename): .awt. frame.Label.gif"). Import java.This method returns the default toolkit.setVisible(true).png. Label lbl = new Label("Welcome to Tutorial.This method retrieves the pixels data of the image which can be either in format of .".CENTER). Toolkit class is used to bind the various components to particular native toolkit implementations.awt.400). getDefaultToolkit(): .gif.getImage("icon_confused.setSize(400.*. import java.add(lbl). frm.

*. This is done using the addWindowListener() method of the Frame class which passes the new instance of the WindowAdapter class that uses the windowClosing() method for receiving the WindowEvent and close the frame or window.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.awt. package.CENTER). WindowAdapter() : .awt.setVisible(true). frame.event. Import java.awt.400).*.event.*. frame. Label lbl = new Label("Welcom in Tutorial". closing the frame).Setting the close button operation for the frame in Java Introduction If you click on the close button of the frame or window that will be cancelled automatically. windowClosing() : . This is an abstract class used for receiving window events.awt.This is the constructor of the WindowAdapter class of the java. 200 .event.This is the addWindowListener() method which adds the window listener to receive the window event from the window.add(lbl). } } Making a Frame Non Resizable in Java import java.This is the windowClosing() method of the WindowAdapter class invoked when the frame is attempted to close from the window's system menu or close button. import java.Label. This method receives the WindowEvent object.*. This method passes the window listener.e.setSize(400. frame. frame. import java. public class AwtCloseButtonEvent{ public static void main(String[] args){ Frame frame = new Frame("Close Operation Frame").awt.exit(0). } }). addWindowListener() : . The close button of the frame has to be set for the desired operation (i.*.

CENTER.public class AwtFrameNonResizable{ public static void main(String[] args){ Frame frame = new Frame("Non Resizable Frame"). package which is used to arranging and resizing it's components to fit in five rigions : north.400). west and center. import java. panel. Here. public class CreateContainer{ public static void main(String[] args){ Panel panel = new Panel().add(lbl).". } } Create a Container in Java awt Introduction Container contains several control or tools for develop your application.add(new Button("Button 1")). SOUTH.event.*.Label.getDefaultToolkit(). Image icon = Toolkit. All the controls used in your application are the container for one another. The panel and a text area added to the frame.awt. Each region may contain only one component.dispose().CENTER). panel.awt. BorderLayout : . the add() method has been used for both operations (add buttons to the panel and add panel and text area to the frame). All regions are represented by the NORTH.SOUTH since the position of the text area has been specified the center of the frame using BorderLayout.add(new Button("Button 2")). Ex: Three buttons have been added to the panel. } }). Label lbl = new Label("Welcome to Tutorial.setSize(400.setResizable(false). east.*.BorderLayout is the class of the java. The position for the panel on the frame has been specified south of the frame by using BorderLayout.getSource(). frame.getImage("icon_confused. frame. frame. 201 .gif").*. frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ Frame frame = (Frame)we. frame.setVisible(true). import java. south.setIconImage(icon). WEST and CENTER constants of the BorderLayout class. frame. frame.awt. EAST.

CENTER). } }).awt.awt.CENTER).addFocusListener(new MyFocusListener()). BorderLayout. frame.add(txtArea. frame.add(cancel). frame. import java. The generated event (FocusEvent) is passed to every FocusListener objects that receives such types of events using the addFocusListener() method of the object. Panel panel = new Panel().NORTH). Button yes = new Button("Yes"). panel. no.add(new Button("Button 3")).addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System. panel. Button cancel = new Button("Cancel").400).BorderLayout.add(panel.setVisible(true).*. public static void main(String[] args){ FocusChange fc = new FocusChange().400). The addFocusListener() method is takes the instance of MyFcousListener class.add(panel. panel.add(no). 202 .setVisible(true).*.setSize(400. label = new Label(). Handling Focus Changes in Java Introduction The generated focus events are performed by the FocusListener of the object used in your application using the addFocusListener() method.event.add(label.addFocusListener(new MyFocusListener()). public class FocusChange{ Label label. Frame frame = new Frame("Container Frame"). cancel. Button no = new Button("No").setSize(400. import java. yes.addFocusListener(new MyFocusListener()). frame. } public FocusChange(){ Frame frame = new Frame("Welcome").} } panel. frame.exit(0). frame. TextArea txtArea = new TextArea(). frame.BorderLayout. frame. BorderLayout. frame.add(yes).SOUTH).

addMouseListener(new MyMouseListener()).exit(0).net").*.equals("Roseindia.frame. String str = bt.equals("You have clicke the button. p. import java. lbl = new Label("Roseindia.400).getSource().exit(0). } else if (str. } }).")){ lbl. f.add(lbl. } } } Handling Mouse Clicks in Java import java.getLabel(). label. f. } public class MyMouseListener extends MouseAdapter{ public void mouseClicked(MouseEvent me){ String str = lbl.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System. BorderLayout.setVisible(true).NORTH).setText("You have clicke the button.*. Panel p = new Panel().CENTER).setSize(400. if (str. } public MouseClick(){ Frame f = new Frame("Checking the mouse click"). f.getText().add(button.event. } }).net").").add(p.NORTH).addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.setText(str). } public class MyFocusListener extends FocusAdapter{ public void focusGained(FocusEvent fe){ Button bt = (Button)fe. public static void main(String[] args) { MouseClick MC = new MouseClick(). button. BorderLayout.awt.setText("Roseindia.BorderLayout. f. public class MouseClick { Label lbl.awt.net")){ lbl. Button button = new Button("Click Me"). } } 203 . f.

} public AwtEvent(){ super("Event in Java awt"). import java. AwtEvent is the main class of the program which extends from the Frame class implements the ActionListener interface. When you click on the button then the actionPerformed() method is called which receives the generated event. Button button1 = new Button("INSERT_A_FILENAME_HERE"). The constructor of the AwtEvent class creates two buttons with adding the addActionListener() method to it. } catch (Exception e){} setSize(400. This method shows the text of the source of the event on the label.CENTER). package. add(lbl. add(button1. try{ Button button = new Button("INSERT_AN_URL_HERE"). Import java.*.awt.*. setVisible(true).NORTH). This program starts to run from the main method in which the object for the AwtEvent class has been created. BorderLayout.addActionListener(this).awt.400). button1.awt.*. lbl = new Label("Welcome").event. add(button. The constructor also initializes a label with text "welcome". setLayout(new BorderLayout()).SOUTH).addActionListener(this). } }).exit(0).} } Event handling in Java AWT Introduction This example shows you how to handle events in java. public static void main(String argv[]){ AwtEvent t = new AwtEvent(). public class AwtEvent extends Frame implements ActionListener{ Label lbl. addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System. BorderLayout. button. } 204 . BorderLayout.

String str = Character.getKeyChar().getLabel(). setVisible(true). BorderLayout. add(panel. label = new Label(). public static void main(String[] args) { KeyPress k = new KeyPress().toString(i).getSource(). String str = bt.*.awt. TextField txtField.CENTER). import java.public void actionPerformed(ActionEvent e){ Button bt = (Button)e. label. panel.setText(str). BorderLayout. } } } Item Events in Java Introduction 205 .setText(str). } } Handling Key Press Event in Java Introduction import java. public class KeyPress extends Frame{ Label label. txtField = new TextField(20).exit(0). BorderLayout. txtField.addKeyListener(new MyKeyListener()). lbl. addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.CENTER).*.400).add(txtField. Panel panel = new Panel().event.NORTH). } public class MyKeyListener extends KeyAdapter{ public void keyPressed(KeyEvent ke){ char i = ke. } public KeyPress(){ super("Key Press Event Frame").awt. add(label. } }). setSize(400.

event.CENTER).setText("This is the " + e. txtArea = new TextArea(). import java.awt. add(txtArea. public AwtItemEvent(String title){ super(title).This is the method of the ItemEvent class which returns the value of the selected or deselected item. Blue.- Handling item event through the given program in which. choice. The generated event is passed to all ItemListener objects which is registered to receive such types of event. This is done using the addItemListener() method of the object. If you select an item from the combo box then the message with the item name will be displayed in the text area.addItem("blue"). BorderLayout.400). addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.awt. public class AwtItemEvent extends Frame{ TextArea txtArea. setVisible(true). Choice choice = new Choice().*. choice. ItemEvent : . } }). Green. Items of the combo box are as follows : Red. } public static void main(String[] args){ AwtItemEvent f = new AwtItemEvent("AWT Demo").getItem() + " color.This is the ItemEvent class which indicates an event on selecting or deselecting items from the item group. add(choice.addItem("green").NORTH). } }). } } 206 . setResizable(false). import java. This event is passed by ItemListener object.exit(0). BorderLayout. a combo box and a text area have been taken. choice. getItem() : . setSize(400.addItem("red"). choice.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e){ txtArea.\n").*. : Choice() This is the constructor of the Choice class which creates combo box.

Panel p =new Panel().awt. public KeyListenerTester(String s ) { super(s).setText ( "Key Pressed" ) . setSize ( 200. } public static void main (String[]args ){ new KeyListenerTester ( "Key Listener Tester" ) . setVisible(true). add(p). The following program show a frame titled with "Frame Hiding".add(l1). } public void keyPressed ( KeyEvent e){ l1. l1 = new Label ("Key Listener!" ) . import java. the frame will not be closed but it will hide certain with holding all frame data as it is.How to use KeyListener import java.exit(0).*. } public void keyReleased ( KeyEvent e ){ l1.awt. Label l1. p. } } Hiding Frame in Java Description of program: In this program.event.setText( "Key Released" ) . When you click on the close button of the frame. addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System. } public void keyTyped ( KeyEvent e ){ l1.*. program you will see that only one method of the frame is important for the purpose. addKeyListener ( this ) .100 ). } }).setText("Key Typed"). Method's Description: 207 . public class KeyListenerTester extends Frame implements KeyListener{ TextField t1.

awt. Here this is used for creating the object of the class to set the layout by passing the created object from the setLayout() method of the Frame class.*. Panel p =new Panel().getSource(). it can return the Form's object that is done invisible by using the setVisible() method. } } How to Create Button on Frame Description of Program The following program has used simply the Button class for creating a command button on the frame object.getSource(): This is the method of EventObject class.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ Frame frame = (Frame)e. fa. By default Java Awt Form is in the invisible state. import java. fa. This class is used for arranging the component from left to right.add(p). Here is the code of this program: import java.awt.*. public class ButtonText { public static void main(String[] args) { 208 . import java. import java. fa. p.*. fa. Label l1=new Label("Welcome").add(l1).event. frame. here this method is used for the WindowEvent class so.*. } }). FlowLayout(): This is the constructor of FlowLayout class.setVisible(false). setVisible(false): This method takes a boolean valued argument which decides the form for visible or not.setSize(300.awt. public class FrameHide{ public static void main(String[] args){ Frame fa= new Frame("Frame Hiding").setVisible(true).200). If you pass the boolean value false then the form will be invisible otherwise if you argument is true then the form object will be visible.event. Hence.awt. The getSource() method returns the source of the generated event.

event.awt. How to create CheckBox On frame Program Description: There is class named CheckBox is used in the program for creating a checkbox component.} } Frame frame=new Frame("Button Frame").awt. The constructor is taking here a String type parameter that is the label of checkbox.setVisible(true). import java. public class CheckBoxDemo{ public static void main(String[] args){ Frame frame= new Frame("Checkbox"). frame.setLayout(new FlowLayout()). frame. frame.add(check1). 209 . Checkbox check1=new Checkbox("Roseindia").setLayout(new FlowLayout()).*. public class ChoiceOptionExample{ public static void main(String[] args) { Frame frame=new Frame("Choice").setVisible(true). } }).*.exit(0). frame.add(button). import java.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System. frame.*.exit(0). Checkbox check=new Checkbox("Welcome").setSize(300.setSize(200. } }). frame.100).*.200). frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System. } } Choice Option (Combo) In Java import java.awt. frame.awt. Button button = new Button("Submit").add(check). This class is explained as follows: CheckBox(): This is the constructors for CheckBox class used for creating checkbox. frame. import java. frame.event. frame.

this). g. public static void main(String[] args) { new PaintIcon().add("ASIA"). choice. } } Paint an Image .exit(0).setLayout(new FlowLayout()).getImage("warning.This section provides you to paint an image on the frame.add("WELCOME"). frame.85.150).yellow). } public void paint(Graphics g){ Toolkit tool = Toolkit.add(label). frame.awt. } }). image = tool. Choice choice=new Choice(). choice. All drawing process is done using the paint() method.100). frame.Label label=new Label("What is your Choice:"). g. frame. frame. setVisible(true).setColor(Color.100.50. addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System. g.100.*.200).addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.add("INDIA"). import java.20.30. setSize(200.40).drawImage(image. choice. import java.add(choice).*.50. 210 . g.getDefaultToolkit().drawRect(20.gif").event.100).fillRect(20.awt.exit(0).drawString("Draw Images:".setVisible(true). Paint means draw an image and set its on the frame to the specified location according to its x coordinate and y coordinate.setSize(250. } public PaintIcon(){ setTitle("Paint an Icon example!"). } }). g. public class PaintIcon extends Frame{ Image image. frame.

getImage("Tom.drawImage(image.gif"). g.this).image = tool.85.80. } } 211 .

Sign up to vote on this title
UsefulNot useful