Você está na página 1de 112

Java Basic Chapter - 1

1. What is Programming? Programming or coding is a language that is used by operating systems to perform the task. We know computer understands binary languages with digits 1s and 0s. These binary languages are difficult to understand by human; so we generally use an intermediate language instead of binary language. Again the program uses high-level language that is interpreted into bytes that the computer understands. So a programmer writes a source code and uses a tool or interpreter that allows the computer to read, translate and execute the programs to perform a function. 2. What is Java? Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated with the World Wide Web but it is older than the origin of Web. It was only developed keeping in mind the consumer electronics and communication equipments. It came into existence as a part of web application, web services and a platform independent programming language in the 1990s. 1. Earlier, C++ was widely used to write object oriented programming languages, however,it was not a platform independent and needed to be recompiled for each different CPUs. 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. They wanted to make it new software based on the power of networks that can run on different application areas, such as computers and electronic devices. In the year 1991 they make platform independent software and named it Oak. But later due to some patent conflicts, it was renamed as Java and in 1995 the Java 1.0 was officially released to the world. Java is influenced by C, C++, Smalltalk and borrowed some advanced features from some other languages. The company promoted this software product with a slogan named Write Once Run Anywhere that means it can develop and run on any device equipped with Java Virtual Machine (JVM). This language is applicable in all kinds of operating systems including Linux, Windows, Solaris, and HP-UX etc. 3. Where Java is used? Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the`

primary motivation was the need for a platform-independent (that is, architecture-neutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. As you can probably guess, many 1. different types of CPUs are used as controllers. The programming language Java was developed by Sun Microsystems in the year 1995. Earlier, it was only used to design and program small computing devices but later adopted as one of the platform independent programming language. The most important feature of Java is its byte code that can be interpreted on any platform including windows, Linux etc. One can also download it freely from the official website of Sun.

As we have mentioned above that 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.

As far as syntax is concerned, Java is similar as the C programming language but a distinct style of coding. It follows all the general programming features like loops, data types, conditions, curly braces, semi-colon etc. Its a fully featured Object Oriented Programming (OOP) language as it supports all OOP features including classes, modules, inheritance, Polymorphism etc.

Mobile Java - Besides the above technology, Java is also used for various entertainment devices especially mobile phone. Mobile Information Devices Profile (MIDP) uses Java run time environment in cell phones, mobile tracking systems and other traditional PDA devices. Java technology enabled application is key to the games and services available in the mobile world. This also plays an important role in the field of telemedicine such as PulseMeter. As far as mobile technology is concerned, it offers offline facility, so that users can get service even if they face loss of connection. Today, all leading mobile service provider like Nokia, Siemens, Vodafone are using Java technology. Sun Java Wireless Toolkit offers complete support for developing different MIDP application. Java technology is enabled with healthy content ecosystem by offering a healthy development and deployment environment, protecting users and operators from down time and viruses. The increase volume of users now encouraging manufactures and developers to apply Java technology in numerous other productive and functional ways including MP3 players, digital TV, video, 3D, simplifying games, etc. Java Releases (The

Creation of Java )

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called Oak, but was renamed Java in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype. Java is developed by Sun Microsystems in 1996. Now the Java is powerful tools for the development of robust and scalable enterprise applications. The tables given below provide information about the name and time of releases for different versions of Java technology.

Releases Event Month Java 1.5.0_09 October Java 1.5.0_08 August Java 1.5.0_06 December Java 1.5.0_05 October 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

Year 2006 2006 2005 2005 2005 2005 2002 2000 1999 1999

Java Development Kit 1.2 (JDK 1.2) Java Development Kit 1.1 (JDK 1.1) Java Development Kit 1.0 (JDK 1.0)
Downloading JDK (Java)

December February January

1998 1997 1996

What is JDK (Java Development Kit) ?


JDK 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. If you are beginner or learning Java then start by downloading J2SE. Acronyms: JDK Java Development Kit JVM Java virtual machine Download JDK You can download JDK from www.javasoft.com/j2se Installing Java Downloading and Installing J2SE Software on Windows Platform To download J2SE for development visit http://www.java.sun.com/j2se and download J2SE on your machine. In this tutorial we have used jdk-1_5_0_06-windows-i586.exe.The java 2Platform or (JDK) can be downloaded from the sun. Formerly Known as the java Development kit ,or JDK, Downloading java is really about downloading the java 2 plat form that comes in three editions , J2ME, J2SE and J2EE , if you are learning java, then, you should start by downloading J2EE. Once you have downloaded the j2se on your system, you are ready to install . In the following section we will learn how to install jdk development environment on your machine. here are the step to install JDK on your windows machine. Step 1

Double click the JDK down loaded file, the executable extracts the required Contents to the temporary directory and then License agreement screen appears. On the license agreement page read and accept the license and the click the next button .

Step 2 The custom setup screen appears as follows.

Step 3 Click on the change button to change the installation directory to "c:\jdk1.5.0_06" as shown in the following screen.

and click on the "OK" button. After clicking on the "OK" button installation begins:

Step 4 In the next window installer asks for the installing the runtime as shown in the following screen:

Step 5 Click on next button install the J2SE runtime on your machine. Next screen shows the browser selection:Click on the "Next" button.

Step 6 Once the installation is finished it shows you the final screen indications the success. Now you have successfully installed J2SE on your machine. Installer shows the following final confirmation window as

shown below: Click on the "Finish" button to exit from the installer. Configuring the installation on windows machine: In this Section we will add some settings to the windows environment so that the java compiler and runtime becomes available for compiling and running the java application. Go to the control panel and double click on "System Properties" and to to the advance tab.

and add "c:\jdk1.5.0_06" to path variable:

and click on ok button. To save the setting click on "OK" button. Understanding Java SDK Directory Structure This section introduces the Directory and file structure of SDK (Software Development Kit). The following figure shows jdk1.5.0 software stored in 'c' directory that has multiple subdirectories like bin, demo, include and jre etc. to hold all important developing and testing tools. See detail information bellow. SDK Directory Structure:

Subdirectories of the SDK: The jdk1.5.0 has following directory:

Bin directory - The bin directory provides all inessential tools for developing and testing the program through the help of command provided by Java compiler. Demo directory - This directory consists many applications and applets with source code. Include directory - It contains all header files like for 'C' programming language that enables you to combine C code into a Java program. Jre directory - When you run any java program then you have to compile it by the help of Java interpreter or Java Runtime Environment (JRE). The SDK uses the internal adaptation of JRE, which containing in the jre root directory. Lib directory - This is a most important directory for development tools that contains libraries and it's supported files. Docs directory - It is the last directory of Software Development Kit that assists you to store the Java documents. The docs directory is an optional directory. Files of the SDK: JDK1.5.0 directory has following files that provide the detail information about it. README.html : The jdk1.5.0 directory provides an html file that contains the detail information of SDK shown on the web browser. This file contains all system requirements, features and documentation links to represents all information's about the jdk1.5.0. scr.zip: The zip file is a collection of one of more files that has been compressed or stored to '.zip' extension. Similarly, the scr.sip file contains the source code of SDK. It become necessary to extract the file that contain the source code from the ZIP file. Writing Hello World Java program Java is a high level programming language and it is used to develop the robust application. Java application program is platform independent and can be run on any operating System. Writing Hello World program is very simple. To write the Hello world program you need simple text editor like note pad and jdk must be install in your machine for compiling and running. Hello world program is the first step of java programming language. Be careful when you write the java code in your text pad because java is a case sensitive programming language.

For Example hello world !=(not equal to) Hello World Write the following code into your note pad to run the Hello World program .

class HelloWorld { public static void main(String[] args){ System.out.println("Hello World!"); } }


Save the file and Please remember the location where you save your file. In this example we have saved the file in the "C:\javatutorial\example" directory. The file name should be match the class name and to save the file give the .java extension. e.g. HelloWorld.java Now open the command prompt to compile the HelloWorld.java program. 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.java javac is a compiler in the java Language. Java compiler change the programming Language into machinery language. So that the java virtual can understand it. Once the compilation is successful a new file will be created with the name HelloWorld.class. 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. Hello World! Here is the screen shot of the above steps:

In this lesson you have learned how to write and then test the Hello World! java program. Understanding Hello World Java Program Now you are familiar with the Java program. In the last lesson you learned how to compile and run the Java program. Before start hard programming in Java, its necessary to understand each and every part of the program. Lets understand the meaning of public, class, main, String[] args, System.out, and so on.

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }

Class Declaration: Class is the building block in Java, each and every methods & variable exists within the class or object. (instance of program is called object ). The public word specifies the accessibility of the class. The visibility of the class or function can be public, private, etc. The following code declares a new class "HelloWorld" with the public accessibility: public class HelloWorld {

The main Method:


The main method is the entry point in the Java program and java program can't run without main method. JVM calls the main method of the class. This method is always first thing that is executed in a java program. Here is the main method: public static void main(String[] args) { ...... .....

} { and is used to start the beginning of main block and } ends the main block. Every thing in the main block is executed by the JVM. The code: System.out.println("Hello, World"); prints the "Hello World" on the console. The above line calls the println method of System.out class. The keyword static: The keyword static indicates that the method is a class method, which can be called without the requirement to instantiate an object of the class. This is used by the Java interpreter to launch the program by invoking the main method of the class identified in the command to start the program..

Chapter 2
DATA TYPES
Java programming language is a language in which all the variables must be declared first and then to be used. That means to specify the name and the type of the variable. This specifies that Java is a stronglytyped programming language. Like int pedal = 1; This shows that there exists a field named 'pedal' that holds a data as a numerical value '1'. The values contained by the variables determines its data type and to perform the operations on it. There are seven more primitive data types which are supported by Java language programming in addition to int. A primitive data type is a data type which is predefined in Java. Following are the eight primitive data types: int It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647. This data type is used for integer values. However for wider range of values use long. byte The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). We can save memory in large arrays using byte. We can also use byte instead of int to increase the limit of the code. short The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. shortis used to save memory in large arrays. long The long data type is a 64-bit signed two's complement integer. It ranges from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range of values. float The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float (instead of

double) to save memory in large arrays. We do not use this data type for the exact values such as currency. For that we have to use java.math.BigDecimal class. double This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data type is generally the default choice for decimal values. boolean The boolean data type is 1-bit and has only two values: true and false. We use this data type for conditional statements. true and false are not the same as True and False. They are defined constants of the language. char The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535. They are not same as ints, shorts etc. The following table shows the default values for the data types:

Keyword Description Byte-length Byte integer short Int long Float 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 32-bit IEEE 64-bit IEEE 16-bit Unicode character true or false

Single-precision floating point Double-precision double floating point A single char character A boolean value boolean (true or false)

When we declare a field it is not always essential that we initialize it too. The compiler sets a default value to the fields which are not initialized which might be zero or null. However this is not recommended.

String
The String type is used to declare string variables. You can also declare arrays of strings. Aquoted string constant can be assigned to a String variable. A variable of type String can be assigned to another variable of type String. You can use an object of type String as an argument to println( ). For example, consider the following fragment:

String str = "this is a test";

System.out.println(str);

Here, str is an object of type String. It is assigned the string this is a test. This string is displayed by the println( ) statement what is type casting? Type Casting refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If you will store a int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change the type of resultant data which has to be stored. This type of operation has illustrated below :

Chapter 3
DATA - TYPE CONVERSION / TYPE CASTING
In this example we will see that how to convert the data type by using type casting. In the given line of the code c = (char)(t?1:0); illustrates that if t which is boolean type variable is true then value of c which is the char type variable will be 1 but 1 is a numeric value. So, 1 is changed into character according to the Unicode value. But in this line c = (char)(t?'1':'0'); 1 is already given as a character which will be stored as it is in the char type variable c. Code of the program : public class conversion{ public static void main(String[] args){ boolean t = true; byte b = 2; short s = 100;

char c = 'C'; int i = 200; long l = 24000; float f = 3.14f; double d = 0.000000000000053; String g = "string"; System.out.println("Value of all the variables like"); System.out.println("t = " + t ); System.out.println("b = " + b ); System.out.println("s = " + s ); System.out.println("c = " + c ); System.out.println("i = " + i ); System.out.println("l = " + l ); System.out.println("f = " + f ); System.out.println("d = " + d ); System.out.println("g = " + g ); System.out.println(); //Convert from boolean to byte. b = (byte)(t?1:0); System.out.println("Value of b after conversion : " + b); //Convert from boolean to short. s = (short)(t?1:0); System.out.println("Value of s after conversion : " + s); //Convert from boolean to int. i = (int)(t?1:0); System.out.println("Value of i after conversion : " + i); //Convert from boolean to char. c = (char)(t?'1':'0'); System.out.println("Value of c after conversion : " + c); c = (char)(t?1:0); System.out.println("Value of c after conversion in unicode : " + c); //Convert from boolean to long. l = (long)(t?1:0); System.out.println("Value of l after conversion : " + l); //Convert from boolean to float. f = (float)(t?1:0); System.out.println("Value of f after conversion : " + f); //Convert from boolean to double. d = (double)(t?1:0); System.out.println("Value of d after conversion : " + d); //Convert from boolean to String. g = String.valueOf(t); System.out.println("Value of g after conversion : " + g); g = (String)(t?"1":"0"); System.out.println("Value of g after conversion : " + g); int sum = (int)(b + i + l + d + f); System.out.println("Value of sum after conversion : " + sum); } }

Chapter 4
OPERATORS
Simple Assignment Operator
= Simple assignment operator

Arithmetic Operators
+ * / % Additive operator (also used for String concatenation) Subtraction operator Multiplication operator Division operator Remainder operator

Unary Operators
+ ++ -! Unary plus operator; indicates positive value (numbers are positive without this, however) Unary minus operator; negates an expression Increment operator; increments a value by 1 Decrement operator; decrements a value by 1 Logical compliment operator; 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


instanceof Compares an object to a specified type

Bitwise and Bit Shift Operators


~ << >> Unary bitwise complement Signed left shift Signed right shift

>>> & ^ |

Unsigned right shift Bitwise AND Bitwise exclusive OR Bitwise inclusive OR

The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each operation. In the discussion that follows, keep in mind that the bitwise operators are applied to each individual bit within each operand.
A 0 1 0 1 B 0 0 1 1 A|B 0 1 1 1 A&B 0 0 0 1 A^B 0 1 1 0 ~A 1 0 1 0

The Bitwise Logical Operators

Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its operand. For example, the number 42, which has the following bit pattern:
00101010 becomes 11010101 after the NOT operator is applied.

The Bitwise NOT

The Bitwise AND


The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all other cases. Here is an example:
00101010 & 00001111 00001010 10 42 15 10

The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the resultant bit is a 1, as shown here:
00101010 | 00001111 00101111 42 15 47

The Bitwise XOR


The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1.

Otherwise, the result is zero. The following example shows the effect of the ^. This example also demonstrates a useful attribute of the XOR operation. Notice how the bit pattern of 42 is inverted wherever the second operand has a 1 bit. Wherever the second operand has a 0 bit, the first operand is unchanged. You will find this property useful when performing some types of bit manipulations.
00101010 ^ 00001111 00100101 42 15 37

The Left Shift


The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times. It has this general form: value << num

byte a = 64, b; int i; i = a << 2; OUTPUT i=256 The Right Shift


The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its general form is shown here: value >> num

int a = 32; a = a >> 2; // a now contains 8 int a = 35; a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens: 00100011 35 >> 2 00001000 8

Chapter 5
Comparing Two Numbers

the method of comparing two numbers and finding out the greater one. First of all, name a class "Comparing" and take two numbers in this class. Here we have taken a=24 and b=25, now we have to find out whether a=b, a>b or b>a. To find out this apply if and else condition one by one. Now apply the condition "if (a=b)", if this satisfies then type that both are equal in the system class. If this doesn't satisfy, then check whether a>b by applying the "else if" condition and type the message "a is greater than b" in the system class. Again this doesn't satisfy then 'else' condition as shown in the example will show that b is greater than a. Now compile and run the program and you will find the desired output. If you are getting any error then check the whole program thoroughly and surely you will get correct result. By compiling and running this exact program, you will find that b is greater than a. class Comparing { public static void main(String[] args) { int a=24, b=25; if (a == b) { System.out.println("Both are equal"); } else if(a>b) { System.out.println("a is greater than b"); } else { System.out.println("b is greater than a"); } } }

Determining the largest number This example of Java programming determining the largest number amongst three. Here is the code of program: class largernumber

{ public static void main(String[] args) { int x=500, y=70, z=3000; if (x>y) { if (x>z) { System.out.println("x is greater"); } else { if(z>y) { System.out.println("z is greater"); } else { System.out.println("y is greater"); } } } else { if (y>z) { System.out.println("y is greater"); } } } }

2. List all even numbers between two numbers This example of Java programming listing out all the even numbers between two numbers. For this first create a class named AllEvenNum under the java.io package. Here is the code of the program: import java.io.*; class AllEvenNum { public static void main(String[] args) { try{ BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter number : "); int num = Integer.parseInt(br1.readLine()); System.out.println("Even Numbers:"); for (int i=1;i <=num ; i++)

{ if(i%2==0 ) { System.out.print(i+","); } } } catch(Exception e) { } } }

Calculate area and perimeter of a circle Here is the code of the program: import java.io.*; class CircleArea { public static void main(String[] args) { int r=0; try { BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Radius of Circle : "); r = Integer.parseInt(br1.readLine()); double area = java.lang.Math.PI*r*r; System.out.println("Area of Circle : "+area); double perimeter =2*java.lang.Math.PI*r ; System.out.println("Perimeter of Circle : "+perimeter); } catch(Exception e) { System.out.println("Error : "+e); } } } Calculate factorial of any given number Here is the code of the program: import java.io.*; class Factorial { public static void main(String[] args)

{ try { BufferedReader object = new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the number"); int a= Integer.parseInt(object.readLine()); int fact= 1; System.out.println("Factorial of " +a+ ":"); for (int i= 1; i<=a; i++) { fact=fact*i; } System.out.println(fact); } catch (Exception e){} } } 3. Palindrome Number Example in Java 4. Program for calculating area and perimeter of a rectangle. 5. Program to construct a triangle with the ?*?

Chapter 6
Java Control statements
Java Control statements control the order of execution in a java program, based on data values andconditional logic. There are three main categories of control flow statements; Selection statements: if, if-else and switch. Loop statements: while, do-while and for. Transfer statements: break, continue, return, try-catch-finally and assert. We use control statements when we want to change the default sequential order of execution The If Statement The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statementor a block of code within an if statement. Note that the conditional expression must be a Boolean expression. The simple if statement has the following syntax: if (<conditional expression>) <statement action> Below is an example that demonstrates conditional execution based on if statement condition. public class IfStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } } Output b>a

The If-else Statement The if/else statement is an extension of the if statement. If the statements in the if statement fails, thestatements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression. The if-else statement has the following syntax: if (<conditional expression>) <statement action> else <statement action> Below is an example that demonstrates conditional execution based on if else statement condition. public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); } } } Output b>a Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statementbegins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch. Its general form is as follows:

switch (<non-long integral expression>) { case label1: <statement1> case label2: <statement2> case labeln: <statementn> default: <statement> } // end switch When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the programto continue executing after the current code block. Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.

//An improved version of the season program. class Switch { public static void main(String args[]) { int month = 4; String season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11:

season = "Autumn"; break; default: season = "Bogus Month"; } System.out.println("April is in the " + season + "."); } }

Chapter 7
Loops: The purpose of loop statements is to repeat Java statements more than times. There are several kinds of loop statements in Java. for loop: For loop is used to execute a block of code continuously to accomplish a particular condition. For statement consists of tree parts i.e. initialization, condition, and increment/decrement. initialization: It is an expression that sets the value of the loop control variable. It executes only once. condition: This must be a boolean expression. It tests the loop control variable against a target Value and hence works as a loop terminator. Increment/decrement: It is an expression that increments or decrements the loop control variable. Example: int a; for (a=0; a<=10; a++) { System.out.println("a = " +a); }

while loop: in while loop the statement(s) will be executed as long as Expression evaluates to true. If there is only a single statement inside the braces, you may omit the braces. Example: class counting{ public static void main (String args[]){ int i = 0; while (i < =5){ System.out.println("count"); i = i + 1;

} } }

do-while loop: The do-while statement is like the while statement, except that the associated block always gets executed at least once. Syntax: Do { statement (s) } while (Expression); Example:

public class MyClass { public static void main(String[] args) { int i = 0; do { System.out.println(i); i++; } while (i < 10); } }

Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops:

// Loops may be nested. class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print(" "); System.out.println(); } } }
The output produced by this program is shown here: .......... ......... ........ ....... ...... ..... .... ... .. .

Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a civilized form of goto. The last two uses are explained here.

Using break to Exit a Loop


By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example:

// Using break to exit a loop. class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10

System.out.println("i: " + i); } System.out.println("Loop complete."); } }


This program generates the following output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete

Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loops end. The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. Here is an example program that uses continue to cause two numbers to be printed on each line: // Demonstrate continue. class Continue { public static void main(String args[])] { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0) continue; System.out.println(""); } } }

This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program: 01 23 45 67 89 Here is an example program that uses continue to print a triangular multiplication table for 0 through 9. // Using continue with a label. class ContinueLabel { public static void main(String args[]) { outer: for (int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j > i) { System.out.println(); continue outer; } System.out.print(" " + (i * j)); } } System.out.println(); } }

The continue statement in this example terminates the loop counting j and continues with the next iteration of the loop counting i. Here is the output of this program:
0 01 024 0369 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81

EXERCISE :  Checking whether a year is leap or not ?  Listing out leap years between certain period ?  Preparing table of a number by using loop ?  Finding out the prime number ?  Prime Number in Java ? A Scanner object can parse user input entered on the console or from a le. A Scanner breaks its input into separate tokens (which are typically separated by white space), and then returns them one at a time. The scanner provides methods to convert the tokens into values of different types. For example, this code reads two numbers from the console and prints their sum: Scanner in = new Scanner (System. in); int i = in.nextInt(); int j = in.nextInt(); System.out.println (i+j); The scanner also provides methods to test whether there is any input left, and if there is, what type of token appears next. This functionality is provided through methods like hasNextInt, hasNextDouble. For example, the following code reads integers and adds them up until there is no more input or a nonnumeric token is encountered: Scanner in = new Scanner(System.in); int sum = 0; while (in.hasNextInt()) { sum += in.nextInt(); }

Creating Scanners Whenever using scanners, be sure to include the proper import line: import java.util.Scanner; We will create scanners in two ways: 1. To read from the console, use the following: Scanner input = new Scanner (System. in); 2. To read from a le, use the following: Scanner input = new Scanner (new FileStream("filename.txt"));

Chapter 8

Introducing Classes
The class is at the core of Java. It is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object. As such, the class forms the basis for object-oriented programming in Java. Any concept you wish to implement in a Java program must be encapsulated within a class. Because the class is so fundamental to Java, this and the next few chapters will be devoted to it. Here, you will be introduced to the basic elements of a class and learn how a class can be used to create objects. You will also learn about methods, constructors, and the this keywordIntroduction to Java Classes A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a classs corresponding object are stored in the objects instance variables. Methods define the operations that can be performed in java programming.

The General Form of a Class When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real-world classes contain both. As you will see, a class code defines the interface to its data. Aclass is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. A simplified general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method }

// ... type methodnameN(parameter-list) { // body of method } } A class has the following general syntax: <class modifiers>class<class name> <extends clause> <implements clause> { // Dealing with Classes (Class body) <field declarations (Static and Non-Static)> <method declarations (Static and Non-Static)> <Inner class declarations> <nested interface declarations> <constructor declarations> <Static initializer blocks> } Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume(). public class Cube { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } } How do you reference a data member/function? This is accomplished by stating the name of the object reference, followed by a period (dot), followed by thename of the member inside the object. ( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).

For example: cubeObject.length = 4; cubeObject.breadth = 4; cubeObject.height = 4; cubeObject.getvolume()

Class Variables Static Fields


We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods Static Methods


Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method.

Instance Variables
Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.
Consider this simple Java program showing the use of static fields and static methods

// Class and Object initialization showing the Object Oriented concepts in Java class Cube { int length = 10; int breadth = 10; int height = 10; public static int numOfCubes = 0; // static variable public static int getNoOfCubes() { //static method return numOfCubes; } public Cube() { numOfCubes++; // } }

public class CubeStaticTest { public static void main(String args[]) { System.out.println("Number of Cube objects = " + Cube.numOfCubes); System.out.println("Number of Cube objects = " + Cube.getNoOfCubes()); } }

Output Number of Cube objects = 0 Number of Cube objects = 0 Final Variable, Methods and Classes In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed. Variables defined in an interface are implicitly final. You cant change value of a final variable (is a constant). A final class cant be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method cant be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error. Introduction to Java Objects The Object Class is the super class for all classes in Java. Some of the object class methods are equals toString() wait() notify() notifyAll() hashcode() clone() An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.

An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables. Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance. When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type. Below is an example showing the creation of Cube objects by using the new operator. public class Cube { int length = 10; int breadth = 10; int height = 10; public int getVolume() { return (length * breadth * height); } public static void main(String[] args) { Cube cubeObj; // Creates a Cube Reference cubeObj = new Cube(); // Creates an Object of Cube System.out.println("Volume of Cube is : " + cubeObj.getVolume()); } }

/* A program that uses the Box class. Call this file BoxDemo.java */ class Box

{ double width; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); //object creation of box class double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }

What Are Objects Java is an object-oriented programming language. But what are objects? An object is a self-contained entity which has its own private collection of properties (ie. data) and methods (ie. operations) that encapsulate functionality into a reusable and dynamically loaded structure. After a class definition has been created as a prototype, it can be used as a template for creating new classes that add functionality. Objects are programing units of a particular class. Dynamic loading implies that applications can request new objects of a particular class to be supplied on an 'as needed' basis. Objects provide the extremely useful benefit of reusable code that minimizes development time.

Serialize objects in java


Serialization is the process of converting an object into a sequence of bits, so that it can be persisted on a storage medium such as a file or a memory buffer. This guide shows how to make a java class serializable and how to serialize/deserialize java objects and save/load them into files. Our example class: class Person { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName;

this.lastName = lastName; } } The only change we need is implementing the Serializable interface. This is an empty, tagging interface, no need to implement any additional methods: import java.io.Serializable; class Person implements Serializable { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } } ObjectSerializer is an example class, shows how to perform object serialization in Java. The ObjectSerializer serializes or deserializes a serializable java object and write / read it to a file. import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.ObjectInputStream; class ObjectSerializer { public void serializeObject(String fileName, Object obj) { ObjectOutputStream out = null; try { FileOutputStream fos = new FileOutputStream(fileName); out = new ObjectOutputStream(fos); out.writeObject(obj); out.close(); } catch (IOException ex) { throw new RuntimeException("Serialization failed", ex); } finally { try { if(out != null) out.close(); } catch(Exception e) { // do nothing } } } public Object deSerializeObject(String fileName) { Object obj; ObjectInputStream in = null; try {

FileInputStream fis = new FileInputStream(fileName); in = new ObjectInputStream(fis); obj = in.readObject(); return obj; } catch (Exception e) { throw new RuntimeException("De-serialization failed", e); } finally { try { if(in != null) in.close(); } catch(Exception e) { // do nothing } } } } Using the ObjectSerializer: public class Test { public static void main(String[] args) { // writing to a file Person person = new Person("John", "Doe"); ObjectSerializer serializer = new ObjectSerializer(); serializer.serializeObject("person.dat", person); // reading from a file Person personFromFile = (Person) serializer.deSerializeObject("person.dat"); } }

Chapter 9
CONSTRUCTOR

A java constructor has the same name as the name of the class to which it belongs. Constructors syntax does not include a return type, since constructors never return a value. Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition. Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided. The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object. Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor). public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10; height = 10; } Cube1(int l, int b, int h) { length = l; breadth = b; height = h; } public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1(); cubeObj2 = new Cube1(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); } }

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case. Java Overloaded Constructors Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as theclass, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor. It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor. Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructorscontext public class Cube2 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube2() { this(10, 10); System.out.println("Finished with Default Constructor"); } Cube2(int l, int b) { this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params"); } Cube2(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params");

} public static void main(String[] args) { Cube2 cubeObj1, cubeObj2; cubeObj1 = new Cube2(); cubeObj2 = new Cube2(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume()); } } public class Cube2 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube2() { this(10, 10); System.out.println("Finished with Default Constructor"); } Cube2(int l, int b) { this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params"); } Cube2(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params"); } public static void main(String[] args) { Cube2 cubeObj1, cubeObj2; cubeObj1 = new Cube2(); cubeObj2 = new Cube2(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume()); } }

Output

Finished with Parameterized Constructor having 3 params Finished with Parameterized Constructor having 2 params Finished with Default Constructor Finished with Parameterized Constructor having 3 params Volume of Cube1 is : 1000 Volume of Cube2 is : 6000 In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to beoverloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. If you have never used a language that allows the overloading of methods, then the concept may seem strange at first. But as you will see, method overloading is one of Java's most exciting and useful features. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. Here is a simple example that illustrates method overloading: // Demonstrate method overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo();

double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.2); System.out.println("Result of ob.test(123.2): " + result); } } This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.2 Result of ob.test(123.2): 15178.24 As you can see, test( ) is overloaded four times. The first version takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth takes one doubleparameter. The fact that the fourth version of test( ) also returns a value is of no consequence relative to overloading, since return types do not play a role in overload resolution. When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method's parameters. However, this match need not always be exact. In some cases Java's automatic type conversions can play a role in overload resolution. For example, consider the following program: // Automatic type conversions apply to overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter void test(double a) { System.out.println("Inside test(double) a: " + a); } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); // this will invoke test(double) ob.test(123.2); // this will invoke test(double)

} } This program generates the following output: No parameters a and b: 10 20 Inside test(double) a: 88 Inside test(double) a: 123.2

Method Overriding
If you dont want parent class implementation for any method we can override in the child class based on our child class requirement. This concept is called Overriding. While overriding we have to fallow rules: 1. In the overriding, the method names and args must be same. Ie. In the case of the overriding the signatures of the methods must be same Until 1.4 version, the return types must be same. But from 1.5 version onwards covariant return types are also allowed. Example: class p { public Number getNumber(){} } class c extends P{ public Number getNumber(){} } (or) class C extends P { public Byte/Short/Integer getNumber(){} } For Number class Byte/Short/Integer is co-variant return types or classes. Hence in case of overriding as the return type we can keep child class objects also.

y y

Example: import java.io.*; class P { public object m1(){ return new object; } } class C extends P { public Object m1(){ return new Object; } } class C extends P {

public String m1(){ return durga; } }//in 1.4 CTE saying m1() in C cannot override found:string, req:object: in 1.5 ver no CTE 2. final methods cant be overridden. 3. private methods never participate in the in the overriding because these methods are not visible in the child classes. 4. While overriding decreasing access specifier is not allowed. Violation leads to CTE. class P { public int m1(){} } class C extends P { public int m1(){} } Parent class -------------------------------- Child class public ----------------------------------------------- public protected ---------------------------------------- protected, public default ---------------------------------------- default, protected ,public private ---------------------------------------- private, default, protected, public * While implementing any interface method, we should declare that method as public in the implemented class.(by default implements interface method is public and abstract) * An abstract method can be overridden as abstract. The child of the original child class is responsible for the implementation. class P { public void m1() { } }//non abstract abstract class C extends P { public abstract m1(); }//valid abstract 5. While overriding the size of the CheckedException should not increase. There is no rule for UnCheckedExceptions. Example: Base or parent class : public void m1()throws IOException

Derived or child class : public void m1()throws FileNotfoundException //valid public void m1()throws Exception -->CTE public void m1()throws RunTimeException //valid We can override a synchronized method to non-synchronized and vice versa We can override native to native to non native and vice versa. We can override a non-final method to final method.

y y y

We cant override a static method to non static and a non-static method to static violation leads to CTE .

While overriding method has to execute will be decided by JVM based on the Run Time Object. Hence Overriding is an example of dynamic polymorphism or LateBinding (Dynamic Method dispatch).

If the parents class reference can be used to hold child class object by using that reference we are allowed to call only parent class methods. Child class specific methods are not allowed to call by using parent class reference.

Method Hiding:This is exactly same as overriding except both parent & child class methods must be declared as static. In the method hiding the method resolution take care by compiler only based on the reference type. Ex: class P { static int x=10; int y=20; } class C extends P { static int x=100; int y=200; } class Sample { public static void main(String[] a) {

P p=new C(); System.out.println(p.x+,+p.y); //10,20 C c=new C(); System.out.println(c.x+,+c.y); //100,200 P p1=new P(); System.out.println(p1.x+,+p1.y); //10,20

} } We cant override in the child class. But if define exactly same variable in child class. Variable resolutions take care by compiler only based on the reference type.

y y

Chapter 10 Inheritance
Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements.

Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base class or superclass) with another class (called the derived class or subclass). In Java, inheritance is used for two purposes: 1. Class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class Inheritance. 2. Interface inheritance - create a new class to implement the methods dened as part of an interface for the purpose of subtyping. That is a class that implements an interface conforms to (or is constrained by the type of) the interface. Java supports multiple interface inheritance. In Java, these two kinds of inheritance are made distinct by using different language syntax. For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements. public class derived-class-name extends base-class-name { // derived class methods extend and possibly override // those of the base class } public class class-name implements interface-name { // class provides an implementation for the methods // as specified by the interface

package MyPackage; class Base { private int x; public int f() { ... } protected int g() { ... } } class Derived extends Base { private int y; public int f() { /* new implementation for Base.f() */ } public void h() { y = g(); ... } } In Java, the protected access qualier means that the protected item (eld or method) is visible to a any derived class of the base class containing the protected item. It also means that the protected item is visible to methods of other classes in the same package. This is different from C++. Extends keyword The extends is a Java keyword, which is used in inheritance process of Java. Itspecifies the superclass in a class declaration using extends keyword. It is a keyword that indicates the parent class that a subclass is inheriting from and may not be used as identifiers i.e. you cannot declare a variable or class with this name in your Java program. In Java, every class is a subclass of java.lang.Object. For example, Class X extends class Y to add functionality, either by adding fields or methods to class Y, or by overriding methods of class Y. Take a look at the following example, which demonstrates the use of the 'extends' keyword.

public class A { public int number; } class B extends A { public void increment() { number++; } }

In this example, we inherit from class A, which means that B will also contain a field called number. Two or more classes can also be inherited from the same parent class. extends keyword is also used in an interface declaration to specify one or more superinterfaces. For instance: interface MyInterface { ????. } interface MyInterface extends SuperInterface { ??????. }

SUPER KEYWORD The super is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java programming language likewise thesuper keyword indicates the following : -- The super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used. -- The super keyword as a standalone statement is used to call the constructor of the superclass in the base class. Example to use the super keyword to call the constructor of the superclass in the base class:

public class Class1 { public Class1(String arg) { super(arg); }

-- The syntax super.<method_Name>() is used to give a call to a method of the superclass in the base class. -- This kind of use of the super keyword is only necessary when we need to call a method that is overridden in this base class in order to specify that the method should be called on the superclass. Example to use the super keyword with a method: public class Class1 { public String String_Method() { return super.overriden_String_Method(); }

Order of Construction under Inheritance Note that when you construct an object, the default base class constructor is called implicitly, before the body of the derived class constructor is executed. So, objects are constructed top-down under inheritance. Since every object inherits from the Object class, the Object() constructor is always called implicitly. However, you can call a superclass constructor explicitly using the builtin super keyword, as long as it is the rst statement in a constructor. For example, most Java exception objects inherit from the java.lang.Exception class. If you wrote your own exception class, say SomeException, you might write it as follows:

public class SomeException extends Exception { public SomeException() { super(); // calls Exception(), which ultimately calls Object() } public SomeException(String s) { super(s); // calls Exception(String), to pass argument to base class } public SomeException (int error_code) { this("error); // class constructor above, which calls super(s) System.err.println(error_code); } }

Chapter 11
Abstract Base Classes An abstract class is a class that leaves one or more method implementations unspecied by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class. abstract public class abstract-base-class-name { // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params ); ... // other abstract methods, object methods, class methods } public class derived-class-name extends abstract-base-class-name { public return-type abstract-method-name (formal-params) { stmt-list; } ... // other method implementations } It would be an error to try to instantiate an object of an abstract type: abstract-class-name obj = new abstract-class-name(); // ERROR! That is, operator new is invalid when applied to an abstract class.

Example abstract class usage abstract class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public void move(int dx, int dy)

{ x += dx; y += dy; plot(); } public abstract void plot(); // has no implementation } abstract class ColoredPoint extends Point { private int color; protected public ColoredPoint(int x, int y, int color) { super(x, y); this.color = color; } } class SimpleColoredPoint extends ColoredPoint { public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); } public void plot() { ... } // code to plot a SimpleColoredPoint } Since ColoredPoint does not provide an implementation of the plot method, it must be declared abstract. The SimpleColoredPoint class does implement the inherited plot method. It would be an error to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Point

reference and initialize it with an instance of a subclass object that implements the plot method: Point p = new SimpleColoredPoint(a, b, red); p.plot();

Instance of operator
The instanceof operator has this general form: object instanceof type Here, object is an instance of a class, and type is a class type. If object is of the specified type or can be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result isfalse. Thus, instanceof is the means by which your program can obtain run-time type information about an object. The following program demonstrates instanceof: // Demonstrate instanceof operator. class A { int i, j; }

class B { int i, j; } class C extends A { int k; } class D extends A { int k; } class InstanceOf { public static void main(String args[]) { A a = new A();

B b = new B(); C c = new C(); D d = new D(); if(a instanceof A) System.out.println("a is instance of A"); if(b instanceof B) System.out.println("b is instance of B"); if(c instanceof C) System.out.println("c is instance of C"); if(c instanceof A) System.out.println("c can be cast to A"); if(a instanceof C) System.out.println("a can be cast to C"); System.out.println(); // compare types of derived types A ob; ob = d; // A reference to d System.out.println("ob now refers to d"); if(ob instanceof D) System.out.println("ob is instance of D"); System.out.println(); ob = c; // A reference to c System.out.println("ob now refers to c"); if(ob instanceof D) System.out.println("ob can be cast to D"); else System.out.println("ob cannot be cast to D"); if(ob instanceof A) System.out.println("ob can be cast to A"); - 230 System.out.println(); // all objects can be cast to Object if(a instanceof Object) System.out.println("a may be cast to Object"); if(b instanceof Object) System.out.println("b may be cast to Object");

if(c instanceof Object) System.out.println("c may be cast to Object"); if(d instanceof Object) System.out.println("d may be cast to Object"); } } The output from this program is shown here: a is instance of A b is instance of B c is instance of C c can be cast to A ob now refers to d ob is instance of D ob now refers to c ob cannot be cast to D ob can be cast to A a may be cast to Object b may be cast to Object c may be cast to Object d may be cast to Object The instanceof operator isn't needed by most programs, because, generally, you know the type of object with which you are working. However, it can be very useful when you're writing generalized routines that operate on objects of a complex class hierarchy.

Using final to Prevent Overriding


While method overriding is one of Javas most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final: class A { final void meth() { System.out.println("This is a final method."); } } class B extends A {

void meth() { // ERROR! Can't override. System.out.println("Illegal!"); } } Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time error will result.

Using final to Prevent Inheritance


Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. Here is an example of a final class: final class A { // ... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A // ... } As the comments imply, it is illegal for B to inherit A since A is declared as final.

package Chapter - 12
A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces. Packages are nothing more than the way we organize files into different directories according to their functionality, usability as well as category they should belong to. An obvious example of packaging is the JDK package from SUN (java.xxx.yyy) as shown below: Basically, files in one directory (or package) would have different functionality from those of another directory. For example, files in java.io package do something related to I/O, but files in java.net package give us the way to deal with the Network. In GUI applications, it's quite common for us to see a directory with a name "ui" (user interface), meaning that this directory keeps files related to the presentation part of the application. On the other hand, we would see a directory called "engine", which stores all files related to the core functionality of the application instead. Packaging also help us to avoid class name collision when we use the same class name as that of others. For example, if we have a class name called "Vector", its name would crash with the Vector class from JDK. However, this never happens because JDK use java.util as a package name for the Vector class (java.util.Vector). So our Vector class can be named as "Vector" or we can put it into another package like com.mycompany.Vector without fighting with anyone. The benefits of using package reflect the ease of maintenance, organization, and increase collaboration among developers. Understanding the concept of package will also help us manage and use files stored in jar files in more efficient ways.

Suppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing we have to do is to specify the keywordpackage with the name of the package we want to use (world in our case) on top of our source file, before the code that defines the real classes in the package, as shown in our HelloWorld class below: // only comment can be here package world; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } One thing you must do after creating a package for the class is to create nested subdirectories to represent package hierachy of the class. In our case, we have the world package, which requires only one directory. So, we create a directory world and put our HelloWorld.java into it.

Setting up the CLASSPATH From figure 2 we put the package world under C:. So we just set our CLASSPATH as: set CLASSPATH=.;C:\; We set the CLASSPATH to point to 2 places, . (dot) and C:\ directory. Note: If you used to play around with DOS or UNIX, you may be familiar with . (dot) and .. (dot dot). We use . as an alias for the current directory and .. for the parent directory. In our CLASSPATH we include this . for convenient reason. Java will find our class file not only from C: directory but from the current directory as well. Also, we use ; (semicolon) to separate the directory location in case we keep class files in many places. When compiling HelloWorld class, we just go to the world directory and type the command: C:\world\javac HelloWorld.java If you try to run this HelloWorld using java HelloWorld, you will get the following error: C:\world>java HelloWorld Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: world/HelloWorld) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:442) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:101) at java.net.URLClassLoader.defineClass(URLClassLoader.java:248) at java.net.URLClassLoader.access$1(URLClassLoader.java:216) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:191) at java.lang.ClassLoader.loadClass(ClassLoader.java:290) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) The reason is right now the HelloWorld class belongs to the package world. If we want to run it, we have to tell JVM about its fully-qualified class name(world.HelloWorld) instead of its plain class name (HelloWorld). C:\world>java world.HelloWorld C:\world>Hello World Note: fully-qualified class name is the name of the java class that includes its package name We just changed the location of the package from C:\world\HelloWorld.java to C:\myclasses\world\HelloWorld.java. Our CLASSPATH then needs to be changed to point to the new location of the package world accordingly. set CLASSPATH=.;C:\myclasses; Thus, Java will look for java classes from the current directory and C:\myclasses directory instead. Someone may ask "Do we have to run the HelloWorld at the directory that we store its class file everytime?". The answer is NO. We can run theHelloWorld from anywhere as long as we still include the package world in the CLASSPATH. For example, C:\>set CLASSPATH=.;C:\;

C:\>set CLASSPATH // see what we have in CLSSPATH CLASSPATH=.;C:\; C:\>cd world C:\world>java world.HelloWorld Hello World C:\world>cd .. C:\>java world.HelloWorld Hello World

How to use package


There are 2 ways in order to use the public classes stored in package. 1. Declare the fully-qualified class name. For example, ... world.HelloWorld helloWorld = new world.HelloWorld(); world.moon.HelloMoon helloMoon = new world.moon.HelloMoon(); String holeName = helloMoon.getHoleName(); ... 2) Use an "import" keyword: import world.*; // we can call any public classes inside the world package import world.moon.*; // we can call any public classes inside the world.moon package import java.util.*; // import all public classes from java.util package import java.util.Hashtable; // import only Hashtable class (not all classes in java.util package)

Thus, the code that we use to call the HelloWorld and HelloMoon class should be
... HelloWorld helloWorld = new HelloWorld(); // don't have to explicitly specify world.HelloWorld anymore HelloMoon helloMoon = new HelloMoon(); // don't have to explicitly specify world.moon.HelloMoon anymore ... Note that we can call public classes stored in the package level we do the import only. We can't use any classes that belong to the subpackage of the package we import. For example, if we import package world, we can use only the HelloWorld class, but not the HelloMoon class. A Short Package Example Keeping the preceding discussion in mind, you can try this simple package: // A simple package

package MyPack; class Balance { String name; double bal; Balance(String n, double b) {

name = n; bal = b; } void show() { if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal); } } class AccountBalance { public static void main(String args[]) {
Balance current[] = new Balance[3];

current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++) current[i].show(); } }
Call this file AccountBalance.java and put it in a directory called MyPack. Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory. Then, try executing the AccountBalance class, using the following command line: java MyPack.AccountBalance Remember, you will need to be in the directory above MyPack when you execute this command. (Alternatively, you can use one of the other two options described in the preceding section to specify the path MyPack.) As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line: java AccountBalance AccountBalance must be qualified with its package name.

Class 13 Exeception handling


Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution. During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block. Error that occurs during the program execution generate a specific object which has the information about the errors occurred in the program. In the following example code you will see that how the exception handling can be done in java program. This example reads two integer numbers for the variables a and b. If you enter any other character except number ( 0 - 9 ) then the error is caught by NumberFormatException object. After thatex.getMessage() prints the information about the error occurring causes. Code of the program : import java.io.*; public class exceptionHandle { public static void main(String[] args) throws Exception { try { int a,b; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); a = Integer.parSystem.out.println(ex.getMessage() + " is not a numeric value."); System.exit(0); } } }

Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.
// File Name : ExcepTest.java

import java.io.*; public class ExcepTest { public static void main(String args[]) { Try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }
This would produce following result:

Exception thrown Out of the block

:java.lang.ArrayIndexOutOfBoundsException: 3

Multiple catch Blocks:


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException:

import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
Amethod can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:

import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition }

The finally Keyword


The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax:

try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. }

Example:
public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } }
This would produce following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed

Declaring you own Exception:


You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes: y y y All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:


class MyException extends Exception{ }

You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example:
// File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount;

public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } }
To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } }
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

// File Name BankDemo.java public class BankDemo { public static void main(String [] args)

CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } } }
Compile all the above three files and run BankDemo, this would produce following result:

Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13)

Chapter 14
Interface In English, an interface is a device or system that unrelated entities use to interact. According to this definition, a remote control is an interface between you and a television set, the English language is an interface between two people, and the protocol of behavior enforced in the military is the interface between people of different ranks. Similarly, a Java interface is a device that unrelated objects use to interact with one another. Java interfaces are probably most analogous to protocols (an agreed-upon behavior). In fact, other object-oriented languages have the functionality of Java's interfaces, but they call their interfaces protocols. A Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface, thereby agreeing to certain behavior. Definition: An interface is a named collection of method definitions (without implementations). An interface can also include constant declarations

REMEMBER

When you implement an interface method, it must be declared as public

Using the keyword interface, you can fully abstract a class interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. In practice, this means that you can define interfaces that dont make assumptions about how they are implemented. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. To implement an interface, a class must create the complete set of methods defined by the interface. However, each class is free to determine the details of its own implementation. By providing the interface keyword, Java allows you to fully utilize the one interface, multiple methods aspect of polymorphism.

Java interface example : In this example i implemented Java shape interface in the circle class .as you will see in the following example ,up-casting for the object "circleshape" . Note : In interface : o functions are public and abstract o fields are public and final . Code:

public class Main { public static void main(String[] args) { shape circleshape=new circle(); circleshape.Draw(); } }

interface shape { public String baseclass="shape";

public void Draw();

} class circle implements shape {

public void Draw() { System.out.println("Drawing Circle here"); }

class A implements IntfA,IntfB { public int a; A() {this(10); }

A(int x) {a=x;

public String MethodofIntfA() { String s="Method-A"; // System.out.println(s); return s; } public void methodofA() { System.out.println(" Method Of A " +a); } public String MethodofIntfB() { String s2="Method-B"; return s2; }

public static void main(String args[]) { A a1=new A();

String s1=new String(); String s2=new String(); s1=a1.MethodofIntfA(); s2=a1.MethodofIntfB(); a1.methodofA(); System.out.println(""); System.out.println("Method -IntfA"+s1); System.out.println(""); System.out.println("Method -IntfB"+s2);

} }

interface IntfA extends IntfB { //constant can be declare;;;;;;;;;;;;;;;;;;;; how use it's public String MethodofIntfA();

//public String MethodofIntfA1(); }

interface IntfB {//constant can be declare;;;;;;;;;;;;;;;;;;;; how use it's public String MethodofIntfB(); //public String MethodofIntfA1(); }

/*****************/ You will have to implement IntfB interface in the Class A and i will give you some changes. i hope your query is solved. /*************************/ output /**************************/

Method Of A 10 Method -IntfAMethod-A Method -IntfBMethod-B

/**************************/

Multithreading
Multitasking and MultiThreading

chapter 15

In multi-tasking operating system tasks are known as heavy-weight process; in a multithreaded environment tasks are light weight process, or threads. The difference is that heavy weight process are in separate address space and should be thought of as different program running on the same system like Word Excel. Inter-process communication is expensive and limited .Context switching, changing the running process , is also heavy-weight. We usually only think about using one of these programs at a time, even they are both running. Threads on the other hand share the same address space and cooperatively share the same heavy weight process. Inter-thread communication is very light-weight and pervasive. Context switching is fast and an integral part of running any one program. Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

Creating Threads:
We can create thread in a program using class Thread or implementing interface Runnable.

Lifecycle of a Thread

1. New state After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 2. Runnable (Ready-to-run) state A thread start its life from 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, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.

3. Running state 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: the scheduler select a thread from runnable pool.

4. Dead state A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. 5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread

A simple program to explain the life cycle of thread


class ThreadDemo implements Runnable{ Thread t; ThreadDemo(String s) { t=new Thread(this,s); t.start();//Ready to run } public void run() {//Running state for(int i=0;i<5;i++) { System.out.println("Thread Name :"+Thread.currentThread().getName()); try{ Thread.sleep(1000);//Blocked }catch(Exception e){} } }//Dead state } public class RunnableThreadDemo1{ public static void main(String args[]){ System.out.println("Thread Name :"+Thread.currentThread().getName()); ThreadDemo m1=new ThreadDemo("My Thread 1");//New atate ThreadDemo m2=new ThreadDemo("My Thread 2"); } }

Synchronization
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors. E.g. synchronizing a function: public synchronized void Method1 () { // method code. } E.g. synchronizing a block of code inside a function: public Method2 (){

synchronized (this) { // synchronized code here. }

} Synchronization
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors. E.g. synchronizing a function: public synchronized void Method1 () { // method code. } E.g. synchronizing a block of code inside a function: public Method2 (){ synchronized (this) { // synchronized code here. }

} Messaging
Once our program is divided into several logical threaded parts, we have to define how these threads will communicate with each other. Java provide a clean way for two threads to talk to each other via thewait() and notify() and notifyall() methods.

Thread Priorities
Thread priorities are defined as integers between 1 and 10. Ten is the highest priority. One is the lowest. The normal priority is five. Higher priority threads get more CPU time. We can set a thread's priority with the setPriority(int priority) method.

In Java, thread scheduler can use the threadpriorities in the form of integer value to each of its thread to determine the execution schedule of threads . Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state. Priorities are integer values from 1 (lowest priority given by the constant Thread.MIN_PRIORITY) to 10 (highest priority given by the constant Thread.MAX_PRIORITY). The default priority is 5(Thread.NORM_PRIORITY).

Constant

Description The maximum priority of any Thread.MIN_PRIORITY thread (an int value of 10) Thread.MAX_PRIORITY The minimum priority of any

thread (an int value of 1) The normal priority of any Thread.NORM_PRIORITY thread (an int value of 5)
The methods that are used to set the priority of thread shown as:

Method

Description This is method is used to set the setPriority() priority of thread. This method is used to get the getPriority() priority of thread.
When a Java thread is created, it inherits its priority from the thread that created it. At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution. In Java runtime system, preemptive scheduling algorithm is applied. If at the execution time a thread with a higher priority and all other threads are runnable then the runtime system chooses the newhigher priority thread for execution. On the other hand, 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. Thread Scheduler In the implementation of threading scheduler usually applies one of the two following strategies: y Preemptive scheduling ? 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.

Time-Sliced (Round-Robin) Scheduling ? A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.

You can also set a thread's priority at any time after its creation using the setPriority method. Lets see, how to set and get the priority of a thread. class MyThread1 extends Thread{ MyThread1(String s){ super(s); start();

} public void run(){ for(int i=0;i<3;i++){ Thread cur=Thread.currentThread(); cur.setPriority(Thread.MIN_PRIORITY); int p=cur.getPriority(); System.out.println("Thread Name :"+Thread.currentThread().getName()); System.out.println("Thread Priority :"+cur); } } } class MyThread2 extends Thread{ MyThread2(String s){ super(s); start(); }

public void run(){ for(int i=0;i<3;i++){ Thread cur=Thread.currentThread(); cur.setPriority(Thread.MAX_PRIORITY); int p=cur.getPriority(); System.out.println("Thread Name :"+Thread.currentThread().getName()); System.out.println("Thread Priority :"+cur); } } } public class ThreadPriority{ public static void main(String args[]){ MyThread1 m1=new MyThread1("My Thread 1"); MyThread2 m2=new MyThread2("My Thread 2"); } }

A situation where a thread is waiting for an object lock that holds by second thread, and this second thread is waiting for an object lock that holds by first thread, this situation is known as Deadlock.

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. But Thread1need to printer that is hold up by the Thread2, likewise Thread2 need the keyboard that is hold up by the Thread1. 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); } } } } }

Chapter - 16
File I/O What is Java I/O? Introduction The Java Input/Output (I/O) is a part ofjava.io package. The java.io package contains a relatively large number ofclasses that support input and output operations. The classes in the package are primarily abstract classes and stream-oriented that define methods and subclasses which allow bytes to be read from and written to files or other input and output sources. The InputStream andOutputStream are central classes in the package which are used for reading from and writing to byte streams, respectively. The java.io package can be categories along with its stream classes in a hierarchy structure shown below:

InputStream:

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

InputStream is inherited from the Object class. Each class of the InputStreams provided by the java.io package is intended for a different purpose.

OutputStream: The OutputStream class is a sibling to InputStream that is used for writing byte and array of bytes to an output source. Similar to input sources, an output source can be anything such as a file, a string, or memory containing the data. Like an input stream, an output stream is automatically opened when you create it. You can explicitly close an output stream with the close( ) method, or let it be closed implicitly when the object is garbage collected. The classes inherited from the OutputStream class can be seen in a hierarchy structure shown below:

OutputStream is also inherited from the Object class. Each class of the OutputStreams provided by the java.io package is intended for a different purpose. How Files and Streams Work: Java uses streams to handle I/O operations through which the data is flowed from one location to another. For example, an InputStream can flow the data from a disk file to the internal memory and anOutputStream can flow the data from the internal memory to a disk file. The disk-file may be a text file or a binary file. When we work with a text file, we use a character stream where one character is treated as per byte on disk. When we work with a binary file, we use a binary stream. The working process of the I/O streams can be shown in the given diagram.

1. Classes and Interfaces of the I/O Streams The following listing of classes provided by the java.io package shown in the given table.

Reading Text from the Standard Input Standard Streams:

Standard Streams are a feature provided by many operating systems. By default, they read input from the keyboard and write output to the display. They also support I/O operations on files. Java also supports three Standard Streams: y y y

Standard Input: Accessed through System.in which is used to read input from the keyboard. Standard Output: Accessed through System.out which is used to write output to be display. Standard Error: Accessed through System.err which is used to write error output to be display.

These objects are defined automatically and do not need to be opened explicitly. Standard Output andStandard Error, both are to write output; having error output separately so that the user may read error messages efficiently. System.in is a byte stream that has no character stream features. To use Standard Input as a character stream, wrap System.in within the InputStreamReader as an argument. InputStreamReader inp = new InputStreamReader(system.in); 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. The Reader class is used for this purpose that is available in the java.io package. It acts as an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). the Reader class is further categorized into the subclasses. The following diagram shows a class-hierarchy of the java.io.Reader class.

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

Method read( ) read(char[] cbuf, int off, int len) readLine( )

Return Type int int String

Description Reads a single character Read characters into a portion of an array. Read a line of text. A line is considered to be terminated by

close( )

void

('\n'). Closes the opened stream.

This program illustrates you how to use standard input stream to read the user input.. import java.io.*;

public class ReadStandardIO{ public static void main(String[] args) throws IOException{ InputStreamReader inp = new InputStreamReader(System.in) BufferedReader br = new BufferedReader(inp); System.out.println("Enter text : "); String str = in.readLine(); System.out.println("You entered String : "); System.out.println(str); } }

2. keyboard on command line. This program illustrates how to use standard input to read the user input. Working With the Files The File class deals with the machine dependent files in a machine-independent manner i.e. it is easier to write platform-independent code that examines and manipulates files using the Fileclass. The constructors of the File class are shown in the table:

Description Create File object for default File(path) directory (usually where program is located). Create File object for directory path File(dirpath,fname) given as string. Create File object for directory. File(dir, fname)
3. Thus the statement can be written as: 4. File f = new File("<filename>");

Constructor

5. The methods that are used with the file object to get the attribute of a corresponding file shown in the table.

Description Returns true if file exists. f.exists() Returns true if this is a normal file. f.isFile() true if "f" is a directory. f.isDirectory() Returns name of the file or directory. f.getName() Returns true if file is hidden. f.isHidden() f.lastModified() Returns time of last modification. Returns number of bytes in file. f.length() path name. f.getPath() Deletes the file. f.delete() Renames f to File f2. Returns true if f.renameTo(f2) successful. Creates a file and may throw f.createNewFile() IOException. Method
o Create a File import java.io.*;

public class CreateFile1{ public static void main(String[] args) throws IOException { File f; f=new File("myfile.txt"); if(!f.exists()){ f.createNewFile(); System.out.println("New file \"myfile.txt\" has been creat d to the current directory"); } } }

Read the File import java.io.*; class FileRead { public static void main(String args[]) { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("textfile.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in )); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println (strLine); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }

Write to a File

For writing data to a file, the classFileWriter and BufferedWriter are used. FileWriter : FileWriter is a subclass ofOutputStreamWriter class that is used to write text (as opposed to binary data) to a file. You create a FileWriter by specifying the file to be written to, or optionally, when the

data should be appended to the end of an existing file instead of overwriting that file. The FileWriter class creates an internal FileOutputStream to write bytes to the specified file BufferedWriter : The BufferedWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays and strings. The constructor of the FileWriter class takes the file name which has to be buffered by theBufferedWriter stream. The write( ) method of BufferedWriter class is used to create the file into specified directory. Following code write data into new file: out.write(read_the_Buffered_file_name); Following code creates the object of FileWriter and BufferedWriter:

FileWriter fstream = new FileWriter(file_name); BufferedWriter out = new BufferedWriter(fstream);


Lets see an another example that writes the text input by the user using the FileWriter and theBufferedWriter class. import java.io.*; public class FileWriter{ public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter the file name to create : "); String file_name = in.readLine(); File file = new File(file_name); boolean exist = file.createNewFile(); if (!exist) { System.out.println("File already exists."); System.exit(0); } else { FileWriter fstream = new FileWriter(file_name); BufferedWriter out = new BufferedWriter(fstream); out.write(in.readLine()); out.close(); System.out.println("File created successfully."); }

} }

Appending to a File

Here is the code of java program to write text to a file: import java.io.*; class FileWrite { public static void main(String args[]) { try{ // Create file FileWriter fstream = new FileWriter("out.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write("Hello Java"); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }

Chapter 17
AWT and Applet 1. Graphical User Interfaces A class library is provided by the Java programming language which is known as Abstract Window Toolkit (AWT). What is AWT in java ava.awt.*; package available with JDK. AWT stands for Abstract Windowing Toolkit. It contains all classes to write the program that interface between the user and different windowing toolkits. You can use the AWT package to develop user interface objects like buttons, checkboxes, radio buttons and menus etc. This package provides following interfaces and classes as follows:

Interfaces and Descriptions of AWT Package:


This interface is used for handling events. This interface takes numeric value to Adjustable adjust within the bounded range. This interface defines methods to draw Composite a graphical area. It combines a shape, text, or image etc. This interface allows the existence of CompositeContext several context simultaneously for a single composite object. It handles the state of the operations. This interface is used for maintaining ItemSelectable zero or more selection for items from the item list. KeyEventDispatcher The KeyEventDispatcher implements the current KeyboardFocusManagerand it receives KeyEvents before despatching their targets. KeyEventPostProcessor This interface also implements the current KeyboardFocusManager. The KeyboardFocusManager receives the KeyEvents after that dispatching their targets. It defines the interface class and it has LayoutManager layout containers. This is the interface extends from the LayoutManager2 LayoutManager and is subinterface of that. This interface has all menu containers. MenuContainer This interface is used to color pattern. Paint It used for the Graphics2D operations.

ActionEvent

PaintContext

PaintGraphics Shape Stroke

Transparency

This interface also used the color pattern. It provides an important color for the Graphics2D operation and uses the ColorModel. This interface provides print a graphics context for a page. This interface used for represent the geometric shapes. This interface allows the Graphics2Dobject and contains the shapes to outline or stylistic representation of outline. This interface defines the transparency mode for implementing classes.

Describe the AWT Components Following some components of Java AWT are explained : 1. Labels : This is the simplest component of Java Abstract Window Toolkit. This component is generally used to show the text or string in your application and label never perform any type of action. Syntax for defining the label only and with justification :

Label label_name = new Label ("This is the label text."); Above code simply represents the text for the label. Label label_name = new Label ("This is the label text.", Label.CENTER); Justification of label can be left, right or centered. Above declaration used the center justification of the label using the Label.CENTER.

2. Buttons : This is the component of Java Abstract Window Toolkit and is used to trigger actions and other events required for your application. The syntax of defining the button is as follows :

Button button_name = new Button ("This is the label of the button."); You can change the Button's label or get the label's text by using the Button.setLabel(String)and Button.getLabel() method. Buttons are added to the it's container using the add (button_name) method.

3. Check Boxes : This component of Java AWT allows you to create check boxes in your applications. The syntax of the definition of Checkbox is as follows :

CheckBox checkbox_name = new Checkbox ("Optional check box 1", false); Above code constructs the unchecked Checkbox by passing the boolean valued

argument falsewith the Checkbox label through the Checkbox() constructor. Defined Checkbox is added to it's container using add (checkbox_name) method. You can change and get the checkbox's label using the setLabel (String) and getLabel() method. You can also set and get the state of the checkbox using the setState(boolean) and getState() method provided by the Checkbox class.

4. Radio Button : This is the special case of the Checkbox component of Java AWT package. This is used as a group of checkboxes which group name is same. Only one Checkbox from a Checkbox Group can be selected at a time. Syntax for creating radio buttons is as follows :

CheckboxGroup chkgp = new CheckboxGroup(); add (new Checkbox ("One", chkgp, false); add (new Checkbox ("Two", chkgp, false); add (new Checkbox ("Three",chkgp, false); In the above code we are making three check boxes with the label "One", "Two" and "Three". 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.

5. Text Area: This is the text container component of Java AWT package. The Text Area contains plain text. TextArea can be declared as follows:

TextArea txtArea_name = new TextArea(); You can make the Text Area editable or not using the setEditable (boolean) method. If you pass the boolean valued argument false then the text area will be non-editable otherwise it will be editable. The text area is by default in editable mode. Text are set in the text area using thesetText(string) method of the TextArea class. 6. Text Field: This is also the text container component of Java AWT package. This component contains single line and limited text information. This is declared as follows :

TextField txtfield = new TextField(20); You can fix the number of columns in the text field by specifying the number in the constructor. In the above code we have fixed the number of columns to 20.

Applet:
A Java applet is an applet delivered to users in the form of Java bytecode. Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand-alone tool for testing applets. Java applets were introduced in the first version of the Java language in 1995, and are written in programming languages that compile to Java bytecode, usually in Java, but also in other languages such as Jython,
[8]

JRuby,[9] or Eiffel (via SmartEiffel).[10]


[11]

Java applets run at speeds comparable to, but generally slower than, other compiled languages such as C++, but many times faster than JavaScript. In addition they can use 3D hardware

acceleration that is available from Java. This makes applets well suited for non trivial, computation
intensive visualizations. Since Java's bytecode is cross-platform or platform independent, Java applets can be executed by browsers for many platforms, including Microsoft Windows, Unix, Mac OS and Linux. It is also trivial to run a Java applet as an application with very little extra code. This has the advantage of running a Java applet in offline mode without the need for any Internet browser software and also directly from the integrated development environment (IDE).

Example The following example is made simple enough to illustrate the essential use of Java applets through its java.applet package. It also uses classes from the Java Abstract Window Toolkit(AWT) for producing actual output (in this case, the "Hello, world!" message). import java.applet.Applet; import java.awt.*; // Applet code for the "Hello, world!" example. // This should be saved in a file named as "HelloWorld.java". public class HelloWorld extends Applet { // This method is mandatory, but can be empty (i.e., have no actual code). public void init() { } // This method is mandatory, but can be empty.(i.e.,have no actual code). public void stop() { } // Print a message on the screen (x=20, y=10). public void paint(Graphics g) { g.drawString("Hello, world!", 20,10);

// Draws a circle on the screen (x=40, y=30). g.drawArc(40,30,20,20,0,360); } } Additional simple applets are available at Wikiversity.[25] For compiling, this code is saved on a plain-ASCII file with the same name as the class and .java extension, i.e. HelloWorld.java. The resulting HelloWorld.class applet should be placed on the web server and is invoked within an HTML page by using an <APPLET> or an<OBJECT> tag. For example: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>HelloWorld_example.html</TITLE> </HEAD> <BODY> <H1>A Java applet example</H1> <P>Here it is: <APPLET code="HelloWorld.class" WIDTH="200" HEIGHT="40"> This is where HelloWorld.class runs.</APPLET></P> </BODY> </HTML> Displaying the HelloWorld_example.html page from a Web server, the result should look as this: A Java applet example Here it is: Hello, world! To minimize download time, applets are usually delivered in a form of compressed zip archive (having jar extension). If all needed classes (only one in our case) are placed in compressed archive example.jar, the embedding code would look different: <P>Here it is: <APPLET code="HelloWorld" WIDTH="200" HEIGHT="40" ARCHIVE="example.jar"> This is where HelloWorld.class runs.</APPLET></P> Applet inclusion is described in detail in Sun's official page about the APPLET tag.[26] [edit]Advantages A Java applet can have any or all of the following advantages:[27]  It is simple to make it work on Linux, Microsoft Windows and Mac OS X i.e. to make it cross platform. Applets are supported by mostweb browsers.

The same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the Java Runtime Environment (JRE) the client will be forced to wait during the large download.

Most web browsers cache applets, so will be quick to load when returning to a web page. Applets also improve with use: after a first applet is run, the JVM is already running and starts quickly (the JVM will need to restart each time the browser starts afresh).

It can move the work from the server to the client, making a web solution more scalable with the number of users/clients.

If a standalone program (like Google Earth) talks to a web server, that server normally needs to support all prior versions for users which have not kept their client software updated. In contrast, a properly configured browser loads (and caches) the latest applet version, so there is no need to support legacy versions.

 

The applet naturally supports the changing user state, such as figure positions on the chessboard. Developers can develop and debug an applet direct simply by creating a main routine (either in the applet's class or in a separate class) and calling init() and start() on the applet, thus allowing for development in their favorite Java SE development environment. All one has to do after that is re-test the applet in the AppletViewer program or a web browser to ensure it conforms to security restrictions.

An untrusted applet has no access to the local machine and can only access the server it came from. This makes such an applet much safer to run than a standalone executable that it could replace. However, a signed applet can have full access to the machine it is running on if the user agrees.

Java applets are fast - and can even have similar performance to native installed software.

[edit]Disadvantages A Java applet may have any of the following disadvantages:   It requires the Java plug-in. Some organizations only allow software installed by the administrators. As a result, some users can only view applets that are important enough to justify contacting the administrator to request installation of the Java plug-in.

As with any client-side scripting, security restrictions may make it difficult or even impossible for an untrusted applet to achieve the desired goals. Some applets require a specific JRE. This is discouraged.[28] If an applet requires a newer JRE than available on the system, or a specific JRE, the user running it the first time will need to wait for the large JRE download to complete.

 

Java automatic installation or update may fail if a proxy server is used to access the web. This makes applets with specific requirements impossible to run unless Java is manually updated. The Java automatic updater that is part of a Java installation also may be complex to configure if it must work through a proxy.

Unlike the older applet tag, the object tag needs workarounds to write a cross-browser HTML document.

AWT Components The class component is extended by all the AWT components. More of the codes can be put to this class to design lot of AWT components. Following are the AWT components: i. Canvas

import java.awt.*; import java.applet.*; public class MyCanvas extends Applet { public MyCanvas() { setSize(80, 40); } public void paint(Graphics g) { g.drawRect(0, 0, 90, 50); g.drawString("A Canvas", 15,15); } } 2. Here is the Output:

C:\newprgrm>javac MyCanvas.java C:\newprgrm>appletviewer MyCanvas.html


3.

4.

i.

Checkbox import java.awt.*; import java.applet.Applet; public class MyCheckbox extends Applet { public void init() { Checkbox c = new Checkbox("Choose this option"); add(c); } }

ii.

Label import java.awt.*; import java.applet.Applet; public class MyLabel extends Applet { public void init() { add(new Label("label one")); add(new Label("label two", Label.RIGHT)); } }

iii.

Scrollbar import java.awt.*; import java.applet.Applet; public class ScrollbarDemo extends Applet { public void init() { Scrollbar sb = new Scrollbar (Scrollbar.VERTICAL, 0, 8, -100, 100); add(sb); } }

iv.

TextField

import java.awt.*; import java.applet.Applet; public class TextFieldDemo extends Applet{ public void init(){ TextField tf = new TextField("Type in the box "); add(tf); } }

chapter - 18 Swing
Swing is important to develop Java programs with a graphical user interface (GUI). There are many components which are used for the building of GUI in Swing. The Swing Toolkit consists of many components for the building of GUI. These components are also helpful in providing interactivity to Java applications. Following are components which are included in Swing toolkit: y y y y y list controls buttons labels tree controls table controls

All AWT flexible components can be handled by the Java Swing. Swing toolkit contains far more components than the simple component toolkit. It is unique to any other toolkit in the way that itsupports integrated internationalization, a highly customizable text package, rich undo supportetc. Not only this you can also create your own look and feel using Swing other than the ones that are supported by it. The customized look and feel can be created using Synth which is specially designed. Not to forget that Swing also contains the basic user interface such as customizable painting, event handling, drag and drop etc. The Java Foundation Classes (JFC) which supports many more features important to a GUI programcomprises of Swing as well. The features which are supported by Java Foundation Classes (JFC) arethe ability to create a program that can work in different languages, the ability to add rich graphics functionality etc. The features which are provided by Swing and the Java Foundation Classes are as follows:

Swing GUI Components There are several components contained in Swing toolkit such as check boxes, buttons, tables, text etc. Some very simple components also provide sophisticated functionality. For instance, text fieldsprovide formatted text input or password field behavior. Furthermore, the file browsers and dialogs can be used according to one's need and can even be customized.

Java Swing Labels JLabel is a display area for a short text string or an image, or both. A label does not react to input events. As a result, it cannot get the keyboard focus. A label can, however, display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can't display it. A JLabel object can display either text, an image, or both. You can specify where in the label's display area the label's contents are aligned by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default. You can also specify the position of the text relative to the image. By default, text is on the trailing edge of the image, with the text and image vertically aligned. A label's leading and trailing edge are determined from the value of its ComponentOrientation property. At present, the default ComponentOrientation setting maps the leading edge to left and the trailing edge to right. Finally, you can use the setIconTextGap method to specify how many pixels should appear between the text and the image. The default is 4 pixels. The Java Swing example below demonstrates use of Jlabel. It creates a window which shows different alignments of JLabel. Seven different labels are created and are added to container. Label1 is a simple label. Label 2, 3, 4, 5, 6 has different alignments such as LEFT, CENTER, RIGHT etc. For Label7 Text added with setText(). Code:

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JLabelDemo extends JApplet { /* Declaration */ private Container Panel; private LayoutManager Layout; private private private private private private private JLabel JLabel JLabel JLabel JLabel JLabel JLabel Label1; Label2; Label3; Label4; Label5; Label6; Label7;

public JLabelDemo() { /* Instantiation */ Layout = new GridLayout(7, 1); Label1 = new JLabel("A Simple Label"); Label2 = new JLabel("A Label with LEFT alignment", JLabel.LEFT); Label3 = new JLabel("A Label with CENTER alignment", JLabel.CENTER);

Label4 = new JLabel("A Label with RIGHT alignment", JLabel.RIGHT); Label5 = new JLabel("A Label with LEADING alignment", JLabel.LEADING); Label6 = new JLabel("A Label with TRAILING alignment", JLabel.TRAILING); Label7 = new JLabel(); Panel = getContentPane();

/* Location */
Panel.setLayout(Layout); Panel.add(Label1); Panel.add(Label2); Panel.add(Label3); Panel.add(Label4); Panel.add(Label5); Panel.add(Label6); Panel.add(Label7); /* Decoration */ Panel.setBackground(Color.yellow); Label7.setHorizontalAlignment(JLabel.CENTER); Label7.setForeground(Color.blue); Label7.setText("Text added with setText"); } }

Java Swing Buttons JButtons are just as you'd think, buttons on the screen that a user can press to change properties of your program. A JButton can be instantiated and used in a GUI just like a java.awt.Button. Buttons can be configured, and to some degree controlled, by Actions. Using an Action with a button has many benefits beyond directly configuring a button. A Swing button can display both text and an image. The underlined letter in each button's text shows the mnemonic the keyboard alternative for each button. When a button is disabled, the look and feel automatically generates the button's disabled appearance. However, you could provide an image to be substituted for the normal image. How you implement event handling depends on the type of button you use and how you use it. Generally, you implement an action listener, which is notified every time the user clicks the button. The following Java Swing example demonstrates how to create JButton. It creates a simple JButton with string, This is a JButton. Code:

import java.awt.*; import javax.swing.*; public class JButtonDemo { public static void main(String[] a) { JFrame f = new JFrame("JButton Demo"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton b = new JButton("This is a JButton"); f.getContentPane().add(b); f.pack(); f.setVisible(true); } }

Java Swing Combo Boxes The JComboBox is a very handy drop-down menu control that lets you select one option from a list of things. The JComboBox is component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value. Combo boxes require little screen space, and their editable text field form is useful for letting the user quickly choose a value without limiting the user to the displayed values. Combo boxes can be more appropriate when space is limited or more than a few choices are available. A JComboBox can have two very different forms, the default form is the uneditable combo box, which features a button and a drop-down list of values. The second form, called the editable combo box, features a text field with a small button abutting it. The user can type a value in the text field or click the button to display a drop-down list.

The combo box fires an action event when the user selects an item from the combo box's menu. Combo boxes also generate item events, which are fired when any of the items' selection state changes. The following Java Swing example demonstrates the use of JcomboBox. It creates two combo boxes, the uneditable combo box and the editable combo box. Code:

import javax.swing.*; class ComboPanel extends JPanel { String choices[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus","Neptune", "Pluto"}; public ComboPanel() { JComboBox combo1 = new JComboBox(); JComboBox combo2 = new JComboBox(); for (int i=0;i<choices.length;i++) { combo1.addItem (choices[i]); combo2.addItem (choices[i]); } combo2.setEditable(true); combo2.setSelectedItem("X"); combo2.setMaximumRowCount(4); add(combo1); add(combo2); } } public class JComboboxDemo { public static void main(String args[]){ JFrame frame = new JFrame("JCombobox Demo"); frame.add(new ComboPanel()); frame.setSize(200, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

Java Swing Check Boxes A check box is an item that can be selected or deselected, and which displays its state to the user. By convention, any number of check boxes in a group can be selected. The JCheckBox class provides support for check box buttons. The JCheckbox is a control that lets you select more than one attribute at a time on the screen by 'checking' i.e. ticking selections in a list. This is useful when multiple choices are involved, for example the people you want to play in your football team. Each CheckBox has a state of either selected or deselected. Using the JCheckBoxMenuItem class you can also put check boxes in menus. As JCheckBox and JCheckBoxMenuItem are inherited from AbstractButton, Swing check boxes have all the usual button characteristics. For example, you can specify images to be used in check boxes. Check boxes are similar to radio buttons, but their selection model is different. User can select any number of check boxes in a group: none, some, or all can be selected. A group of radio buttons can have only one button selected. A check box generates one item event and one action event per click. Generaly, you listen only for item events, as they let you determine whether the click selected or deselected the check box. This following Java Swing example illustrates you how to create a Check Box component in Java Swing. It creates a simple Swing check box with string, 'This is the JCheckBox'. Code:

import javax.swing.*; public class JCheckboxDemo { public static void main(String[] args){ JFrame frame = new JFrame("JCheck Box Demo"); JCheckBox chk = new JCheckBox("This is the JCheckBox"); frame.add(chk); frame.setSize(200, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

Java Swing - Making Dialogs JDialog is the main class in swing for creating a dialog window. You can use this class to create a custom dialog, or invoke the many class methods in JOptionPane to create a variety of standard dialogs. The JDialog component contains a JRootPane as its only child. The contentPane should be the parent of any children of the JDialog. As a convenience add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write: Code:
dialog.add(child);

And the child will be added to the contentPane. The contentPane is always non-null. Attempting to set it to null generates an exception. The default contentPane has a BorderLayout manager set on it. Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JDialog. In a multi-screen environment, you can create a JDialog on a different screen device than its owner. The Java Swing example below demonstrates use of simple Jdialog. After executing the code a dialog window opens with question Yes or No. If you answer yes it returns 0 and if you answer No it returns 1 which can be seen in the console. Code:
import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; public class JDialogDemo { public static void main(String argv[]) { JOptionPane pane = new JOptionPane("Yes or NO?"); Object[] options = new String[] { "Yes", "No" }; pane.setOptions(options); JDialog dialog = pane.createDialog(new JFrame(), "JDilaog demo"); dialog.setVisible(true); Object obj = pane.getValue(); int result = -1; for (int k = 0; k < options.length; k++) if (options[k].equals(obj)) result = k; System.out.println("Your choice: " + result);

} }

Java Swing Event Handling The Java Swing event model is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source. Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects. Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources. The most important rule to keep in mind about event listeners is that they should execute very quickly. Because all drawing and event-listening methods are executed in the same thread, a slow event-listener method can make the program seem unresponsive and slow to repaint itself. If you need to perform some lengthy operation as the result of an event, do it by starting up another thread (or somehow sending a request to another thread) to perform the operation. Every event-listener method has a single argument an object that inherits from the EventObject class. Although the argument always descends from EventObject, its type is generally specified more precisely. For example, the argument for methods that handle mouse events is an instance of MouseEvent, where MouseEvent is an indirect subclass of EventObject. Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event. Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible. To help you avoid implementing empty method bodies, the API generally includes an adapter class for each listener interface with more than one method. For example, the MouseAdapter class implements the MouseListener interface. An adapter class implements empty versions of all its interface's methods. Inner classes can also be useful for event listeners that implement one or more interfaces directly. You can create an inner class without specifying a name this is known as an anonymous inner class. An EventHandler class supports dynamic generation of simple, one-statement event listeners. Probably the most common use of EventHandler is to extract a property value from the source of the event object and set this value as the value of a property of the target object. The example below demonstrates event handling for a swing component named Slide bar. This program gives you two slide bar and a image inside the frame. When you drag the horizontal slide bar then the image will be increased or decreased from left and right according to the value of the slide bar while when

you drag the vertical slide bar then the image will be increased or creased from top and bottom according to the value of the slide bar. Code:

import javax.swing. *; import javax.swing.event.*; import java.awt.*; public class SwingEventHandling{ public static void main(String[] args) { final JSlider width = new JSlider(JSlider.HORIZONTAL, 5, 150, 125); final JSlider height = new JSlider(JSlider.VERTICAL, 5, 150, 125); class DynamicIcon implements Icon { public int getIconWidth() { return width.getValue(); } public int getIconHeight(){ return height.getValue(); } public void paintIcon(Component c, Graphics g, int x, int y) { g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true); } } Icon icon = new DynamicIcon(); final JLabel jl = new JLabel(icon); class Updater implements ChangeListener { public void stateChanged(ChangeEvent e) { jl.repaint(); } }; Updater ud = new Updater(); width.addChangeListener(ud); height.addChangeListener(ud); JFrame fm = new JFrame(); fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container ca = fm.getContentPane(); ca.setLayout(new BorderLayout()); ca.add(width, BorderLayout.NORTH); ca.add(height, BorderLayout.WEST); ca.add(jl, BorderLayout.CENTER); fm.setSize(250,250);

fm.setVisible(true); } }

Você também pode gostar