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

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

Mostly compiler produce code for a particular system but Java compiler produce code for a virtual machine . It provides the cross platform functionality to java. JVM provides security to java. Byte code is an intermediary language between Java source and the host system. Java Virtual Machine(JVM) JVM is the main component of Java architecture and it is the part of the JRE (Java Runtime Enviroment) . 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 . and without JRE.- Java as an interpreted language is its error debugging quality. given the presence of the Java runtime system. The architecture of the JVM is given below - JRE consists of a number of classes based on JavaAPI and JVM. JVM is a part of Java Run Time Environment that is required by every operating system requires a different JRE . it is impossible to run Java. . to be easily interpreted on any machine and to be easily translated into native machine code on the fly.The Java compiler by generating byte code instructions. 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. Due to this any error occurring in the program gets traced. 6 .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. ArchitectureNeutral . This is a software process that converts the compiled Java byte code to machine code.

method return results are stored in Java Stack. 2. It is used for creating objects 3. Execution Engine: It contains Interpreter and JIT Compiler which translate the byte code instruction into machine language. Java Stack: Java method is executed. Method Area: Bytecode instructions will be loaded . PC Register: (Program counter Register):These registers store the address of the instruction being executed by Microprocessor 5. Native Method Stacks: Native methods are methods written in some other language like C or C++ 6. The allotted memory is divided into five parts 1.It contains objects. Method parameters and temporary results . contain class code along with method code.which are executed by MicroProcessor. 4. 7 . Heap : Heap is second part of memory.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.

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

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

8080.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. First Microprocessor 4004.Macro Assemblers . Assembler: Translates assembly language to machine language Mnemonics are used in assembly languge.8086.exe (machine language instructions with a copy of all header files.ii.obj (contains machine language instructionsof a source Run Xyz. - 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. Following figure shows the working of the Java compiler: 10 . iii.8088.Micro Assemblers compile Xyz.c program) Xyz. Assembler s/w – Turbo Assemblers .

-

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

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

and a final variable can occur at most once as a left-hand expression. If followed by a label. Byte is the basic measuring unit Byte represents binary digits called bits. It is also used in an interface declaration to specify one or more superinterfaces. 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. extends keyword is used. final It is used to define an entity once that cannot be altered nor inherited later. However for wider range of values use long. It ranges from -2. a final method cannot be overridden.648 to 2. int It is a 32-bit signed two's complement integer data type. break Used to resume program execution at the statement immediately following the current enclosing block or statement.647.147.147. strictfp To get the precise results in Floating point calculations use strictfp keyword regardless of any operating system and hardware platform. 16 .483. Moreover.483. the program resumes execution at the statement immediately following the enclosing labeled statement or block. 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. All methods in a final class are implicitly final.extends To specify the superclass in a class declaration. Memory Description Information is stored in the floppy disks as Bytes. Java Data Types There are eight primitive data types which are supported by Java language programming which is predefined. a final class cannot be subclassed.

We do not use this data type for the exact values such as currency.767. unsigned Unicode character. We use this data type for conditional statements. It ranges from 1.768 to 32. short It is a 16-bit signed two's complement integer. We can save memory in large arrays using byte.854. They are not same as ints. It ranges from -9.854. long The long data type is a 64-bit signed two's complement integer.808 to 9. shorts etc. It ranges from -128 to127 (inclusive).775. For that we have to use java. We can also use byte instead of int to increase the limit of the code. It ranges from 4.40129846432481707e-45 to 3.223.math. short is used to save memory in large arrays. Use this data type with larger range of values.byte It is an 8-bit signed two's complement integer.BigDecimal class. Use a float (instead of double) to save memory in large arrays. It ranges from 0 to 65.372. 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 . char The char data type is a single 16-bit.94065645841246544e-324d to 1. They are defined constants of the language. double This data type is a double-precision 64-bit IEEE 754 floating point. boolean The boolean data type is 1-bit and has only two values: true and false. This data type is generally the default choice for decimal values.036.807.223.775.535.79769313486231570e+308d (positive or negative). true and false are not the same as True and False.036. float The float data type is a single-precision 32-bit IEEE 754 floating point.372. It ranges from -32.40282346638528860e+38 (positive or negative).

Constant and Literal in Java Variable : You can assign the values to the variable once it has been declared. 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 . The values of the constant can't be changed once its declared An electronic device can understand 1. The values of the variable can be changed anywhere in the program if the variable is accessible in that scope.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 . hexadecimal or octal format. Similarly put the characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal format. To represent the type as long integer we use L as a suffix.Absence of voltage Are the machine languge instructions Java Literals Integer Literals Integer literals is a sequence of digits and a suffix as L. To indicate a decimal format put the left most digit as nonzero.Variable.Presence of voltage 0. We can specify the integers either in decimal. Constants: Constants are declared using the final keyword.

We can specify a character literal as a single printable character in a pair of single quote characters such as 'a'. The syntax begins with a single backslash character.1. the default type when you write a floating-point literal is double. hex etc represents a number.3. or a nonprintable character as a character literal use an escape sequence.4 * 1038 +/. The letter d such as in the octal. Floating-pointliterals Floating-point numbers are like real numbers in mathematics. '#'. 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. The table below shows the codes that can represent these special characters. a backslash. BooleanLiterals The values true and false are also treated as literals in Java programming. and '3'.8 * 10308 Precision in decimal digits 6-7 15 19 . Type Size Name bytes bits Float 4 32 Double 8 64 Range approximate +/. An escape sequence uses a special syntax to represents a character.

however) Unary minus operator.01f String Literals The string of characters is represented as String literals in Java. use null literal. In this example an object is referenced by s. 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. Null Literals We specify the Null literal in the source code as 'null'. 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. as in this example the object is no longer referenced so it will be available for the garbage collection i. decrements a value by 1 20 . rather it is an object.5E+32 (or 6. The type of the null literal is always null. Now. We typically assign null literals to object reference variables. increments a value by 1 -.Decrement operator. We reduce the number of references to an object by assigning null to s. the compiler will destroy it and the free memory will be allocated to the other object.e. negates an expression ++ Increment operator. We represent string literals as String myString = "How are you?". For instance s = null. + Unary plus operator. 6.The following floating-point literals represent double-precision floating-point and floating-point values. In Java a string is not a basic data type.5E32) 7D . indicates positive value (numbers are positive without this.

 Convert 0010 1101 into decimal Rule: Multiply the digits by the posers of 2 and take the sum of the products. 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 .1 Binary Number System . 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 . Ex: for 45 we ‘ll get 101101.Convert 45 into binary. Rule: Divide the no successively by 2 and takes the remainders from bottom to top.! Logical compliment operator.0.

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 .

y=11.println(“x&y=:”+ (x&y)). x=10.out.out.out.y.println(“x<<2=:”+ (x<<2)). assignment operators are evaluated from right to left. System.println(“x^y=:”+ (x^y)).out.println(“~x=:”+ (~x)). 23 . 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. System.println(“x>>2=:”+ (x>>2)). System.out. System.out. } }  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. System. System.println(“x|y=:”+ (x|y)).

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

} Block: A group of statements written inside left and right curly braces. . It is absolutely system generated. package) Differences between #include and import . min() This is the min() function which distinguishes the minimum value from the two given value. sqrt() This is the sqrt() function which returns you the square root of the specified value.langString System.A method performs a task having a group of statements .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.e main() .Variables are memory locations to store values . random() This is the random() function which returns you the random number. Package : package is a sub directory containing group of class/interface Java library(group of packageclass/interfacemethodsjava.# include copies all lines of the header file into a C program Thus is waste the memory & processor time also. . max() This is the max() function which distinguishes the maximum value from the two given value. class First { Block of statements. pow() This is the pow() function which returns you the number raised to the power of a first given value by the another one. Import does not copy the libraries and #include copies.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.One method is needed to execute a java program i.void main(String args[]) 25 . rint() This is the rint() function which returns you a value closest to the given value.

2.- void (no value is returned. . } } . t.main().methodname(). Hello world (First java program) Java is a case sensitive programming language. Then call the method using ObjectName.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.out is an object of PrintStream class that object takes the input and gives the output on monitor.A static method is a method that is called and executed without an object.out. Obj.out is a method provided by Java software .System. 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. Ex: Test t=new Test(). Create an object to the class to which that method belongs. 26 .We cannot create an object to print stream class . className objname=new className().println(“welcome”).Out is a static variable .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(). . class Test { void main(String args[]) { Test t=new Test().System. System. .So to avoid this or to break the chain we use static methods.

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

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. 28 . ‘IsSizeOf’ is an operator but not a keyword Java is case sensitive In java every statement should end with . It will execute the . To find the address of particular memory location in java by using ‘hashcode’ of the object class.- 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. ‘NULL’ is not a keyword.class file & displays the output.

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

while. return) Selection . 30 . . do-while).Identifier and Primitive Data Types in java Identifier is a simple variable name which is defined as the value container. continue. . switch).In this section we will learn how to use if-then. the looping statements (for.This code gets executed if and only if the test evaluates to true.Java . The type of value stored by identifier is defined by the special java keyword is termed as primitive data type. if-then else and switch statements The if statement . if-then-else.The statement following the if will only be executed when the boolean expression evaluates to true. and the branching statements (break.That is the if statement in Java is a test of any boolean expression. 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.

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

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

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

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

35 . for (int j = 0. } } } The continue statement . j<=i. In this example. if we haven't use break statement thus the loop will continue and it will give the output as shown below.print("\n").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.Now observe the example of unlabeled form below.out. j++) { System. class BreaklabDemo1 { public static void main(String[] args) { for (int i = 0. We have used two loops here two print '*'.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. if (j==5) { // break.while statement . i < 10.out.print("*"). i++) { System. .

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

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

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

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

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

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

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

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

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

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.out.println("Area of a Rectangle=" +r. 3.println("Area of a Rectangle=" +r. System.println("Area of a Rectangle=" +r.Rect(5). r.Area()). Types of Constructors: 1. r. But there are many difference between the method(function) and the Constructor. Constructors are not required to call into main function explicitly. class Rectangle 45 . System. Constructor is the method which name is same to the class.Rect(). System. which is used to initialize the instance variables of a class. 4.{ return(length*breadth).*.Rect(9.Area()).Area()). r.out. } public static void main(String[] args) { Rectangle r=new Rectangle(). Constructor initiates(initialize) something related to the class’s methods. 2.4).io.out. } } Constructor: Constructor creates an instance for the class. Constructor does not return any values.

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

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

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.out. Rectangle r3=new Rectangle(9.out. that the car has four wheels .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. System.Area()).3).println("Area of a Rectangle=" +r2.println("Area of a Rectangle=" +r3.println("Area of a Rectangle=" +r1. Inheritance is the mechanism through which we can derived classes from other classes.Area()). To derive a class in java the keyword extends is used. System.out.} public int Area() { return(length*breadth). System. But the word car makes a more specific image in mind than vehicle. 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 . } public static void main(String[] args) { Rectangle r1=new Rectangle(). It concludes from the example that car is a specific word and vehicle is the general word. } } Inheritance Acquiring the properties of one class to the other class is called Inheritance It is the concept that is used for reusability purpose. Rectangle r2=new Rectangle(8).

println(x). } } class B extends A{ public static void main(String args[]){ A a = new A().out. } void display(){ System. y=q. a.Show(). The following kinds of inheritance are there in java. a.println("B"). int get(int p. int y.get(5. return(0).because every car has the features of it's parent (in this case vehicle) class. eg. 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. class A { int x. } void Show(){ System. } } 49 .6). int q){ x=p. In case of single inheritance there is only a sub class and it's parent class.out.

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

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

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

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

then a call to the method clone() on Myclass's object will give an error.g.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. Marker interfaces are Serializable. public void incrrace (int Obj). } Marker Interface . While the Clonable is an empty interface but it provides an important functionality. SingleThreadModel.Marker Interfaces are implemented by the classes or their super classes in order to add some functionality. - - Difference between Interfaces and abstract classes 54 . . 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. Clonable. to add this functionality one should implement the Clonable interface.g. public void changegear (int Obj). Electric switch is also the interface's example. Interface Definition visibility mode interface interfaceName{ constant variable declarations abstract method declarations } e. public interface RacingCar{ public void startcar (int Obj). Event listener. This means. public void stopcar (int Obj).Interfaces with no methods are known as marker interfaces. Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class. e.

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

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

This is the example of SringBuffer class and it's functions. 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). System.out.append(str). System.println(strbuf).append("Hello")."_Java "). 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. length() This is the length() function is used to finding the length of the buffered string. //print HelloWorld //print Hello_Java World //reverse() strbuf. System. //insert() strbuf.print("Reversed string : ").println(strbuf).readLine(). System.".reverse(). String str.length()).out. strbuf. strbuf. str = in.*.in)).print("Enter your name: ").) in the buffered string.io. str += ".println(strbuf).out.out. charAt() This is the charAt() function which is used to get the character at the specified position of the given string. System.insert(5.str.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. public class stringBuffer{ public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.out. //append() strbuf. capacity() This is the capacity() function is used to know about the current characters kept which is displayed like : number of characters + 6.delete(0. //Create a object of StringBuffer class StringBuffer strbuf = new StringBuffer(). //print dlroW avaJ_olleH 57 . import java.append("World").out. try{ System.println(strbuf). strbuf. 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.

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

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

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

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

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

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

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

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

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

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

The List interface follows. public class FindDups2 { public static void main(String[] args) { Set<String> uniques = new HashSet<String>().println("Duplicate words: " + dups). E element). //optional boolean addAll(int index.*. E set(int index. //optional E remove(int index).import java. //optional void add(int index. public interface List<E> extends Collection<E> { // Positional access E get(int index). } } The List Interface A List is an ordered Collection (sometimes called a sequence). System. for (String a : args) if (!uniques. Collection<? extends E> c).util. //optional // Search 68 .add(a)) dups. System. Lists may contain duplicate elements.out. // Destructive set-difference uniques. //optional boolean add(E element).add(a). 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.removeAll(dups). E element). Set<String> dups = new HashSet<String>().out.println("Unique words: " + uniques).

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

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

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

size(). inclusive.. 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. Calls to next and previous can be intermixed. there are n+1 valid values for index.} it. To make all this concrete. An initial call to previous would return the element whose index was index-1. The first call to previous returns the same element as the last call to next. The following figure shows the five possible cursor positions in a list containing four elements. The form with no arguments returns a ListIterator positioned at the beginning of the list. 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. Intuitively speaking.. Similarly. ) { Type t = it. 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.indexOf. The List interface has two forms of the listIterator method. and previousIndex returns the index of the element that would be returned by a subsequent call to previous. Note the argument to listIterator in the preceding idiom. It should also come as no surprise that the number returned by nextIndex is always one greater than the number returned by previousIndex. In a list of length n. The index refers to the element that would be returned by an initial call to next. but you have to be a bit careful. from 0 to n.previous(). .hasPrevious(). The five possible cursor positions. the first call to next after a sequence of calls to previous returns the same element as the last call to previous. The n+1 valid index values correspond to the n+1 gaps between elements. the form with an int argument returns a ListIterator positioned at the specified index. 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. from the gap before the first element to the gap after the last one. 72 . the following is a possible implementation of List.

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

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

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

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

Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement.lang package as java. such as logic errors or improper use of an API. These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from.- These exceptions cannot be anticipated and recovered like programming bugs. IndexOutOfBoundsException ArrayIndexOutOfBoundsException ClassCastException ArithmeticException NullPointerException IllegalStateException SecurityException Error – The errors in java are external to the application. This class can be instantiated and thrown by the program. 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. Here is the list of unchecked exceptions. This error will cause the program to terminate but if an application wants then the error might be caught. declared in 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. - - - 80 .lang. like arithmetic overflow.IOError would be thrown. divide by zero etc. Most such errors are abnormal conditions. 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. 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.Throwable.io.

only the exceptions are thrown by your code and not the errors. Well. The exception classes can be explained as well seeing the hierarchy structure: The java. 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. EXCEPTIONS DESCRIPTION CHECKED UNCHECKED Arithmetic ArithmeticException errors such as aYES divide by zero ArrayIndexOutOfBoundsException Arrays index isYES 81 . Remember that they are a member of Exception family and can be of type Checked or Unchecked exception.e.lang package defines several classes and exceptions. Some of these classes are not checked while some other classes are checked. Also Remember that they are a member of Error family.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. Sometimes it also happens that the exception could not be caught and the program may get terminated.

ClassNotFoundException IOException IllegalArgumentException InterruptedException NoSuchMethodException NullPointerException NumberFormatException not within array. if a thrown exception object has class IllegalArgumentException. Such as IllegalArgumentException.lang can be thrown if any method with an invalid argument is thrown . It depends upon the situation that whether to use an existing exception class from java. that indicates someone passed an illegal argument to a method. Moreover only those objects could be thrown whose classes are derived from Throwable. For example.lang or create any of your own. - 82 . a subclass of RuntimeException in java. Objects of your own design could also be thrown provided that they should be the subclass of some member of the Throwable family.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. Also the throwable classes which are defined by you must extend Exception class.

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

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

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

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

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

then the exception is dealt with by the default exception handler at the top level. 88 . normal execution is suspended. } catch (MyException exc) { exc. If no handler is found.0)). The runtime system proceeds to find a matching catch block that can handle the exception.println(divide(4. } } } 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.} public static void main(String[] args) { try { System.printStackTrace().out.

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

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

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

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

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

Returns the exception that caused the occurrence of current exception. 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. IOException{ try { int rs=10/0.util. throw new MyException("Chained ArithmeticException"). } } } 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. Thus the chain exception is thrown to next level of exception handler.getMessage()).err.printStackTrace() GetCause() InitCause() Returns the full name of the exception class and some additional information apart from the information of first two method. } Lets see an example having the implementation of chained exceptions: import java.*. } catch(Exception e) { System. class MyException extends Exception{ MyException(String msg){ super(msg). System. Returns the current exception due to the Throwable constructors and the Throwable argument to initCause. } } public class ChainExcep{ public static void main(String args[])throws MyException. try { } catch (IOException e) { throw new TestException("Other IOException". e). import java.io.err.println(e. 94 .*.getCause()).println(e.

len = str.. System..length() . try{ StringBuffer sbuf = new StringBuffer(str).. } } } MultiThreading Multitasking Multitasking allow to execute more than one tasks at the same time...out.println("Got an IOException: " + e. Lets see an example that prints an exception's message....charAt(ct)). a task being a program..Try { // . 95 . For Example running the spreadsheet program and you are working with word processor also. Multitasking is running heavyweight processes by a single OS.printStackTrace()..out.print(sbuf... } - 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...ct--){ System.. } } catch(Exception e) { e. int len=0. In multitasking only one CPU is involved Multitasking allow processes (i. for(int ct=len. Public class PrintStack{ public static void main (String args[]){ String str = "Exception" .getMessage()). programs) to run concurrently on the program.e. } catch (IOException e) { // .ct>=0.

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

The main() method execution can finish. called the main thread. At this point. If no other threads are created by the main thread. then program terminates when the main() method complete its execution. The main thread creates some other threads called child threads. Main Thread When any standalone application is running. it firstly execute the main() method runs in a one thread.A thread start its life from Runnable state. 97 .- Diagram shown below in which a thread is executed along with its several operations with in a single process. Runnable (Ready-to-run) 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.

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

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

In Java. MyThread m2=new MyThread("My Thread 2"). try{ Thread. } } Thread Priorities . }catch(Exception e){} } } } public class MultiThread1{ public static void main(String args[]){ System. . } public void run(){ for(int i=0.MIN_PRIORITY any thread (an int value of 10) The minimum priority of Thread.MAX_PRIORITY any thread (an int value of 1) The normal priority of any Thread.getName()). MyThread m1=new MyThread("My Thread 1").Priorities are integer values from 1 (lowest priority given by the constant Thread. start().out.class MyThread extends Thread{ MyThread(String s){ super(s).currentThread().MAX_PRIORITY).NORM_PRIORITY).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 .Thread gets the ready-to-run state according to their priorities. Constant Description The maximum priority of Thread.i++){ System. 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 . . . .out.getName()).sleep(1000).i<5.MIN_PRIORITY) to 10 (highest priority given by the constant Thread.The default priority is 5(Thread.println("Thread Name :" +Thread.The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.

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

getPriority().println("Thread Priority :"+cur).i++){ Thread cur=Thread. likewise Thread2 need the keyboard that is hold up by the Thread1. this situation is known as Deadlock. } } DeadLock A situation where a thread is waiting for an object lock that holds by second thread.out.out. 106 .println("Thread Name :"+Thread.currentThread(). cur. start().getName()). 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. System.setPriority(Thread. MyThread2 m2=new MyThread2("My Thread 2").} } class MyThread2 extends Thread{ MyThread2(String s){ super(s). } } } public class ThreadPriority{ public static void main(String args[]){ MyThread1 m1=new MyThread1("My Thread 1"). } public void run(){ for(int i=0. System.currentThread(). int p=cur. and this second thread is waiting for an object lock that holds by first thread.MAX_PRIORITY). But Thread1 need to printer that is hold up by the Thread2.i<3.

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

"a". 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". This technique is known as Interthread communication which is implemented by some methods.sleep(1000).Synchronized statements must specify the object that provides the native lock. Share t2=new Share("Thread Two: "). Share(String threadname){ super(threadname). } } - Inter-Thread Communication A process where. These methods are defined in "java. } public void display(String threadN){ synchronized(this){ for(int i=0. }catch(Exception e){} } } public class SynStatement { public static void main(String[] args) { Share t1=new Share("Thread One: ").start(). try{ this.out.start(). "is".i<=4.i++) System. t2. t1.lang" package and can only be called within synchronized code shown as: 111 . "synchronized". } public void run(){ display(getName()). The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.println(threadN+msg[i]). 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. "variable"}.

} System. All these methods must be called within a try-catch block. boolean value = false.out. } this. Method 112 . Producer(Shared s) { this. } catch (InterruptedException e) { System. notify(). } catch (InterruptedException e) { System. } } class Producer extends Thread { Shared s.println("InterruptedException caught"). System. value=false.println("consume: " + num). synchronized int get() { if (value==false) try { wait(). The highest priority thread will run first. notify(). } synchronized void put(int num) { if (value==true) try { wait().s=s.out. return num. notifyAll( Wakes up (Unloack) all the threads that called wait( ) on ) the same object. Lets see an example implementing these methods : class Shared { int num=0.println("Produce: " + num). It wakes up the first thread that called wait() on the same notify( ) object.out.start().out.println("InterruptedException caught").num=num.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(). this. value=false.

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

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

An input source can be a file.InputStream: The InputStream class is used for reading the data such as a byte and array of bytes from an input source. An input stream is automatically opened when you create it. 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. a string. or memory that may contain the data. The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown below: - 115 .

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

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

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

It has character read source. It writes bytes and decodes them into characters. This is a character stream reader and reads the data push back into the stream. This class also connected into a piped output stream. It also include the another function of input stream. This is a serializable permission class. It takes an input stream and parse it into "tokens" . It is a piped character-input stream.ObjectOutputStream. This is also a character string class. It creates communication between both. It is a piped character-output stream. This class also communicates the piped input stream into piped output stream. This class adds the functionality of another output stream. This class represents an output stream of bytes. It supports both reading and writing to a random access file. Interfaces: 119 .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 represents the logical concatenation of other input stream. In this class the data bytes are written into piped output stream. It uses for writing to character stream. This class adds the functionality of another input stream. The token to be allowed at the read time. This is a character string class. Such as: "push back" or "unread" one byte. It uses to shows the output in the buffer. This class describes the serializable field. It used for reading character stream. Serialization's descriptor for classes.

This interface used for Constants writing into Serialization Objects Stream.Serializable interface. This is a Callback interface. It allows the validation of objects within a graph.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. 120 .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. DataOutput This interface can be used for writing the byte stream and converting data from the java primitive data types.The following summary of Interfaces provided by the java. It can be used for Filtering the Pathnames. This interface used for reading of objects and it extends the DataInput interface. When the file input stream to be end then EOFException to be occuted.io. FileNotFoundException When the open file's pathname does not find then this exception to be occured. This is written in Serializable Stream. This interface implementing java. in the Externalizable FileFilter FilenameFilter ObjectInput ObjectInputValidation ObjectOutput ObjectStreamConstants Serializable Exceptions Classes: The following summary of the exception classes provided by the java. This interface used for writing of objects and it extends the DataOutput interface. It save and store it's contents. This interface used for Filter the Filenames.

then The Character Encoding is not supported. This is a supper class of all exception class. Any problems to be created with class. 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. It used for specific to Object Stream Classes. A molformed UTF-8 has been read in a data input stream. This exception when the instance is required to a Serializable interface. In this exception to be thrown by the ObjectStreamException during a write operating. it implemented by data input 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. SyncFaieldException UnsupportedEncodingException UTFDataFormatException The sync operation is failed SyncFaieldException to be occure. when the Serializing runtime to be detected. WriteAbortedException 121 . The Serialization or deserialization operations are not active then it occurs. When the I/O operations to be failed then it occurs.

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

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

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

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

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

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

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

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

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

FileWriter The FileWriter is a class used for writing character files. arrays. and strings. //Close the output stream out.e. buffering characters so as to provide for the efficient writing of single characters.println("Error: " + e. import java.err.txt".close().io. 131 .Java Tutorial Introduction .true). 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.*. the pre-exist data in a file is not overwritten and the new data is appended after the pre-exist data. Program takes the file name through the keyboard and checks whether the file exists. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. class FileWrite { public static void main(String args[]) { try{ // Create file FileWriter fstream = new FileWriter("out. out. 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. } } } Getting the Size of a File in Java Introduction How to get the size (in bytes) of a specified file. BufferedWriter The BufferWriter class is used to write text to a character-output stream. }catch (Exception e){//Catch exception if any System.getMessage()). BufferedWriter out = new BufferedWriter(fstream).the class FileWriter and BufferedWriter to append the data to a file.write("Hello Java"). About the methods that can be used to get the file size.Append To File .

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

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

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

Advantages of Applet: • • • • • • Applets are cross platform and can run on Windows. Applet can't access system resources on the local computer. Java applets runs on the java enabled web browsers such as mozila and internet explorer . so the user does not need to trust the code. Mac OS and Linux platform Applets can work all the version of Java Plugin Applets runs in a sandbox.} } } Applets Introduction Applet is java program that can be embedded into HTML pages. Applets don't have the main method while in an application execution starts with the main method. 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. 135 . Applets can run in our browser's window or in an appletviewer. Applets are designed for the client site programming purpose while the applications don't have such type of criteria. 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. are the small programs while applications are larger programs. so it can work without security approval Applets are supported by most web browsers Applets are cached in most web browsers. Applets are used to make the web site more dynamic and entertaining. To run the applet in an appletviewer will be an advantage for debugging.

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

probably the browser will ignore the <APPLET> and <PARAM> tags that doesn't understand the <APPLET> tag.- 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. 137 . Applets read user-specified values for parameters with the getParameter() method. Java-compatible browsers ignore this extra HTML code. 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. - < PARAM NAME = appletParameter1 VALUE = value > The only way to specify applet-specific parameters is to use the <PARAM> tags. The init() method is basically called to read the PARAM tag in the html file. There is only miner difference between the start() method and stop () method. Start () method: The start method of an applet is called after the initialization method init(). The init() method is called only one time in the life cycle on an applet. In the start method user can interact within 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 if the user wants to return to 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. This method may be called multiples time when the Applet needs to be started or restarted. alternateHTML If we use this <applet> tag in an HTML page to be viewed by the browser. 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. destroy() method: The destroy() method is called only one time in the life cycle of Applet like init() method. 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.

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

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

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

setColor(Color.drawString("Circle".setColor(Color. So.red).drawLine(3. 100 ).Graphics.fillRect( 400.100.magenta). g.applet. g.y=100. //Drawing line color is red g.yellow). g.*.fillRect() : This is the fillRect() method used to fill the color inside the rectangle by specified color.100).y-r. 100 ). 200.fillRect(int X_coordinate.200.setColor(Color. 50. 141 . public class ShapColor extends Applet{ int x=300.100).50.*. int height) import java.drawString("Rectangel". g. public void paint(Graphics g){ g. } } 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.magenta). 100.275.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. import java.awt. you can pass the parameters from your html page to the applet embedded in your page. g.450. g.magenta).100. g.100).drawOval(x-r.r=50. //Fill the yellow color in circle g.y-r.drawRect(400.200. g.100).fillOval( x-r.yellow).10). int Y_coordinate. g.setColor(Color.100). g. int Wdth.setColor(Color.setColor(Color.drawString("Line".300. Here is the syntax of the fillRect() method : g. //Fill the yellow color in rectangel g.

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

All Java Swing classes imports form the import javax. And they are not allowed to manipulate the threads outside the applets own thread group. Applet is not allowed to create the reference of their own class loader. 143 .- 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. extended.class file. Compile the program : javac appletParameter. overridden. Alternatively you can also run this example from your favorite java enabled browser. Applets are not allowed to invoke any program to list the contents of your file system that means it cant invoke System.html Appletviewer will run the applet for you and and it should show output like Welcome in Passing parameter in java applet example. 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.*. Then the system class loader can not be overloaded. - 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. They cant load the libraries or define the native method calls. with codebase taking precedence. except for the host. package. which provided the . Because the html page come from the host or the host specified codebase parameter in the applet tag.swing. They are also prevented from starting other programs on the client. Applets are loaded over the net. replaced. A web browser uses only one class loader that’s established at start up. go to command prompt and type appletviewer appletParameter.exit() function to terminate you web browser.java Output after running the program : To run the program using appletviewer.

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

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

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

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

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

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

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

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

package. 152 . 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.) "Yes" and "No" 2. A message dialog box which has two or three buttons. 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".swing.e. The window for showing message for input or output makes your application very innovative.*. "No" and "Cancel" 3. 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. "Ok".Show Dialog Box in Java . You can set several values for viewing several message dialog box as follows: 1.) "Ok". and "Cancel" A input dialog box which contains two buttons "Ok" and "Cancel". JOptionPane class is available in the javax. The JOptionPane class has three methods as follows: • showMessageDialog(): First is the showMessageDialog() method which is used to display a simple message.) "Yes".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. Program description: JOptionPane Class: In non-swing application we were using System. This class provide various types of message dialog box as follows: • • • • • A simple message dialog box which has only one button i. In this section we will use JOptionPane class to display the message Dialog box.

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

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

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

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

setText(str). public class ComboBox{ JComboBox combo. 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.setDefaultCloseOperation(JFrame.gray).awt."PPC". Here. JTextField txt."MCA". combo.setBackground(Color.setSize(400. } }).*. itemStateChanged(): This is the method which receives the ItemEvent generated by the addItemListener() method of the JComboBox class. Here is the code of program: import javax. frame.*. import java.awt.add(combo). panel.add(panel).getSelectedItem(). combo = new JComboBox(course).EXIT_ON_CLOSE). frame. JPanel panel = new JPanel().event. JFrame frame = new JFrame("Creating a JComboBox Component"). frame.add(txt).foreground color is red. txt. combo. frame. import java.setForeground(Color. 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. } public ComboBox(){ String course[] = {"BCA". txt = new JTextField(10).red)."CIC"}.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent ie){ String str = (String)combo. When you select the item from the combo box then the selected item is displayed in the text box. panel. combo.swing. public static void main(String[] args) { ComboBox b = new ComboBox().*.400).setVisible(true). The event is generated when you select item from the combo box. } } 157 .

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.*. package. 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.". This program shows a text field. first is for the adding items to the combo box and another is for the removing items from the combo.Combo Box operation in Java Swing In this section. This method takes a string argument which is to be used to add 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.swing. 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.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 above code has been used to create a combo box in this program. 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). removeItemAt(index): This is the method of the JComboBox class which remove the item at the specified 158 . showMessageDialog(): This the method of the JOptionPane class of javax. This method displays some messages in the special dialog box. The JComboBox instance combo is created using the constructor of the JComboBox class of the javax. you can learn how to operate the Combo Box component. This constructor holds the string array in which items for the combo box are kept. 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. remove items from the combo box. package. a combo box and two command buttons. you will learn how to add items to the combo box.

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

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

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

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

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

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

events on the JSlider component have also been shown. For creating the slider this class creates a instance using it's constructor JSlider(). There is minimum chances of being mistake to illegal input values. frame.setDefaultCloseOperation(JFrame.} } frame. In this program. If you increase or decrease the slider by selecting then the actual position of the slider will be displayed on a label. A Slider is a Swing tool which you can use for selecting a range. Methods and APIs are as follows: JSlider: This is the class which creates the slider for the swing application. ChangeEvent: This is the class which handle the event generated by the JSlider component on change the state. JSlider Component of Java Swing In this section. 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.EXIT_ON_CLOSE).setVisible(true). 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. 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.

swing.swing.setVisible(true).getValue().toString(value).*. slider = new JSlider().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.EXIT_ON_CLOSE).awt. slider. JPanel panel = new JPanel(). Here is the code of the program: import import import import javax. } } } Progress Bar in Java Swing 166 . } public class MyChangeAction implements ChangeListener{ public void stateChanged(ChangeEvent ce){ int value = slider. String str = Integer. public class CreateSlider{ JSlider slider. java.*.event. label = new JLabel("Roseindia.event.awt.add(panel. javax. 400).*. public static void main(String[] args){ CreateSlider cs = new CreateSlider(). label.add(label). frame. frame. panel.add(slider). panel. frame. JLabel label. frame.setDefaultCloseOperation(JFrame.net").setSize(400.addChangeListener(new MyChangeAction()). slider. java.setValue(70). BorderLayout. } public CreateSlider(){ JFrame frame = new JFrame("Slider Frame").setText(str).CENTER).*.

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

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

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

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

add(editmenu). 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. you will learn how to create a Popup menu in Java.add(editItem4). menubar.setVisible(true). Following figure shows the popup menu when you right click on the frame: This program illustrates you about the creation of the popup menu. This method returns true if the event is generated when the popup is triggered. frame.add(filemenu).event. mouseReleased This is the method of the FormView. Create a Popup Menu in Java Here. editmenu. frame.add(editItem2).setSize(400. package. frame.setJMenuBar(menubar).} } editmenu. editmenu.*. menubar.MouseEventListener class which is imported from 171 .awt.add(editItem3). isPopupTrigger(): This is the method of the MouseEvent class of the java. This method returns a boolean type value either true or false. This class is helpful to add the object of the JMenuItem class which creates a particular menu. Popup menu is the list of menu which is displayed at that point on the frame where you press the right mouse button.400).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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. 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 .

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. the MouseAdapter class implements the MouseListener interface. Thus. For instance. An adapter class can be used by creating a subclass of it and then overriding the methods which are of use only. mousePressed. the methods which you do not want to care about can have empty bodies. 192 . mouseReleased etc.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. we have adapter class. For instance. That is some of the listener interfaces contain more than one method. Adapter classes help us in avoiding the implementation of the empty method bodies. the MouseListener interface contains five methods such as mouseClicked. Generally an adapter class is there for each listener interface having more than one method.

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

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

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

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

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

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

Import java.".jpeg or .400). frm.*.setSize(400.getDefaultToolkit(). frm. frame. public class AwtSetIconOfFrame{ public static void main(String[] args){ Frame frame = new Frame("Icon setting for the Awt Frame").400).setVisible(true).CENTER). Label lbl = new Label("Welcome to Tutorial. frame.gif"). Toolkit class is used to bind the various components to particular native toolkit implementations.Label. frm. height (int).This method retrieves the pixels data of the image which can be either in format of .add(lbl).gif. Label lbl = new Label("Welcome to Tutorial. } } 199 .This is also a method of the Frame class sets the visibility of the frame. public class AwtFrame{ public static void main(String[] args){ Frame frm = new Frame("Java AWT Frame"). frame.setIconImage(icon). import java.". . } } 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.setVisible(true).CENTER).getImage("icon_confused. Image icon = Toolkit.awt. getDefaultToolkit(): .setSize(400. setVisible(boolean): . frame.*.png. getImage(url or filename): .add(lbl). The frame will be invisible if you pass the boolean value false otherwise frame will be visible.- This is the method of the Frame class that sets the size of the frame or window. 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.awt.This method returns the default toolkit.Label. This method takes two arguments width (int).

frame. } }). windowClosing() : .setSize(400. addWindowListener() : .setVisible(true).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. frame.awt.event.*. package. 200 .Label.*.awt. public class AwtCloseButtonEvent{ public static void main(String[] args){ Frame frame = new Frame("Close Operation Frame").*.*. 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. WindowAdapter() : .CENTER).exit(0). This method receives the WindowEvent object.This is the addWindowListener() method which adds the window listener to receive the window event from the window.e. frame. Label lbl = new Label("Welcom in Tutorial".400). closing the frame).event.add(lbl).addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.*.awt.awt.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.This is the constructor of the WindowAdapter class of the java. This is an abstract class used for receiving window events. import java.awt. frame. This method passes the window listener. } } Making a Frame Non Resizable in Java import java.event. The close button of the frame has to be set for the desired operation (i. Import java. import java.

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

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

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

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

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

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

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

setVisible(false): This method takes a boolean valued argument which decides the form for visible or not. public class ButtonText { public static void main(String[] args) { 208 .event.*. fa.*. fa.add(l1).setSize(300.event. FlowLayout(): This is the constructor of FlowLayout class. frame. fa. 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.awt. here this method is used for the WindowEvent class so.setVisible(true). } }). By default Java Awt Form is in the invisible state.getSource().awt. Here is the code of this program: import java. import java.add(p). 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. fa.*. The getSource() method returns the source of the generated event.getSource(): This is the method of EventObject class. This class is used for arranging the component from left to right.setVisible(false). p. public class FrameHide{ public static void main(String[] args){ Frame fa= new Frame("Frame Hiding").*. } } 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. import java.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ Frame frame = (Frame)e.200). it can return the Form's object that is done invisible by using the setVisible() method. Panel p =new Panel(). Label l1=new Label("Welcome").awt. Hence.awt. import java.

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

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

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

Sign up to vote on this title
UsefulNot useful