java 5 book2

1023
The Smartest Way to Learn Java 5 Evolution of computer Man is truly an amazing being; his effort is always going on inventing such thing, which makes its life easier. Computer is one of the most amazing and useful inventions made by the man. Computer is an electro-mechanical device for storing and analyzing data fed into it. It accepts data as its input (By using an input device Keyboard, Mouse etc.) and analyzes data in a free defined vessel called CPU (Central Processing Unit) and then gives output to the output device (Monitor, Printer etc.). The output to the Monitor is called Softcopy and the output to the printer is called Hardcopy. The diagram of the computer is given below: Softcopy Hard copy Need of Computer Language By: Amit Kumar Agrawal 1 CPU Monito Print Mouse

Upload: amit-kumar-agrawal

Post on 19-Nov-2014

159 views

Category:

Documents


2 download

DESCRIPTION

All detail in Java

TRANSCRIPT

The Smartest Way to Learn Java5

Evolution of computer

Man is truly an amazing being; his effort is always going on inventing such thing, which makes its life easier. Computer is one of the most amazing and useful inventions made by the man.Computer is an electro-mechanical device for storing and analyzing data fed into it. It accepts data as its input (By using an input device Keyboard, Mouse etc.) and analyzes data in a free defined vessel called CPU (Central Processing Unit) and then gives output to the output device (Monitor, Printer etc.). The output to the Monitor is called Softcopy and the output to the printer is called Hardcopy.

The diagram of the computer is given below:

Softcopy Hard copy

Need of Computer Language

As mentioned earlier computer is an electro-mechanical device, it cannot understand our logics and problem directly. It can only understand Binary language or in other wards only, two commands i.e. ON and OFF. The Binary 1 means ON and the Binary 0 means OFF (0 means absent of data and 1 means presence of data). According to there, use the language is divided in to three categories.

Low–level–language. (Machine level language)Assembly language.

By: Amit Kumar Agrawal 1

CPUMonitor Printer

Mouse

The Smartest Way to Learn Java5

Hi-level-language.

Machine – level – language It is also called as Low-level-language. Here it uses the stream of 1’s and 0’s. It doesn’t need any program translator or interpreter; it is directly understandable by the computer.

Assembly language

To avoid the difficulties of Machine-level-language, Assembly language are used. It uses mnemonics like: - ADD, SUB, DIV, and MUL etc. this language is not directly understandable by the computer. So, it need’s the help of a program translator called Assembler.

High – level – language

It is called as procedural oriented language. Here you can use Alphabets, Numeric, and also all other special character. It is machine independent. It is also called User-friendly language. It needs a program interpreter or program translator to convert it in to machine understandable form.e.g. BASIC, COBOL, FORTRAIN, C, C++, Java etc.

Java is a programming language

Java is an object–oriented–programming language; it is truly an object oriented programming language because we cannot use procedural technique of programming to this language as we can do in C++.

Where did the Java name come from? What does it stand for?

The name was chosen during one of several brainstorming session held by the Java software team. They were aiming to come up with a name that evoked the essence of the technology – Liveliness, Animation, Speed, Interactivity and more. "Java" was chosen from among many, many suggestions. The name is not an acronym, but

By: Amit Kumar Agrawal 2

The Smartest Way to Learn Java5

rather a remainder of that hot, aromatic stuff that many programmers like to drink lots of.

Advantages of OOP (Object Oriented Programming)

Why all of we very excited about the OOP? The chief problem with computer programs is complexity. Large programs are probably the most complicated entities ever created by the programmer. Because of this complexity, programs are prone to error, and software error can be more expensive and even destructive. Object Oriented Programming offers a new and powerful way of programming, which is able to solve the complexity of the program. Its aim is clear; it is more reliable then other structure programming language (like C, BASIC, and FORTRAIN etc.). It is easy to modify the error in program and easy to handle it.

Java is Object – Oriented

In general, a software designer engages in five activities during the programming of software:

Analysis - The process of identifying user requirements. Design - The process of developing a solution to user’s needs and

requirement. Implementation - Coding the design in a computer language such as Java.

Test - Ensuring that the finished software satisfies the requirement. Maintenance - Fixing latent defects, adding new features, and keeping the

software up to date with its environment (Such as OS and Database management).

Object Oriented language was introduced as early as 1967. During 1983, Bjarne Stroustrup of AT&T Bell Laboratories, USA introduced a version of the popular programming language C that supports classes. This “C with classes” went on to become C ++; this is very popular computer programming language ever.

Application of Java:

By: Amit Kumar Agrawal 3

The Smartest Way to Learn Java5

Real time system. (RTS). Simulation and Modeling.

Simulation:

To apply real world utility in computer is called simulation.

Model:

To make a diagram or sample of an object is called modeling.

Object Oriented database.

In object oriented database the tables are implemented in the form of object or classes.

Relationships are established through methods of the classes.

Hypertext and Hypermedia.

Object oriented programming due to its inheritance and polymorphism features enables us to handle Hypertext and Hypermedia in Internet environment.

Parallel program.

Object oriented programming enables is to execute multiple programs simultaneously. Through multi programming concept.

CAD/CAM

CAD – Computer Aided Design. CAM – Computer Aided Manufacturing.

Artificial Intelligence and Expert System. (AI/ES)

Artificial Intelligence - Artificial Intelligence is the view that

human cognitive mental states can be duplicated in computing

By: Amit Kumar Agrawal 4

The Smartest Way to Learn Java5

machinery. Accordingly, an intelligent system is nothing but an

information processing system.

Expert System – Expert System is the intelligent system that is nothing but an information processor.

Evolution of Java

Like C and C ++ (and Unlike BASIC), Java is designed for use by the professional programmer. After the development of C++ language By Bjarne Stroustrup in the year of 1983. In the year 1985, James Gosling developed OAK language. In the year of 1995 means after 10 years, he developed Java, due to some legal problem found in the language OAK.

Chronological order of development

BCPL B C C++ OAK Java

Java development team combines the feature of both C, C++ and adds some of there own to develop Java language.

Feature of Java

Compiled and interpreted

It is the first language, which has both facility of compilation and interpretation.

By: Amit Kumar Agrawal 5

1967 1970 1972 1983 1985 1995

JavacSource code of java

Compiler

Byte codeJava

Interpreted

Object program machine code

The Smartest Way to Learn Java5

The Byte code produces after compilation makes the machine more versatile for different machine.

Platform independent and portable.

Changes and upgrades in O.S., processor and any system resources will not force any changes in java language.

It is first language, which is not tied to any particular O.S. or hardware structure.

It generates Bytecode instruction that can be implemented in any machine.

Size of primitive data type is machine independent.

By: Amit Kumar Agrawal 6

Understanding Byte codes

The java compiler generates files of byte codes - instructions for the Java Virtual Machine. Because the JVM has been ported to nearly every kind of computer, these files of byte codes will serve as cross-platform applications.

Javac010110000011100011100011011100010000

Running program

Windows

Mac

UNIX

010010011001011110100010

Source codeJava compiler

Class file JVM

Other class files

The Smartest Way to Learn Java5

Object oriented

It is a truly object oriented language, that means all program code and data are design within object and classes.

Extensive set of classes arranged in packages, we can use in program by inheritance.

Robust and secure

Java provides safeguard has to ensure reliable code. Strict compiled time and Run time checking for a data

type. It is design as garbage (Un use space) collected language. Exception handling mechanism is un-corporate in Java. Absence of pointer ensures security preventing un-

authorized access to memory location.

Distributed

The ability to share both data and program in different

computer is called distributed environment.

Java application can open and access the remote object in

Internet as well as local system due to this distributed

facility.

By: Amit Kumar Agrawal 7

What’s the Java Runtime Environment?

The JVM is part a larger collection of software on the end user’s machine that’s called the Java Runtime Environment, or JRE. Browser vendors, such as Microsoft and Netscape, include JRE in there web browser if you want end user’s to be able to run java applications, you can get a JRE in your JDK (Java Development Kit); end user can also download the JRE separately.

The Smartest Way to Learn Java5

Multithreading

Due to these properties of java, program handles

multiple tasks simultaneously.

It improved interneting performance of graphical

application.

Java time tool support multiprocess synchronization.

Simple, Small and familiar

It does not use pre-processor header file, goto statement etc. (like in C and C++)

It eliminates operator overloading and multiple inheritance.

It is the simplified version of C++.

High performance

Intermediate bytecode produce by java compiler enhanced the performance.

Multithreading enhanced the execution speed of the java program.

Dynamic and extensible

Java program are capable of dynamically linking new class library, methods and objects. From java development kits (JDK).

Java provides the facility of native method.

These are methods, which are support by java program and dynamically link at run time. But written in another language like in C and C++.

By: Amit Kumar Agrawal 8

The Smartest Way to Learn Java5

Difference of Java with C language

Java doesn’t have goto, sizeof, and typedef.

It doesn’t contain struct, union, enum etc.

It doesn’t use type modifier.

It does not use class specifier.

Here pointer is absent.

It does not use preprocessor.

There is new operand use in Java. Like instanceof, <<<, >>> etc.

To abstract level, break and continue is used.

Difference of Java with C ++ language

Does not support operator overloading. Does not take template. It does not support multiple inheritance. However, in Internet it uses

multiple inheritance. Doesn’t support global variable. Destructor are not used in Java, finalise( ) is use.

Hardware, software requirement in Java

Windows 9’x, Windows NT, Windows 2000, Windows XP.UNIX, LINUX.SUN SOLARIOS.DOS Doesn’t support.CPU 80486 (Minimum).

80586 (P-I)Memory 8 MB (Minimum).Hard device Mouse (Microsoft compatible).Window’s (compatible) sound card.CD – ROM.

The first java program (Sample)

By: Amit Kumar Agrawal 9

The Smartest Way to Learn Java5

Program :

/* Hello java program ********************* *@ Amit Kumar Agrawal ********************* *@ Dt. 01-07-2007 **********************/

class Amt001{ public static void main(String args[]) { System.out.println("Hello friend's this is my first Java program."); }}

Path to Java compiler

C:\> CD JDK1.5.0\BIN

C:\ JDK1.5.0\BIN> edit Amt001.java

C:\ JDK1.5.0\BIN> javac Amt001.java

C:\ JDK1.5.0\BIN> java Amt001

Java support system

It include following systems.

Web Server.

Web Browser.

HTML (Hyper Text Markup Language).

Applet.

Java code.

By: Amit Kumar Agrawal 10

The Smartest Way to Learn Java5

Bytecode.

Web Server

It is the program that accepts, request for information and sends the request document.A computer offering services on a network.

Web Browser

It is a program that provides access www and run java Applet. (www – World Wide Web.).An application that fetches and displays Web pages.

The client sends an HTTP message to a computer running web server program. Ask for a document (Applet).

By: Amit Kumar Agrawal 11

HTTP

Client Server

HTTP (Hyper Text Transfer Protocol)It is a type of protocol, which is a vital element required to transfer hypertext documents and data through World Wide Web (www).ProtocolCommunications protocols are a set of rules and procedures that are used by nodes on a network to communicate.

Client Server

The Smartest Way to Learn Java5

The Web server sends the hypermedia HTML (Applet) document to the client.

HTML

It is a program that provides access www and run Java Applet.

Applet

These are small program written at the user end computer for different application in Internet.

Java code

It is the source code used to defining applets in Java.

Bytecode

The compiled Java code called Bytecode, which is machine independent.

Java environment JDK, API

By: Amit Kumar Agrawal 12

HTML

HTML (Hyper Text Markup Language)A set of codes you must use in a document that you plan to present on the www (World Wide Web).HypermediaHypermedia is document that contains hypertext and other media like sound, audio, and graphics components also.HypertextHypertext is the text that contains a hyperlink to other documents.

The Smartest Way to Learn Java5

JDK – Java Development Kit.API – Application Programming Interface.

Component of JDK.

appletviewer. javac. (Java compiler). java. (Java Interpreter). java doc. javah. javap. jdb. Servlets. Java IDL. ORB.

Applet viewer

It enables the user to run Java Applet.

Javac (Java compiler)

It translates the Java source code to Bytecode.

Java ( Interpreter )

It run's applets by reading and interpreting the byte code files. and makes program executable.

Javadoc (Doclets)

It create HTML format document for Java source code files.

Javah

This produce as header file to use with native method.

By: Amit Kumar Agrawal 13

class

Data

Method

Package

The Smartest Way to Learn Java5

Javap ( Java disampler )

It enables the user to convert the Bytecode into source code.

JDB (Java debugger)

It help's to find error written program.

Servlets

A servlet is a Java program intended to be run on a server (such as a web server). Servlets occupy the same place that CGI (Common Graphics Interface) programs do on many servers today. Because they are written in java, however, servlets are platform-independent. You can learn more about servlets and the servlet API at java.sun.com/marketing/collateral/servlets.html.

Java IDL

Sun already has one mechanism to allow objects on one machine to invoke methods on other machines – It is called Remote Method Invocation (RMI). When you are communicating from one class to another, RMI is efficient and easy to use. Sometimes, however your java program will need to communicate in a broader environment, which may include programs written in C++, SmallTalk, or COBOL. That is where the new Java IDL comes in. In order to understand why sun introduced the Interface Definition Language (IDL) for Java, we need to understand about the ORB's (Object Request Broker's).

ORB's (Object Request Broker's)

An Object Requested Broker is unifying piece of software for a large, sophisticated

distributed application. With an ORB, the clients do not have to know where each

server is located. They call the ORB connects them to the service.

The following figure will illustrate the use of ORB in the Network:

By: Amit Kumar Agrawal 14

User Interface

The Smartest Way to Learn Java5

Component of API

It is also called as JSL (Java Sub Language) classes and methods in API are groups in to functional packages are:

Language Support Package.Utilities Package.I/O Package.

By: Amit Kumar Agrawal 15

ORB

Services Services Services

The Smartest Way to Learn Java5

Networking Package.AWT Package.Applet Package.

Language Support Package.

It is the collection of classes and method require for implementation of Basic Feature of Java.

Utilities Package.

It is the collection of classes and to provide utility function like (Date and time).

I/O Package.

It is the collection of classes for manipulating I/O operation.

Networking Package.

It is the collection of classes for communicating with other computer in Internet.

AWT Package. (Abstract Windowing Tool Kit.)

It is the collection of classes that implement platform independent GUI (Graphics User Interface.).

Applet Package.

It is the collection of classes, which creates Java Applets.

By: Amit Kumar Agrawal 16

The Smartest Way to Learn Java5

Step's in executing a Java Program:

Overview of Java Language:

By: Amit Kumar Agrawal 17

Text Editor Writing Java Program

java source code Java document(HTML file)

Javap Javac

Java class file (Byte code file) Javah

Java JDB

Output of the program

Interpreter

Java language

Applet program. Stand alone application

The Smartest Way to Learn Java5

Two types of Java program can be developed.

Stand alone application.

Applet program.

Stand alone program:

These are program written in java to carry out certain task in a local

computer.

The program can read and write files and can do certain application which

the applet can not do.

Web Applet:

These are small programs written in java (Web Applet) net application.

An applet program can only run within a web browser. Hence applet

located in a remote computer (server) can be downloaded via Internet and

executed on a local personal computer (Using a Java capable browser).

Program for example:

By: Amit Kumar Agrawal 18

The Smartest Way to Learn Java5

Program :

Class Hello{ public static void main (String args[ ]) { System.out.println(" This is the example of Java program (It is a sample of stand alone program)."); }}

No semicolon ( ; ) at the end of class definition.

Java application have any no. of classes. But only one of them must include

a main method to initiate the execution.

Java applets will not use main method at all.

If a method is declared as public, it allows access to all other classes.

If a method is declared as, static belongs to entire class, not to a part of any

object of a class.

Void main method does not return any value if the return type is void.

String args[] :- These contain an array of object of class type String.

println (): - It prints the text that you placed in the double quotation mark.

A static function may not contain the non-static function within its

programming body.

JVM always starts from the static block.

Generally stand-alone program contain one main function.

Applet program are the program that enable the Java for web

programming.

Applet program are the program that never contain main().

By: Amit Kumar Agrawal 19

The Smartest Way to Learn Java5

Q.. Is it possible to write a stand alone program that may not contain main(), and run successfully(Write the code if yes)?

Ans: Yes, as we know JVM first searches for the static block, so the Java program that contain a static block with some executable code may run easily.

Program

C:\JDK1.5.0\BIN> edit WOM.java

Class WOM{

static{

System.out.println(“PROGRAM WITH OUT MAIN”);System.exit(0);

}}

C:\JDK1.5.0\BIN> javac WOM.javaC:\JDK1.5.0\BIN> java WOM

Program :

This is the program to show the use of import statement and calculate the square root of a number.

/* Program to show the use of Math class */

import java.lang.Math;

class Amt002{ public static void main(String args[]) { double x=5,y; y=Math.sqrt(x); System.out.println("The square root of the no. is "+y); }}

By: Amit Kumar Agrawal 20

The Smartest Way to Learn Java5

C:\JDK1.5.0\BIN>javac Amt002.java

C:\JDK1.5.0\BIN>java Amt002

Java program structure

1. Documentation section. (Optional)

/* .............................*/ // /** ...............*..............*.................*/

It comprises a set of comment line about the program. Java uses a special type of comment called documentation comment, which is used to generating comments automatically.

2. Package statement. (Optional)

The first statement in a java file is a package statement. It declares a package name and inform the compiler that the classes define belong to the same package.

Package stud1{ .................... ....................}

Package stud2{ .................... ....................}

3. Import statement. (Optional)

These are similar to # include statement in C or C++, this instruct the interpreter to load the method or class contained in the package.

By: Amit Kumar Agrawal 21

The Smartest Way to Learn Java5

4. Interface statement. (Optional)

It is a class including a group of method declaration. It is used when multiple inheritance is implementing.

5. Class definition.

Classes are define to make the objects of real world problem. No. Of classes used depends on complexity of the program.

6. Main method class.

It is the starting point and essential part of java programming while executing.

It creates object of various classes and established a communication between them.

Java tokens

Java character set. Reserved key wards. Identifiers: Rules. Literals Operators. Separators.

Tokens: -

The smallest individual executable unit in a java program is called token.

C 32 Keywords.C++ 64 Keywords.Java 60 Keywords. 27 new Keywords.

Java character set

By: Amit Kumar Agrawal 22

The Smartest Way to Learn Java5

Characters used to write Java tokens are defined by a character set (16 bits provided to the Uni-Code character set).

Uni-code is 16 bits character coding system, which support more than 34000 character (2 16) from 24 languages.

Reserved keywords.

It cannot be used as variable name, classes or methods. All keywords are written in lower case letter. 27 keyword are new in java out of 60 keyword present.

Identifier

These are programmer design token. These are used for naming classes, variables, objects, level, packages, and

interfaces in a program.Rules:

It can have alphabets, digits, underscore( _ ), and dollar sign( $ ). It must not begin with a digit. Uppercase and lowercase are distinct. It can be of any length.

Literals.

There is a sequence of that represent constant value to be stored in variable is called literals.

Integers. Floating point. Character. String. Boolean.

Operators

By: Amit Kumar Agrawal 23

The Smartest Way to Learn Java5

A symbol that takes one or more arguments and operates on them to produce a result.

Unary-a, ++a, --a, +a, a++, a--.

Binary a+b, a-b, a*b, a/b, a%b.

Ternary a>b ? a:b

Separator

These are symbol used to indicate where groups of code divided or arranged.

They define the shape and function of the code.

Parenthesis ( ). Curley braces { }. Square brackets [ ]. Semicolon ';'. Coma ','. Period '.'

Java statement

1. Expression statement.

Assignment, pre- increment, post- increment, pre- decrement, post- decrement, method call, allocation expression.

2. Labeled statement.3. Control statement.4. Synchronization: Multithreading.5. Guarding statement.

By: Amit Kumar Agrawal 24

Java statement

Expression Labeled Control Synchronization Guarding

The Smartest Way to Learn Java5

1. Expression statement

There are seven type of expression statement: -

Assignment. a=5. Pre increment. ++(a+b). Post increment. ++a. Pre decrement. –(a+b) Post decrement. –a Method call. (y = Math.sqrt(x);)

2. Labeled statement

It must begin with a label and target of some jump statement.

3. Control statement

Selection. Iteration Jump.

The selection statement, selects one of several control flow. (e.g. if........., if.......else......., switch)

Iteration repeats a block of statement. (while, do...........while, for)

Jump passes the control to begin or end of the block or a label.

4. Synchronization

It is used for handling Multithreading properties of Java.

By: Amit Kumar Agrawal 25

The Smartest Way to Learn Java5

5. Guarding statement

These are use to ensure safe and reliable code during exception caused by the program.

try, catch, finally.

Implementing of Java program.

Creating Java program. Compiling of Java program. Running of Java program.

JVM ( Java Virtual Machine )

Java compiler produces an intermediate Bytecode for a machine that does not exist physically this machine is called JVM and it exists only inside the computer's memory.

It is a simulated computer with in the Personal Computer and does all major function of real computer.

The process of compiling a Java program in to Bytecode is called as Virtual Machine Code (VMC).

VMC can run in any machine. Java interpreter generates real machine code, which is different from

any different machine. Java Virtual Machine is included by the JRE (Java Runtime

Environment) while running a Java program.

By: Amit Kumar Agrawal 26

Java source code

Java compiler(javac) JVM

Java interpreter

Real machine code

The Smartest Way to Learn Java5

Constant, variable, and data types.

Integer – decimal, octal, hexadecimal. Real – decimal notation, exponential form. Single character. String. Escape sequence.

Constant

It is a fixed value, which don't change during the execution of the program.

By: Amit Kumar Agrawal 27

Java constant

Escape sequence.Non-numericNumeric

Integer

Real

Character

String

The Smartest Way to Learn Java5

Integer

It refers to a sequence of digit

Decimal integer (0-9) Octal integer (0-7) Hexadecimal integer (0-9,a, b, c, d, e, f)

Real

These are the no. Containing fractional value.

Fixed point representation. (Decimal notation (20.08)) Floating-point representation. (Exponential form (20.08 e 0))

A floating point no. is characterized by real no, which is called mantissa raised to a power called exponent, which is an integer.

Character constant

It contains a single character enclose within a pair of single core.

'c', 'a', 's', '&', ',', '$' etc.

String constant

A sequence of character enclose within a double core is called as string constant.

"Amit", "5+3", "Hello!"

Back slash character constant (escape sequence)

They are used in output methods, they consist of two character one back slash with a single character enclose within a single core.'\n' New line.

By: Amit Kumar Agrawal 28

The Smartest Way to Learn Java5

'\t' Tab.'\r' Caries return.'\'' Single core.'\"' Double core.

Variable

Variable may take values at different time during the execution of the program, which are not same.

An identifier denotes a storage location used to store a value.

Rule for variable declaration

Must not begin with a digit. Case sensitive. Should not be a keyword. Blank space not allowed. Can be of any length.

Program :

This is the program to show the use of operator within a program.

/*program to show the use of operator*/class Amt003{ public static void main(String args[]) { double x=5,y=2; System.out.println("X+Y = "+(x+y)); System.out.println("X-Y = "+(x-y)); System.out.println("X*Y = "+(x*y)); System.out.println("X/Y = "+(x/y)); System.out.println("X%Y = "+(x%y)); }}

Program :

By: Amit Kumar Agrawal 29

The Smartest Way to Learn Java5

This is the program to show the use of operator within a program and the escape sequence

/*program to show the use of operator*/class Amt003_1{ public static void main(String args[]) { double x=5,y=2; System.out.print("X+Y = "+(x+y)+”\n”); System.out.println("X-Y = "+(x-y)+”\n”); System.out.println("X*Y = "+(x*y)+”\n”); System.out.println("X/Y = "+(x/y)+”\n”); System.out.println("X%Y = "+(x%y)+”\n”); }

}

Integer (int)

By: Amit Kumar Agrawal 30

The Smartest Way to Learn Java5

Java has four types of integer variable.

Byte (1 Bytes) – 27 to 27-1

Short (2 Bytes) – 2 15 to 215-1

Int (4 Bytes) – 2 31 to 231-1

Long (8 Bytes) - 2 63 to 263-1

Wider int data type require more time to execution, hence smaller type are

prefer, while converting a wider to smallest may result in loss of information.

Floating point type

Float (f) 4 Bytes Double (d) 8 Bytes

Floating point type holds the number containing fractional part.

3.4 e –0383.4 e +038

1.7 e –308 1.7 e +308

Float is single precision no. Double is double precision no. Floating point, no are treated as double precision quantity to force

them single precision mode we most append f or F to the no. NAN. NAN (Not A Number.) 0/0 =

It is used to represent the result of the operation such as 0/0 where the actual result never finds.

(e.g.

Character

By: Amit Kumar Agrawal 31

-231 to +231

-263 to +263

The Smartest Way to Learn Java5

Char is 2 Bytes (Because Uni-code)

Character type (constant) store as a character constant.

It assumes a size of two Byte but only a single character.

Boolean

It is used when we want to test a particular condition during an execution of

a program it can take two value. i.e. true or false.

It is denoted by keyword Boolean.

It uses 1 Byte of storage (Because for storing 1bit of data we need to

reserve at least 1Byte of memory).

All comparison operator return Boolean type value.

Declaration of Variable

A variable must be declared before it is used in a program. It tells the compiler the variable name. It specifies the data type the variable will hold. Place of declaration decides the scope of the variable.

Syntax

Data type var1, var2, var3... varn;

e.g.:

int a,b,c;

By: Amit Kumar Agrawal 32

The Smartest Way to Learn Java5

float x,y;char a,b[]=”Amit Agrawal”;

Getting value to the variable

Assignment. Read.

Variable can be given value before it has used in an expression by using assignment statement or read statement.

Syntax

Variable_name = value; Data type variable_name = value;

The process of giving initial value to a variable is called initialization. Un initialized value are automatically set the default value ZERO.

Read () (Read statement)

Value can be interactively given to him variable through keyboard by using readLine ().

It is invoked using an object in of class DataInputStream.

It reads input from the keyboard as a string. Which is converted to the corresponding data type using a refer class.

Program:

/* program to swap two no. by with out using third variable */import java.io.DataInputStream;

class swap{ int x,y; void get(int m,int n) { x=m; y=n;

By: Amit Kumar Agrawal 33

The Smartest Way to Learn Java5

} void swapn() { x=x+y; y=x-y; x=x-y; }}

class Amt030{ public static void main(String args[]) { int x,y; DataInputStream in=new DataInputStream(System.in); try { System.out.print("Enter a no. : "); x=Integer.parseInt(in.readLine()); System.out.print("Enter a no. : "); y=Integer.parseInt(in.readLine()); { swap s1=new swap(); s1.get(x,y); System.out.println("The value of X= "+s1.x); System.out.println("The value of Y= "+s1.y); s1.swapn(); System.out.println("After swaping the value"); System.out.println("The value of X= "+s1.x); System.out.println("The value of Y= "+s1.y); } } catch (Exception e){} }}

Program :

This is a program to show the use of readLine () to input a data through keyboard.

/* program to show the reading of data from keyboard */

import java.io.DataInputStream;

class Amt004{ public static void main(String args[])

By: Amit Kumar Agrawal 34

The Smartest Way to Learn Java5

{ DataInputStream in=new DataInputStream(System.in);

int n=0;

float m=0.07f;

try { System.out.print("Enter an integer value : ");

n=Integer.parseInt(in.readLine());

System.out.print("Enter a float value : ");

m=Float.parseFloat(in.readLine());

} catch (Exception e) {} System.out.println("Integer no. : "+n);

System.out.println("flaot no. : "+m);

}}

Scope of variable

Instance Class Local

These are declared inside a class

Instance

Instance variable created when objects are instantiated. They take different values for each object.

Class

Class variable are global to a class and belong to entire set of object that the class create.

Only one memory location can be created for each class variable.

By: Amit Kumar Agrawal 35

The Smartest Way to Learn Java5

Local

They are declared and used, inside methods. They are not available for use in outside method. It can be also declared inside program blocks enclosed within

Curley braces. In case of nesting block, each block can contain its own sets of local

variable. We cannot declare the same variable name in inner and outer block.

Symbolic constant

It helps to modify the program easily and makes the program easy to understand.

Syntax

final datatype variable_name =value;e.g.: - final double pi=3.141;

Rules for creating Symbolic Constant

Symbolic name takes the same form as variable name, but written in capital letter to distinguish by convention.

Symbolic constant should not be re-assigned in any other value within the program.

Symbolic constant are declared for any data type. They cannot be declared inside a method, but should be declared in the

beginning of a class as data member.

Class area{ final float Pi=3.141; ..............................;}

Type casting

By: Amit Kumar Agrawal 36

The Smartest Way to Learn Java5

The process of one data type into another is called type casting.

Syntax

Type variable1 =(type) variable2;e.g.: - int x1= (float) x2;

4 Integer types, float and double can be cast to any other type except Boolean.

Casting into a smaller type may result a loss of data. Smaller type can be cast to wider type with out loss of data.

Program :

This program to show the use of symbolic constant.

/* Program to show the Symblolic constant using of final statement */

import java.io.DataInputStream;class Amt005{ final static double Pi=3.141d; public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); int r; double area; try { System.out.print("Enter the radious of any circle : "); r=Integer.parseInt(in.readLine()); area=Pi*r*r; System.out.println("The area of the suplied radious circle is : "+area); } catch (Exception e) {} }}

Program:

By: Amit Kumar Agrawal 37

The Smartest Way to Learn Java5

This program is to show the no. Pyramid by using loop.

/* printing of a no. pyramid by using loop */class Amt006{ public static void main(String args[]) { int i=0,j=0; for(i=1;i<=10;i++) { for(j=1;j<=i;j++) { System.out.print(+i); } System.out.println(""); } }}

Program:

/* program to find out wheather a entered no is palindrome or not */

import java.io.DataInputStream;

class Amt039{ public static void main(String args[]){ DataInputStream in=new DataInputStream(System.in); int a,b,c; a=b=c=0; try { System.out.print("Enter the no. for palindrome checking : "); a=Integer.parseInt(in.readLine()); } catch(Exception e) {} b=a; while(b>0) { c=(c*10)+(b%10); b=b/10; } if(c==a) {

By: Amit Kumar Agrawal 38

The Smartest Way to Learn Java5

System.out.println("The supplied no. is PALINDROME "); } else { System.out.println("The supplied no. is Not PLINDROME "); } }}

Program :

This program is used to show the use of inputting a no. From keyboard and print the no. Pyramid.

/* program of printing a no. pyramid by inputing a no. from keyboard */

import java.io.DataInputStream;

class Amt007{ public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); int i,j,x=0; try{ System.out.print("Enter a no : "); x=Integer.parseInt(in.readLine()); } catch(Exception e){} for(i=0;i<=x;i++) { for(j=1;j<=i;j++) { System.out.print(+i); } System.out.println(""); } }}

Automatic conversion:

By: Amit Kumar Agrawal 39

The Smartest Way to Learn Java5

1. The transactional conversion, which is performed automatically during

calculation of expression according to presence of highest range datatype,

called type promotion.

2. Type promotion seeks compatible operand in evaluation of expression.

3. It needs type casting.

4. All byte and short type are promoted to int type. With out casting we can assign

a value of one type to a variable of different type.

e.g.:

byte b=35;

Widing or promotion:

Assigning a smaller to a larger.

Narrowing:

The process of assigning a larger value to a smaller.

Outputting /Displaying Result on the Screen:

print( ) For print and wait.

println( ) For print and move to next line.

Standard default values:

byte - 0 short – 0 int - 0 long - 0L double – 0.0d float - 0.0f char - \0 or null

By: Amit Kumar Agrawal 40

The Smartest Way to Learn Java5

boolean – false reference – null or \0

Operator and Expression:

Operator is a symbol that tells the computer to perform certain mathematical and logical operation to produce result.

There are eight type of operator used in Java that are:

1) Arithmetic.2) Relational.3) Logical.4) Assignment.5) Increment and Decrement.6) Conditional.7) Bitwise.8) Special.

Arithmetic operator:

It can operate on numeric type and non-numeric type data like character except Boolean.

Arithmetic operators are used to perform arithmetical operation.

Operators - +, -, *, /, % etc.

Expression support by Java:

Integer: If all the operands are integers then the result also an integer type in the integer expression.

Real arithmetical expression: Real operands are used and result is real. Java supports the feature in which the module operators can apply floating-point data. 10.6%6.0 = 4.6

By: Amit Kumar Agrawal 41

The Smartest Way to Learn Java5

Mixed more Arithmetical expression: One operand may be real another may be integer in mixed more expression. Here integer is converted to real & real arithmetic is performing automatically.

Relational operator:

Here comparison can be done upon the operands and result is either Zero or One or Three or False.

Operators: <, <=, >, >=, = =,! =.

Arithmetic operator has priority over relational operator.

Logical operator:

It returns the value true or false according to the truth table.Operator:

&& - And|| - Or! - Not

Assignment operator:

It's used to assign the value of expression to a variable.Syntax: var = expression.

e.g.: a=a+1 or a+=1

Advantage of short hand assignment

L.H.S. not be reapeted.

Statement is more consisted and easier to read.

Code is more efficient.

By: Amit Kumar Agrawal 42

The Smartest Way to Learn Java5

Increment and Decrement operator:

Operators: ++, --.

e.g.: m = 5;

y = ++m;

print(m);

print(y);

result : m = 6, y = 6.

M = 5; Y= M ++;

Print (M); Print (Y);

Result: 6 and 5.

Like this, the decrement operator also performs his task.

Conditional operator:

Format: (Exp1? Exp2: Exp3)

If the conditional expression inside the bracket is true than expression one will

taken else other expression will taken.

Bit wise operator:

The operator is used to manipulate or shift data bits. Bit wise operator may not

apply to float or double.

By: Amit Kumar Agrawal 43

The Smartest Way to Learn Java5

Note: Double & Float is not applicable.

Operator

1. | - Or

2. & - And

3. ~ - Is complement

4. ^ - Ex-or

5. << - Shift left

6. >> - Shift right

7. >>> - Shift right with Zero fill

8. Special operator: There are two special operators in Java. That is

1. Instance of 2. Dot operators.

Instance of: It's an object reference operator and return true of

object in L.H.S. is an instance of class given of R.H.S.

e.g. person instance of student; (Object) (Class)

This operator determine whether the object belong to a particular class or not.

Dot operator: It used to access instance variable method from object and classes. It also used to access classes from packages.

A program for show the use of Bitwise operator.

/*Program to show the use of >>>, <<, >>*/

class Bit

By: Amit Kumar Agrawal 44

The Smartest Way to Learn Java5

{public static void main(String args[]){

int i=0;i=2<<2;System.out.println("i<<2 - "+i);

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

i=8>>>2;System.out.println("i>>>2 - "+i);

}}

Arithmetic expression:

It's a combination of variable constant and operator arranged as for

the syntax of language. Java does have exponential operator in an

arithmetic expression.

Type conversion in expression:

Lower type expression can be prompted to higher type expression.

The process of local conversion can be done by type casting an

expression individually. When float is converted to int fractional part is

prompted. Double to float conversion round of the digit. In long to

integer conversion causes dropping of excess of higher order bits.

Operator president and associability:

By: Amit Kumar Agrawal 45

The Smartest Way to Learn Java5

Order of operator:

Operator at higher level precedence an evaluated first. Same precedence operator evaluated right to left or left to right.

1. Dot( ), ( ), [ ] (left to right)2. Unary minus (left to right)3. ++, ! (left to right)4. --, ~ (left to right)5. *, /, % (left to right)6. +, - (left to right)7. <<, >>, >>> (left to right)8. <, <=, >, >=, instanceof (left to right)9. = =, ! = (left to right)10. | (left to right)11. && (left to right)12. || (left to right)13. ?: (right to left)14. = (right to left)15. op (right to left)

This is the program to find out the temperature entered in Fahrenheit to the centigrade.

/*program to input a temperature in Fahrenheit then convert it in to centigrade*/

import java.io.DataInputStream;

class Amt008{ public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); double f=0,c=0; try { System.out.print("Enter the temperature in Fahrenheit : "); f=Double.parseDouble(in.readLine()); c=(f-32)/1.8; } catch(Exception e) {}

By: Amit Kumar Agrawal 46

The Smartest Way to Learn Java5

System.out.println("The temperature in Fahrenheit "+f+" f is in centigrade is "+c+" c"); }}

Mathematical function:

Java supports several mathematical functions through Math class through java.lang.

Syntax: Math.methodname();

By: Amit Kumar Agrawal 47

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 48

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 49

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 50

The Smartest Way to Learn Java5

Decision making and branching:

When a program makes a sequential control code and joins another part of code. Then it is called branching.

Conditional branching: It based on particular condition. Un conditional branching: This takes place without any

decision.

Control statement:

1. If statement.2. Switch case statement.3. Conditional operator.

If statement:

It's a two-way decision making statement, which use in construction with an expression.

a. Simple if.b. if ... Else.c. Nested if.d. else.... if ladder.

By: Amit Kumar Agrawal 51

The Smartest Way to Learn Java5

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

if statement – of java will allow only the statement which return true or false, rather than the statement which return any integeral value.

Simple if:

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

If ...else:

Syntax: If (test Expression){ statement(s);

By: Amit Kumar Agrawal 52

The Smartest Way to Learn Java5

...................;}else{ statement(s); ....................;}

Nested if ... else:

Syntax:

if (test expression)

{

if(test expression)

statement(s);

else

statement(s);

}

By: Amit Kumar Agrawal 53

The Smartest Way to Learn Java5

else

{

statement(s);

}

statement(x);

By: Amit Kumar Agrawal 54

The Smartest Way to Learn Java5

Else ... if ... ladder

Syntax:

if (test expression){ statement(s);}else if (test expression){ statement(s);}else statement(s); statement(x);

By: Amit Kumar Agrawal 55

The Smartest Way to Learn Java5

Switch ... case statement:

Java has a build in multi-way design statement called a switch. The switch statement test the value of given variable or expression

against the list of case value when a match is found a block of statement associated with that case is executed.

By: Amit Kumar Agrawal 56

The Smartest Way to Learn Java5

The expression inside the switch case may be an integer or character. Value 1, 2, 3, 4, n are constant or constant expression. Each of these values should be unique in a switch block otherwise, it

will hang the computer. Each case must end with a colon. If there is no match with any case specified in the switch case than the

default statement is executed. Each case must be terminated with a break statement.

Syntax:

switch (expression/variable){

case Val 1:statement(s);break;

case Val 2:statement(s);break;

case Val 3:statement(s);break;

default:statement(s)break;

}

Another of the decision-making constructs is the switch-case construct, which is ideally suited for making multiple-choice application, like, for example, user menus. Typically, in situations where we have one value or expression that has to be exactly matched with a list of pre-defined values or options the switch … case is the construct of choice.

The switch statement is a multiway – decision-making construct based upon the evaluated expression. It gives you a faster way to make a decision from a multiple number choice, the break statement is require after each case because if the switch expression contain default then this statement will execute by default and as well

By: Amit Kumar Agrawal 57

The Smartest Way to Learn Java5

the after finding the require condition it will go for checking other cases which is a drawback, so it is better to use break after each case.

Conditional operator:

By: Amit Kumar Agrawal 58

The Smartest Way to Learn Java5

Syntax:

Exp1? Exp 2:Exp 3;

e.g. : ((X!= A)?((X>A)?(4X+100):(X+30)):(3X+50));

Program:

A program to show compute the net amount paid by the costumer if he purchased Rs. X from mill clothes and Rs. Y from handloom clothes

/* program to net amount to be paid by the costumer of a cloth store after all discount */import java.io.DataInputStream;class Amt014{ public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); double x=0,y=0,disx=0,disy=0,net=0; int c=0,d=0; try { System.out.print("Enter the amount of the Mill clothes purchased : Rs. "); x=Double.parseDouble(in.readLine()); if(x>0||x<=100) c=1; if(x>100||x<=200) c=2; if(x>200||x<=300) c=3; else c=4; System.out.print("Enter the amount of the Handloom clothes purchased : Rs. "); y=Double.parseDouble(in.readLine()); if(y>0||y<=100) d=1; if(y>100||y<=200) d=2; if(y>200||y<=300) d=3; else d=4;

By: Amit Kumar Agrawal 59

The Smartest Way to Learn Java5

switch(c) { case 1: disx=0; break; case 2: disx=x*(0.05); break; case 3: disx=x*(0.075); break; case 4: disx=x*(0.1); break; } switch(d) { case 1: disy=y*(0.05); break; case 2: disy=y*(0.075); break; case 3: disy=y*(0.1); break; case 4: disy=y*(0.15); break; } net=(x-disx)+(y-disy); System.out.println("Net amount payable by the costumer : Rs. "+net); } catch(Exception e){} }}

Program :

A program to calculate the division of the student if its mark is entered by the user ?

/* program to find out the student's division if his mark is given */

import java.io.DataInputStream;

By: Amit Kumar Agrawal 60

The Smartest Way to Learn Java5

import java.lang.String;class Amt015{ public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); int rl=0,ch=0; double tot=0,m=0,pc=0; try { System.out.print("Enter the student's roll : "); rl=Integer.parseInt(in.readLine()); System.out.print("Enter the total mark : "); tot=Double.parseDouble(in.readLine()); System.out.print("Enter the mark obtained : "); m=Double.parseDouble(in.readLine()); pc=((m/tot)*100); System.out.println("\n\nThe result of the student :"); System.out.println("Roll no. of the student : "+rl); System.out.println("Max. mark of the Exam : "+tot); System.out.println("Mark obtained by student : "+m); System.out.println("Percentage of the student : "+pc); if(pc>=75) Contd... System.out.println("Division of the student : Honour's"); else if(pc<75||pc>=60) System.out.println("Division of the student : First"); else if(pc<60||pc>=50) System.out.println("Division of the student : Second"); else if(pc<50||pc>=40) System.out.println("Division of the student : Third"); else System.out.println("Division of the student : Fail"); } catch(Exception e){} }}

Program :

A program to test whether a year is leap year or not?

/* program to find out whether the given year is leap year or not */import java.io.DataInputStream;

By: Amit Kumar Agrawal 61

The Smartest Way to Learn Java5

class Amt009{ public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); int y; try { System.out.print("Enter the Year in Four Digited Format : -"); y=Integer.parseInt(in.readLine()); if(y%400==0) { System.out.println("This is the Leap Year. "); } else { System.out.println("This is not a Leap Year. "); } } catch(Exception e){} }}

Looping:

Entry controlled. Exit controlled. While loop. Do loop. For loop. Jump statement.

Break. Continue.

Looping:

The process of repeatedly executing a block of statement is called as looping; the

statement in the block may be executed any no. Of time from 0 -

If loop continues forever then it is called as infinite loop. In looping a sequence of

statement executed until some condition for termination of the loop is satisfied.

By: Amit Kumar Agrawal 62

The Smartest Way to Learn Java5

A loop consist of two parts.

Control statement. Body of the loop.

The control statement test certain condition and then directs repeated execution of

statement. Contain in the body of the loop.

Depending upon the position of the condition or the control statement it may be of

two types.

EntryControl:

. Here control condition is test before the start of the loop execution. It

will not execute the block of statement for once also if the specified

condition is false

e.g., while (test expression)....

ExitControl:

Here test is performing at the end of the body of the loop and before

that, the body is executed unconditionally for the first time. It must run

the body of the loop at least once whether the condition is true or false

this will not hamper the first execution of the block. E.g. do...while (test

expression).

for loop is the easiest to understand of the loop in Java. The for loop is execute the

block of loop for the fixed no. Of time. It's generally used when you know, before

entering the loop, how much time the loop will execute the code.

By: Amit Kumar Agrawal 63

The Smartest Way to Learn Java5

Here is an example to show the use of for loop in Java.

Program :

This is the sample program to show the use of for loop and as well as find out the whether a no is odd or even from a given set of no.

/* program to find out the given no. is even or odd */class Amt010{ public static void main(String args[]){ int n[]={1,2,3,4,5,6,7,8,9,10}; for(int i=0;i<10;i++){ if((n[i]%2)==0) { System.out.println(n[i]+" is a even no.");} else { System.out.println(n[i]+" is a odd no.")

} } }}

By: Amit Kumar Agrawal 64

The Smartest Way to Learn Java5

These are the control statement or control condition tested before the body start of loop execution. The example of this type of loop is:

e.g.while (condition){ statement(S);}

This loop is run only when the condition is true other wise the will not be executed. This loop is never execute the statement if the condition is false.

By: Amit Kumar Agrawal 65

The Smartest Way to Learn Java5

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

Step in looping process:

1. Setting and initialization of a counter.

2. Execution of statement in the loop.

By: Amit Kumar Agrawal 66

The Smartest Way to Learn Java5

3. Test for a specified condition for execution of loop.

4. Incrementing or decrementing the counter.

While loop (Entry control loop)

While loop:

Format:

Initialization;while (test condition){ Loop body;}

By: Amit Kumar Agrawal 67

The Smartest Way to Learn Java5

Here when the test condition is fails control is transfer out of the loop otherwise loop will be continue or repeated.

Here the body of the loop may be executed at all if the condition doesn't satisfy for 1st time.

e.g.:

sum = 0;add = 1;while(n<=10){ sum=sum+n; n=n+1;}System.out.println(sum);

Program:

The program to show the use of while loop

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

Do while statement (Exit control loop)

By: Amit Kumar Agrawal 68

The Smartest Way to Learn Java5

Do while loop:

Format:

Initializationdo { Body of the loop }while (test condition);

Free from language free from any indentation. Since the test, condition is provided at bottom of the loop it always

executed at least one. This loop will execute till the condition is true.

By: Amit Kumar Agrawal 69

The Smartest Way to Learn Java5

Program :

The program to show the use of do while loop.

/* find out the sum of the first ten natural no. */class Amt017{ public static void main(String args[]) { int s=0,n=1; do { s=s+n; n++; }while(n<=10); System.out.println("Summation of the fist ten natural no. : "+s); }}

For loop (Entry control loop)

Format:

for (initialization; test condition; increment or decrement){ Loop body;}

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

Program :

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

By: Amit Kumar Agrawal 70

The Smartest Way to Learn Java5

Additional feature of For loop:

More than one variable can initialize at a time in for loop statement. The increment section also must have more than one part. Test condition may have any compound relation and testing may not be

limited only two loop control variable. We can use expression in the assignment statement of initialization of

increment section. Both initialization and increment in the for statement. We can setup time delay using null statement using for loop.

e.g.:

int s;for(int i=1,s=0;i<=0&&s<100;i++){ s=s+i;}for(int j=0;j<1000;j++){;}System.out.println("The summation of the no. is"+s);

Nesting of for loop:

Format:

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

Jumping statement in loop:

Break and continue:

Java permits to jump from one statement to the end or beginning as well as

jump out of a loop.

An early exit from a loop can be accomplished using a break statement.

By: Amit Kumar Agrawal 71

The Smartest Way to Learn Java5

In case of nesting loop break will exit only a single loop.

e.g.:

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

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

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

Continue causes the loop to be continue of to the next iteration of the

skipping statements.

In while and do loops continue causes the control to go directly to test the

condition and then continue the iteration process.

In for increment section of for is executed before the test condition is

evaluated.

Label loops:

In java we can give, a label is a valid variable name followed by colon.

By: Amit Kumar Agrawal 72

The Smartest Way to Learn Java5

If we want to jump outside nested loop or continue at an outer loop we can use label break or label continue statement.

Classes, Objects and Methods:

Classes:

It defines the state and behavior of basic programming components is called objects.

It provide a terminate method of staying together a group of logically related data item and function that work on them.

In java the data, items are called as field and function are called as methods.

Format:

Class class_name [extends super class name]{ [Variable name;] [Method name;] }

The statements within the square brackets are optional. Once a class type has been define we can create variable of that type we can

called instance of classes or Objects. Extends is used to inherit the property of the Super class or in other words

this is used for inheritance.

Variable and Methods:

Variable:

These are encapsulated in a class are called instance variable because they are created when ever an objects of the class is instantiated.

class rectangle{ int len,bred;}

By: Amit Kumar Agrawal 73

The Smartest Way to Learn Java5

No storage space will be store in memory, when they are declared.

These are also called as member variable.

Method:

Format:

Return_data_type method_name (parameter list){ Statement(s); Body of the method;}

These are declared within the class, immediately after the declaration of instance variable.

These have four basic part:

Type of value that method return:

It can be simple datatype like int, float etc. it can be any class type or void.

Name of the method:

The method name should be the valid variable name or otherwise we can say valid identifier.

Parameter list:

It contains variable name and type of all value you want to give the method as input.

Body of the method:

It describe the operation should be perform on the data.

e.g.

By: Amit Kumar Agrawal 74

The Smartest Way to Learn Java5

class rectangle{ int l, b; void getdata(int x,int y){ l=x; b=y; } int rectArea() { return(l*b); }}

Accessing instance variable and Method:

Instance variable and all the method can be accessed in main class, but method cannot access the variable declared within the another class.

class Access

{

int x;

void method1()

{

int y;

x=10;

y=20;

}

void method2()

{

int z;

z=5;

x=10;

By: Amit Kumar Agrawal 75

The Smartest Way to Learn Java5

y=20;// This is the wrong statement.

}

}

Creating objects:

Initializing.

Object reference.

It is called as instantiating an object.

Format: Class_name object_name=new class_name();

e.g.

rectangle rect1=new rectangle();rect1=rectangle.l;

Creating an object reserves a block of memory to contains space for store

all instance of variable.

New operator creates objects of specified class and returns a reference to

that class.

The method rectangle is the default constructer of the class.

We can create any no of objects of class rectangle.

Each object has its own copy of its instance variable of its class.

Thus any changes made to variable of object has no effect an the variable of

another object.

Accessing class member:

By: Amit Kumar Agrawal 76

The Smartest Way to Learn Java5

Format: FieldsObject_name.variable; // To access field.Object_name.method ();// To access method. Methods

e.g.:

rect1.l = 15;rect1.b = 10;rect1.rectArea();

All variable must be assigned a value before they used in program. To access class member we can used '.' Dot operator. Value can be assigned to instance variable by using method that is declared

inside the class.

Program to compute the area of the rectangle by giving direct value to the variable and invoking a method and passing the value of variable through the method.

/* program to compute the area of rectangle by supplying direct value to it */class rectangle{ int l,b; void get(int x,int y) { l=x; b=y; } int rectArea() { return(l*b); }}class Amt019 { public static void main(String args[]) { int ar1,ar2; rectangle r1=new rectangle();

By: Amit Kumar Agrawal 77

Data items

Function

Class

The Smartest Way to Learn Java5

rectangle r2=new rectangle(); r1.l=20;//assigning value to l r1.b=10;//assigning value to b ar1=r1.l*r1.b;//find out the area directly r2.get(15,10); ar2=r2.rectArea(); System.out.println("The area of first rectangle is : "+ar1); System.out.println("The area of second rectangle is : "+ar2); }}

Program : Program to compute the area of the rectangle by giving value to the variable by using the keyboard and passing the value of variable through the method.

/* program to call a method to do any task */

import java.io.DataInputStream;class rectangle{ int l=0,b=0; void get(int x,int y) { l=x; b=y; } int rectArea() { return(l*b); }}class Amt018{ public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); rectangle r=new rectangle(); int x=0,y=0; try { System.out.print("Enter the length of the rectangle : "); x=Integer.parseInt(in.readLine()); System.out.print("Enter the breadth of the rectangle : "); y=Integer.parseInt(in.readLine()); } catch(Exception e) {}

By: Amit Kumar Agrawal 78

The Smartest Way to Learn Java5

{ r.get(x,y); System.out.println("The area of the rectangle is "+r.rectArea()); } }}

Constructer:

All objects, which are created, must be given initial value. Java supports a special type method called constructer, which enable an

object when it is created. It has the same name as the class itself. It does not return any type not even void. It returns the instance of the class itself.

Program :

Program to show the use of constructer.

/* program to show the use of constructer*/class rectangle{ int l,b; rectangle(int x,int y) { l=x; b=y; } int rectArea() { return(l*b); }}class Amt040{ public static void main(String args[]) { rectangle r1=new rectangle(10,15); int a1=r1.rectArea(); System.out.println("Area of the supplied rectangle is : "+a1);

By: Amit Kumar Agrawal 79

The Smartest Way to Learn Java5

}}

Method overloading:

Polymorphism: -

In java, it is possible to create method, having same name but different parameter and different definition.

It is used when the objects to perform in similar but using different parameter.

Program :

Program to show the use of constructer overloading.

/* program to show the constructer overloading */class Room{ double l,w; Room(double x,double y) { l=x; w=y; } Room(double x) { l=w=x; } double Area() { return(l*w); }}class Amt021{ public static void main(String args[]) { Room r1=new Room(6,3); Room r2=new Room(3.5); System.out.println("The area of the rectangular room is : "+r1.Area()); System.out.println("The area of the square room is : "+r2.Area()); }

By: Amit Kumar Agrawal 80

The Smartest Way to Learn Java5

}

When the same method name are naming different parameters type and no.

of parameter different then java compiler matches the method name with

the no. of parameters and types of parameter to call that method, this

process is called polymorphism.

Static members:

Nesting of methods:

A member declared as static is belonging to class a whole rather than individual object created for the class.

Static variable and static method are referred as class variable and method. Java creates anyone space in memory for a static variable, even if the class

is never actually instantiated. Static methods are called without using object. It can be available for use by other class. These are called using class name follow by dot operator and followed by

method name.

Restriction: (For static)

They can only call. Other static method. They can only access static data. They cannot refer to super class in any way.

Program :

Program to show the use of static method.

/* program to show the use of static method */class Mathop{ static double mult(double x,double y)

By: Amit Kumar Agrawal 81

The Smartest Way to Learn Java5

{ return(x*y); } static double div(double x,double y) { return(x/y); }}class Amt023{ public static void main(String args[]) { System.out.println("The multiplication of the two no. 6.2 & 3 is : "+Mathop.mult(6.2,3)); System.out.println("The division of the two no. 10 & 5 is : "+Mathop.div(10,5));}}

Nesting of method:

A method can be called by using only its name by another method of the same class this is called as nesting of method.

A method can call any no. of method in nesting. A called method can call another method.

Program :

Program to show the use of nesting of method.

/* program to show the use of nesting of method */class nesting{ int x,y; nesting(int m,int n) { x=m; y=n; } int largest() { if(x>y) { return(x); } else { return(y);

By: Amit Kumar Agrawal 82

The Smartest Way to Learn Java5

} } void disp() { int lar=largest(); System.out.println("The largest amoung two is : "+lar); }}class Amt024{ public static void main(String args[]) { nesting n1=new nesting(5,10); n1.disp(); }}

Inheritance:

Single inheritance. Hierarchical inheritance. Multilevel inheritance. Multiple inheritance (By using interface)

It is the concept of deriving a new class from an existing class.

The old class is called as parent class, base class or super class and new class is called as sub-class, derived class or child class.

By: Amit Kumar Agrawal 83

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 84

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 85

The Smartest Way to Learn Java5

Defining a sub-class:

Format:

class sub_class_name extends super_class{ ......................; ......................; ......................;}

Sub class constructer:

It is used to construct the instance variable of both sub-class and super-class.

Sub-class constructer uses the keyword "super" to invoke the constructer method of the super-class.

Call to super constructer must be the first statement in the sub-class constructer.

Application of single inheritance using sub-class constructer.

Program :

The program to show the use of keyword super and sub-class constructer.

/* program to show the use of inheritance (single) */

class Room{ int l,b; Room(int x,int y){ l=x; b=y; } int Area(){ return(l*b); }}class BedRoom extends Room{ int ht;

By: Amit Kumar Agrawal 86

The Smartest Way to Learn Java5

BedRoom(int x,int y,int z){ super(x,y); ht=z; } int vol(){ return(l*b*ht); }}class Amt025{ public static void main(String args[]) { BedRoom bd1=new BedRoom(15,10,5); System.out.println("The area of the bed room is : "+bd1.Area()); System.out.println("The volume of the bed room is : "+bd1.vol()); }}

Super:

It may be only used within a sub-class constructer method. Call to super-class constructer must appear as the first statement within the

sub-class constructer. Parameter in the super call must match the order and type of instance

variable declared in the super-class.

Multilevel inheritance:

It allows building a chain of class, which is called as chain of path.

By: Amit Kumar Agrawal 87

The Smartest Way to Learn Java5

Format:

class A{ ..........; }class B extends A{ ..........; }class C extends B{ ..........; }

Program :

Program to show the use of multi-level inheritance.

/* program to show the use of inheritance (Multilevel inheritance)*/class A{ int x; A(int m){ x=m; }}class B extends A{ int y;

By: Amit Kumar Agrawal 88

The Smartest Way to Learn Java5

B(int m,int n){ super(m); y=n; }}class C extends B{ C(int m,int n){ super(m,n); } int add(){ return(x+y); }}class Amt026{

public static void main(String args[]){ C inh=new C(10,20); System.out.println("The addition of the no.'s is : "+inh.add()); }}

Hierarchical inheritance:

Certain feature in one level may be share by may other below that levels.

Program :

By: Amit Kumar Agrawal 89

The Smartest Way to Learn Java5

Program to show the use of hierarchical inheritance.

/* program to show the use of inheritance(Heirachical)*/

import java.io.DataInputStream;

class A{ final static double pi=3.141;}class circle extends A{ double r; void get(double x) { r=x; } double cirArea() { return(pi*r*r); }}class cylinder extends A{ double ra,ht; void get(double x,double y) { ra=x; ht=y; } double cylArea() { return(2*pi*ra*ht); }}class Amt027{ public static void main(String args[]) { int ch=0; double m,n; DataInputStream in=new DataInputStream(System.in); try { while(1<2) { System.out.println("1. Area of circle");

By: Amit Kumar Agrawal 90

The Smartest Way to Learn Java5

System.out.println("2. Area of cylinder"); System.out.print("Enter your choice no. (0 to escape): "); ch=Integer.parseInt(in.readLine()); switch(ch) { case 1: circle c1=new circle(); System.out.print("Enter the radious of the circle : "); m=Double.parseDouble(in.readLine()); c1.get(m); System.out.println("The area of the circle is : "+c1.cirArea()); break; case 2: cylinder c2=new cylinder(); System.out.print("Enter the radious of the cylinder : "); m=Double.parseDouble(in.readLine()); System.out.print("Enter the height of the cylinder : "); n=Integer.parseInt(in.readLine()); c2.get(m,n); System.out.println("The area of the cylinder is : "+c2.cylArea()); break; case 0: break; default: System.out.println("Enter your choice with in(0-2)"); break; } if(ch==0) { break; } } } catch(Exception e) {} System.out.println("The program is clossing now "); }}

Method Overriding:

We can override method, defined in super classes, when we want an object to respond to a same method but have different behavior when that method is called.

By: Amit Kumar Agrawal 91

The Smartest Way to Learn Java5

When a method in a sub-class having same name and same argument and same return type as that of in super-class is called the method defined in the sub-class invoke or execute instead of that super-class in super-class.

Program :

Program to show the use of method overriding.

/* program to show the overriding of methods*/class Super{ int x; Super(int m){ this.x=m; } void disp(){ System.out.println("The value of x= "+x); }}class sub extends Super{ int y; sub(int x,int y){ super(x); this.y=y; } void disp() { System.out.println("The value of x= "+x); System.out.println("The value of y= "+y); }}class Amt028{ public static void main(String args[]) { sub s1=new sub(10,15); s1.disp(); }}

Final:

All the methods and variable can be overridden by default in sub-class. If , we want to prevent overriding, we can declare as final.

By: Amit Kumar Agrawal 92

The Smartest Way to Learn Java5

Values of a final variable can never be changed. Final variable behave like a class variable, they don't take any space in

individual object of the class. A class that cannot be sub-class is called a final class. Finalized method can be added to any class, which does the opposite of

initialization. To free the non-object resources finalize method is used. By using a method final we ensure that the method is not redefine the sub-

class.

Program :

Program to show the use of final method.

/* program to show the use of final methods*/class Super{ int x; Super(int m) { this.x=m; } final void disp(){ System.out.println("The value of x= "+x);}}class sub extends Super{ int y; sub(int x,int y) { super(x); this.y=y; } void disp1()//we can not override if the method is final check by replace it by disp() { System.out.println("The value of x= "+x); System.out.println("The value of y= "+y); }}class Amt029{ public static void main(String args[]) { sub s1=new sub(10,15); s1.disp();

By: Amit Kumar Agrawal 93

The Smartest Way to Learn Java5

s1.disp1(); }}

Abstract method and Abstract classes:

Java allows redefining a method in sub-class, this making overriding compulsory, which is done by using keyword "abstract".

e.g.:

abstract class shape{ ....................; ....................; ....................; void draw();}abstract void draw(){ ....................; ....................;}

When a class uses one or more abstract method, it should be declared abstract.

We cannot use abstract classes to instantiate the object directly. Abstract method of an abstract class must be defined within its sub-class. We cannot declare abstract constructer and abstract static method.

Visibility control:

Public. Private. Protected. Friendly. Private protected.

Access modifiers are applying to instance variable and method to restrict the access of certain variable method from outside classes.

By: Amit Kumar Agrawal 94

The Smartest Way to Learn Java5

Java provides three types of access modifier they are Public, Private and Protected.

Public:

It makes visible the variable and method to all classes outside the class. Friendly access: When no access modifier is specified the member default

to a limited version to a Public accessibility known as friendly accessibility.

Difference between Public and Friendly:

Public Friendly1. It makes fields visible in all classes 1. It makes fields visible only in the same regardless of their package. Package not in other.

Protected:

Visibility mode of protected lies in between Public and Friendly. It makes the field visible to all classes and sub-classes in the same package

as well as other packages. Non- sub-classes in other package can access a protected member.

Private:

It holds the highest degree of protection and accessible only within their own class, they are not accessible to sub-class and cannot be inherited in sub-class.

Private method behaved as a final method. We cannot override a non-private method in sub-class and make it private.

By: Amit Kumar Agrawal 95

The Smartest Way to Learn Java5

Arrays:

Arrays are an ordered collection of homogeneous data items arranged in contiguous memory location.

Creation of array. Declaration of array. Initialization of array.

Array has two parts, 1st is Array name and 2nd one is array index.

Depending on the number of indices array can be one dimensional, two-

dimensional, and etc.

One-dimensional:

A list of items having one variable name using only one subscript is called one dimensional array or single subscripted variable.

In Java subscript can be begins with zero.

By: Amit Kumar Agrawal 96

The Smartest Way to Learn Java5

The subscript of an array can be integer value, integer constant, exception that yields integer result.

There are three steps in creating the arrays.

Declaration. Creating memory location. Initialization to array.

Declaration:

i. Type array_name [];ii. Type[] array_name;

Size of the array is not declared in declaration. After declaration, we need to create an array in memory location. Array_name = new type[size]; Or Type array_name[] = new type (size);

Initialization:

Process of putting some value into the created array is called array.

Array_name [Sub script] = value;

Trying to access an array beyond its bounding gives error massage.

We can also initialize any array automatically when they are declared.

It is possible to assigned an array object to another.

Loops may be used to initialize large size array.

While initialization, the subscript value must take an integer value.

The array name must not be same with any reserved key word in Java.

Array length:

In Java, all arrays store the allocated size; in a variable called length, we can access the length of array 'a' using 'a. length'.

By: Amit Kumar Agrawal 97

The Smartest Way to Learn Java5

Program :

Program to display a list of given no. in sorted format(ascending).

/* program to short a set of no. */class Amt031{ public static void main(String args[]) { int temp,i,j; int no[]={1,2,3,4,5,6,7,8,9,10}; try { for(i=0;i<10;i++) { for(j=i+1;j<10;j++) { if(no[i]>no[j]) { temp=no[i]; no[i]=no[j]; no[j]=temp; } } } for(i=0;i<10;i++) { System.out.println(+no[i]); } } catch(Exception e){} }}

Program :

Program to display a list of given no. in sorted format(descending).

/* program to short a set of no. */class Amt032{ public static void main(String args[]) { int temp,i,j; int no[]={1,2,3,4,5,6,7,8,9,10}; try

By: Amit Kumar Agrawal 98

The Smartest Way to Learn Java5

{ for(i=0;i<10;i++){ for(j=i+1;j<10;j++){ if(no[i]<no[j]) { temp=no[i]; no[i]=no[j]; no[j]=temp; } } } for(i=0;i<10;i++) { System.out.println(+no[i]); } } catch(Exception e){} }}

Two-dimensional:

These are store in memory either in row measure form or in column measure form.

1st index selects the rows and 2nd index select the column with in that class. We initialize the two dimensional array in many ways. Type array_name [][] = new Type [i][j]; e.g.: int Array[][] = new int[5][6];

Program :

Program to show the use of two-dimensional array (a multiplication table).

/* program print a multplication table*/class Amt033{ final static int R=11; final static int C=11; public static void main(String args[]) { int prod[][]=new int [R][C]; int i,j; System.out.println("MULTIPLICATION TABLE \n\n\n"); for(i=1;i<R;i++) {

By: Amit Kumar Agrawal 99

The Smartest Way to Learn Java5

for(j=1;j<C;j++){ prod[i][j]=i*j; } } for(i=1;i<R;i++){ for(j=1;j<C;j++){ System.out.print(" "+prod[i][j]); } System.out.println(""); }}}

String class:

It defines a number of methods that allow doing a variety of string manipulation task.

S2 = S1.toLowerCase; S2 = String.toLowerCase(S1);

String:

In Java, strings are represented by using character array. E.g.: char ar1 []=new char [i];

In java, strings are class object implemented using two classes. 1. String. (Class) 2. String buffer. (Class) A java string is an instantiated object of string class. A java string is not a character array and is not NULL terminated. Format for string:

String String_name; String_name = new String [];

It is possible to get length of String by using Length method of String class.String. length(String_name);

Java string can be concatenated by using '+' operator.

String Methods:

By: Amit Kumar Agrawal 100

The Smartest Way to Learn Java5

String classes define a no. of methods that allow to do a variety of string manipulation task.

S2=S1.toLowerCase; S2=String.toLowerCase(S1); S2=S1.toUpperCase; S2=S1.replace('x','y'); S2=S1.trim(); (trim method remove the white spaces from front and end) S1.equals(S2); S1.equalsIgnore Case(S2); S1.length(); S1.charAt(n); S1.compareTo(S2); S1.concat(S2); S1. substring(n); S1.substring(n, p); here n=position, p=no. of character.

String Buffer class:

Java.utilJava.io String Buffer class:

Pear = contemporary.

It is a pear class of string. It creates string of flexible length that can be modified in terms of both

length and format. We can insert character and sub string in the middle of a string using this

class.Methods: A Set of method that are being used for Buffering

S1.setCharAt (n,'x');S1.append (S2);S1.insert (n, S2);S1.Setlength (n);

By: Amit Kumar Agrawal 101

String class

The Smartest Way to Learn Java5

Program :

Program to sorting the set of string.

/* program to short a group of string */class Amt034{ static String name[]={"Amit","Ranjan","Lipsa","Deepa","Atal"}; public static void main(String args[]) { int size=5,i,j; String temp=null; try { for(i=0;i<size;i++) { for(j=i+1;j<size;j++) { if(name[j].compareTo(name[i])<0) { temp=name[i]; name[i]=name[j]; name[j]=temp; } } } } catch(Exception e){} for( i=0;i<size;i++) System.out.println(name[i]); }}

Program :

//program to construct one string from another.class Amt044{ public static void main(String args[]) { char c[]={'J','A','V','A'}; String S1=new String(c); String S2=new String(S1); System.out.println(S1); System.out.println(S2); }}

By: Amit Kumar Agrawal 102

The Smartest Way to Learn Java5

Program :

// program to construct string subset of char array.class Amt045{ public static void main (String args[]) { byte ascii[]={65,66,67,68,69,70}; String S1=new String(ascii); System.out.println(S1); String S2=new String(ascii,2,3); System.out.println(S2); }}

Program :

// program to show the use of equals() and equalsIgnoreCase(). class Amt046{ public static void main(String args[]) { String S1="Hello"; String S2="Hello"; String S3="Good-bye"; String S4="HELLO"; System.out.println(S1+" equals "+S2+" -> "+S1.equals(S2)); System.out.println(S1+" equals "+S3+" -> "+S1.equals(S3)); System.out.println(S1+" equals "+S4+" -> "+S1.equals(S4)); System.out.println(S1+" equalsIgnoreCase "+S4+" -> " + S1.equalsIgnoreCase(S4)); }}

Program :

// program to show the use of substring replacement.class Amt047{ public static void main(String args[]) { String org = "This is Amit test, too."; String ser="is"; String sub="was";

By: Amit Kumar Agrawal 103

The Smartest Way to Learn Java5

String res=""; int i; do{ // replace all matching substrings System.out.println(org); i=org.indexOf(ser); if(i!=1) { res=org.substring(0,i); res=res+sub; res=res+org.substring(i+ser.length()); org=res; } }while(i!=-1); }}

Program :

// program to show the use of toUpperCase and toLowerCaseclass Amt048{ public static void main(String args[]) { String S1="Amit Kumar Agrawal."; System.out.println("The string before using any function: "+S1); String Upcs=S1.toUpperCase(); String Lwcs=S1.toLowerCase(); System.out.println("The string after using toUpperCase(): "+Upcs); System.out.println("The string after using toLowerCase(): "+Lwcs); }}

Program :

//program to show the use of charAt() and setCharAt().class Amt049{ public static void main(String args[]) { StringBuffer st=new StringBuffer("Amit"); System.out.println("Buffer before using of any function: "+st); System.out.println("charAt(2) before = "+st.charAt(2)); st.setCharAt(2,'t'); st.setLength(3);

By: Amit Kumar Agrawal 104

The Smartest Way to Learn Java5

System.out.println("Buffer after using of function : "+st); System.out.println("charAt(2) after = "+st.charAt(2)); }}

Program :

// program to show the use of append().class Amt050{ public static void main(String args[]) { String s;

int a=42;

StringBuffer st=new StringBuffer(40);

s=st.append("a=").append(a).append("!").toString();

System.out.println(s);

}}

Program :

// program to show the use of insert().class Amt051{ public static void main(String args[]) { StringBuffer st=new StringBuffer("Hello I Java");

st.insert(8,"like");

System.out.println(st);

}}

Program :

// program to show the use of reverse() to reverse a StringBuffer.class Amt052{ public static void main(String args[]) { StringBuffer s=new StringBuffer("lawargA ramuK timA");

By: Amit Kumar Agrawal 105

The Smartest Way to Learn Java5

System.out.println(s);

s.reverse();

System.out.println(s);

}}

Interface:

Although Java does not support multiple inheritance, but it provide another

procedure called interface to support the same.

It is a special kind of class, which contains only abstract methods and final field.

Interface don't specified any code to implement this method and data field contain

only constant.

Declaration:

interface Interface_name{ Data declaration; Method declaration;}

Data:

Static final data_type variable_name=value;

Method:

Return data_type Method_name (Parameter list);

The method declaration contains a list of method without any body it

terminated with a semicolon (';').

The class that implements the interface must define the body of the method.

e.g.:

By: Amit Kumar Agrawal 106

The Smartest Way to Learn Java5

interface Area{ final static float Pi=3.141f; float calculate(float x, float y); void show();}Extending interface:

Like classes, interfaces can be extended. The new sub-interface will inherit all the member of the super interface

class and property, in the manner similar to sub-class. e.g.:

interface Amit{ int Roll=1; String nm="Amit Kumar Agrawal";}interface Computer extends Amit{ void dis();}

We cannot combine several interfaces into a single interface. An interface cannot extend classes.

Implementing of interface:

These are used as super-class whose properties are inherited by other classes.

It is necessary to create or class which inherit the properties of interface class.

class Engineering implements Science(interface_name){ .............;}

By: Amit Kumar Agrawal 107

The Smartest Way to Learn Java5

Program :

/* program to impleament the use of interfaces to show(Multiple inheritance)*/

interface Area{ static final float pi=3.141f; float com(float x,float y);}class rectangle implements Area{ public float com(float x,float y ) { return(x*y); }}class circle implements Area{ public float com(float x,float y) { return(pi*x*x); }}class Amt036{ public static void main(String args[]) { rectangle r1=new rectangle(); circle c1=new circle(); System.out.println("Area 1 = "+r1.com(10.0f,20.0f)); System.out.println("Area 2 = "+c1.com(5.0f,5.0f)); }}

Any number of dissimilar classes can implement the interface. To implement the methods we need to refer to class object as type of

interface. If a class that implements an interface does not implement all the method of

the interface then the class become an abstract class and cannot be instantiated.

e.g.:

By: Amit Kumar Agrawal 108

The Smartest Way to Learn Java5

Here is an example from Computer purchasing application. Suppose the Costumer

attempt to purchase a computer, but find that the computer provided by the

computer shop is not so good quality, perhaps the speed is slow or CD-ROM is

present is very old model (not present DVD-ROM). So,again, he checks the all

peripheral of the computer and in the meantime, he want to know about the other

computer also. Start by writing an interface that captures this abstract behavior to

solve the above-mentioned problem.

public interface CrownEagle{ public void RAM(); public static final long ROM=8600;//in millisecond.}

private MicroSoft implements CrownEagle{ private Microtek HCL;

MicroSoft() { HCL = new Microtek; }

public void Computer(){ ...............; if(! HCL.PurMe(this,15*ROM))

}

public void PurComputer(){ Computer();}................;}

By: Amit Kumar Agrawal 109

The Smartest Way to Learn Java5

public synchronized boolean Purchased(MicroSoft ms, long dvd){ boolean b_res=true; int indx = findNextSlot();

if(indx = = NOROOM) {

b_res=false; }else{

waiting[indx]=ms;waitFor[indx]=dvd;new waitThread(indx).start();

}return b_res;

}

By: Amit Kumar Agrawal 110

Interface Are Equivalent to Protocols:

Some object-oriented languages let you specify a set of agreed-upon behaviors for a class. They call these agreements protocols. Protocols in those languages are equivalent to interfaces in Java.

Interfaces are more flexible than Abstract classes:

You can use interfaces to give a defined set of behavior to classes that are otherwise unrelated.

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 111

The Smartest Way to Learn Java5

Accessing of interface variable:

Interfaces can be used to declare a set of constant that can be used in different classes.

The constant variable can be available to any class that implement interface. The value can be used in any method and where we can use a final value.

Program :

/* program to implement multiple inheritance using interface*/

class stud{ int rl; void getno(int x) {

By: Amit Kumar Agrawal 112

The Smartest Way to Learn Java5

rl=x; } void print() { System.out.println("The Roll No. Of The Student Is : "+rl); }}

class test extends stud{ float p1,p2; void get(float m1,float m2) { p1=m1; p2=m2; } void print1() { System.out.println("Mark Obtained By The Student :"); System.out.println("Part 1 = "+p1); System.out.println("Part 2 = "+p2); }}

interface extcur{ final static float extwt=6; void putwt();}

class result extends test implements extcur{ float tot; public void putwt() { System.out.println("Extra weitage to Student is : "+extwt); } void disp() { tot=p1+p2+extwt; print(); print1(); putwt(); System.out.println("Total mark = "+tot); }}class Amt037{

By: Amit Kumar Agrawal 113

The Smartest Way to Learn Java5

public static void main (String args[]){ result r1=new result(); r1.getno(1); r1.get(60,70); r1.disp(); }}

Program :

// program to show the use of interface(implements) for a Retail store.

interface AmitProd{ public float getPrice(); public String getProdPrintType();}

interface CrownProd extends AmitProd{ public String getComp();}

interface EagleProd extends AmitProd{ public float PeriPriceCase();}

abstract class Computer implements CrownProd{ float price; Computer(float pr)

By: Amit Kumar Agrawal 114

Avoid using most modifiers:

You are not permitted to declare an interface data member transient, volatile, or synchronized, nor can you declare any member private or protected. While it's not illegal to declare the member (or the methods) abstract, it's redundant – Sun recommends against it. You can add the native key word in the class file if you want to implement the interface the interface's method by using native code.

The Smartest Way to Learn Java5

{ price=pr; } public float getPrice() { return price; }}

class MicroSoft extends Computer{ MicroSoft(float pr) { super(pr); } public String getComp() { return "CrownEagle"; } public String getProdPrintType() { return " MicroSoft Computer "; }}

class HCL extends Computer { HCL(float pr) { super(pr); } public String getComp() { return "HCL,MicroSoft,Infosys"; } public String getProdPrintType() { return " HCL Computer "; }}

class TBook implements EagleProd{ private static final float kItemsPerCase=111; float fprice; String fTitle;

TBook(float pric,String Tit) { fprice=pric;

By: Amit Kumar Agrawal 115

The Smartest Way to Learn Java5

fTitle=Tit; }

public float getPrice() { return fprice; }

public String getProdPrintType() { return " Book entitled "+ fTitle; }

public float PeriPriceCase() { return kItemsPerCase; }}

public class Amt057{ static MicroSoft ms; static HCL hcl; static TBook tb;

public static void init() { ms=new MicroSoft(35000); hcl=new HCL(65500); tb=new TBook(650,"The Smartest Way To Learn Java 2"); }

public static void main(String argv[]) { init(); getInfo(ms); getInfo(hcl); getInfo(tb); }

public static void getInfo(AmitProd theItem) { System.out.println("This product is a "+theItem.getProdPrintType()+" . "); System.out.println("The price is Rs. " + theItem.getPrice()+" each."); System.out.println(""); }}

By: Amit Kumar Agrawal 116

The Smartest Way to Learn Java5

The above programs transaction diagram is as follows.

The created program is concrete classes in this example depend both on abstract classes and on interfaces.

Program :

// program to use interface in a big store called Amit's Store.interface AmitProd{ public float getPrice(); public String getProdPrintType();}interface CrownProd extends AmitProd{ public String getComp();}interface EagleProd extends AmitProd{ public float PeriPriceCase();}abstract class Computer implements CrownProd{ float price; Computer(float pr)

By: Amit Kumar Agrawal 117

The Smartest Way to Learn Java5

{ price=pr; } public float getPrice() { return price; }}class MicroSoft extends Computer{ MicroSoft(float pr) { super(pr); } public String getComp() { return "CrownEagle"; } public String getProdPrintType() { return " MicroSoft Computer "; }}class HCL extends Computer { HCL(float pr) { super(pr); } public String getComp() { return "HCL,MicroSoft,Infosys"; } public String getProdPrintType() { return " HCL Computer "; }}class TBook implements EagleProd{ private static final float kItemsPerCase=111; float fprice; String fTitle; TBook(float pric,String Tit) { fprice=pric; fTitle=Tit; } public float getPrice()

By: Amit Kumar Agrawal 118

The Smartest Way to Learn Java5

{ return fprice; } public String getProdPrintType() { return " Book entitled "+ fTitle; } public float PeriPriceCase() { return kItemsPerCase; }}public class Amt058{ public static java.util.ListIterator theInventory; public static void init() { java.util.LinkedList theInventoryCollection=new java.util.LinkedList(); theInventory = theInventoryCollection.listIterator(); // add some item to the inventory. theInventory.add(new MicroSoft((float)35000.98)); theInventory.add(new HCL((float)65500.55)); theInventory.add(new TBook((float)649.65," The Smartest Way To Learn Java 2 ")); } public static void main(String args[]) { init(); // iterate over inventory, getting info on each item. System.out.println("Amit's Store"); System.out.println(" Tarbha \n\n\n "); while(theInventory.hasPrevious()) { getInfo((AmitProd) theInventory.previous()); } }

public static void getInfo(AmitProd theItem) { System.out.println("This product is "+theItem.getProdPrintType()+

" .");

System.out.println("The price of the product is Rs.

"+theItem.getPrice()+" each.");

System.out.println("");

}

By: Amit Kumar Agrawal 119

The Smartest Way to Learn Java5

}

Suppose I need to make a collection of products in my Amit's Store. Until I

actually make the product, I do not know whether they're MicroSoft, HCL, TBook,

etc. or something else. It's legal to refer to an interface, as long as I assign the

reference to an instance of a class that implements that before I use it. Thus, I can

write the above. The above program shows very useful technique of programming.

In this version of the store, I declare that the store has an inventory that is stored in

a collection called the Inventory. The only thing to know about this collection is

that I can iterate over it by using ListIterator (It is an interface that was added to the

Java 2 SDK.).

Java Collections: Data Structure Framework Collections store and organize objects for efficient access

Java collections: traditional data structures implemented as an object-

oriented framework

Currently only most "basic data structures sufficient for most needs"

Sets, linked lists, arrays, and maps

Efficiency depends on organization and use

Linked vs. sequential allocation, and hashing vs. sorted search trees

The collections library utilizes heavily inheritance and polymorphism

The library is implemented as a kind of (lightweight) framework, and it

enables user-defined extensions

Separation of interfaces + their implementations:

Collection

Set implemented by HashSet and LinkedHashSet

o SortedSet implemented by TreeSet

By: Amit Kumar Agrawal 120

The Smartest Way to Learn Java5

List implemented by ArrayList and LinkedList

Map implemented by HashMap, IdentityHashMap, and

LinkedHashMap

SortedMap implemented by TreeMap

additionally, we have Iterator and ListIterator interfaces

The idea: always use collections through interfaces, and

Separately create them as concrete collections:

set set = new HashSet ();

set.add ("first");

set.add ("second");

int n = set.size (); // n is 2

assert set.contains ("first");

You should always ask what is the most general class or interface that can

do the required job

Additionally, a set of abstract classes that provide skeletons for

implementations

These abstract classes apply the Template Method pattern

By: Amit Kumar Agrawal 121

The Smartest Way to Learn Java5

The symbols shown in the figure above define interfaces. They can only be used as

attribute definition, not as instantiation class names:

Collection xx = null;

xx = new Collection ( );  // error !

Set yy = null;

SortedSet zz = null;

The figure also provides the directions of the dependencies.

xx = yy;

xx = zz;

yy = xx;  //  error !

By: Amit Kumar Agrawal 122

The Smartest Way to Learn Java5

Corresponding Implementations

Implementations

Hash Table

Resizable Array

Balanced Tree

Linked List

Interfaces

Collection HashSet ArrayList TreeSet LinkedList

Set HashSet   TreeSet  

SortedSet     TreeSet  

List   ArrayList   LinkedList

Map HashMap   TreeMap  

SortedMap     TreeMap  

The table above defines the implementations that correspond to the interfaces

shown in the previous figure. An object defined by an interface must be instantiated

by means of a class lying on the same line as the interface:

Collection xx1 = new HashSet ( );// HashSet on the same line as Collection Collection xx2 = new ArrayList ( ); SortedSet yy = new TreeSet ( );

Of course each collection can also be instantiated under its proper class:

ArrayList al = new ArrayList ( );

Goals

• To introduce you to the data structure classes that come with the JDK;

• To talk about how you design a library of related classes

• To review which data structures are the best tools for a variety of algorithmic

tasks

By: Amit Kumar Agrawal 123

The Smartest Way to Learn Java5

History

In the original version of the Java Development Kit, JDK 1.0, developers were provided very few data structures. These were:

– Vector – Stack: which extended Vector – Hashtable: very similar to our implementation of HashMap– Dictionary: an abstract class that defined the interface and some

functionality for classes that map keys to values. Dictionary served as the base class for Hashtable.

– Enumeration: was a simple version of our Iterator that allowed you to iterate over instances of Hashtable and Vector.

Concurrent Modification

Iterators have to keep references to the underlying data structure to maintain their sense of current position.

Thought experiment:

Create a LinkedList, add elements, get an iterator, advance it. Now using a method in the list not the iterator, delete the iterator's next

item Now call next() on the iterator. What goes wrong?

.Any time you create an iterator, modify the underlying collection, and then use the iterator, you will get a ConcurrentModificationException.

How do you think they implement the check?

By: Amit Kumar Agrawal 124

The Smartest Way to Learn Java5

Vector:

The concept of variable argument to a method is not supported in Java. But this can be achieved by using vector containing in java.util package. Vector class can be used to create a generic dynamic array Known as vector

and can hold object of any number. Object may not be homogeneous. In Java 2,vector was reengineered to extend AbstractList and implement the

List interface, so it now is fully compatible with collections.

Format of vector:

By: Amit Kumar Agrawal 125

The Smartest Way to Learn Java5

Vector () Vector (int size) Vector (int size, int incr) Vector (collection c)

Syntax:

Vector vector_name=new Vector ();

A vector can accommodate an unknown number of items even if size is specified.

We cannot directly store simple datatype in a vector but we can only store object.

Simple data can be converted into object in a vector class using wrapper class.

Advantage: (over arrays)

It is convenient to store object in memory. Hence, vectors are preferred over

array.

It can store list of object that may vary in size.

We can add, delete object from the list and when required.

Vector methods:

List.addElement(item);List.ElementAt(n);List.size();List. capacity();List.removeElement (item);List.removeAllElement();List.copyInTo(array);List.insertElementAt(item, n);

By: Amit Kumar Agrawal 126

The Smartest Way to Learn Java5

Program :

// program to show the use of varios vector operations.

import java.util.*;

class Amt053{ public static void main(String args[]) { //initialise size is 3, increment is 2 Vector v=new Vector(3,2);

System.out.println("Initial size : "+v.size());

System.out.println("Initial capacity: "+v.capacity());

v.addElement(new Integer(1));

v.addElement(new Integer(2));

v.addElement(new Integer(3));

v.addElement(new Integer(4));

System.out.println("Capacity after addition four new:

"+v.capacity());

v.addElement(new Double(7.76));

System.out.println("Current capacity: "+v.capacity());

v.addElement(new Double(1.01));

v.addElement(new Integer(11));

System.out.println("Current capacity: "+v.capacity());

v.addElement(new Integer(8));

v.addElement(new Integer(6));

System.out.println("First Element in the List : "+

(Integer)v.firstElement());

System.out.println("Last Element in the List : "+

(Integer)v.lastElement());

if(v.contains(new Integer(3)))

System.out.println("vector contains 3.");

Enumeration vEnum=v.elements();

System.out.println("\nElements in vector : ");

while(vEnum.hasMoreElements())

By: Amit Kumar Agrawal 127

The Smartest Way to Learn Java5

System.out.print(vEnum.nextElement()+" ");

System.out.println();

}}

Stack:

Stack is the sub-class of vector that implements a standard last-in, first-out

stack.

It includes all methods defined by the vector, and has some of its own.

It only defines the default constructer.

Methods used by stack:

1) booleanempty(): - Returns true if the stack is empty, otherwise return false.2) Objectpeek(): - It return the top element of the stack, with out remove it.3) Objectpop(): - It return the top element of the stack and also remove the

element.4) Objectpush(Object element): - Pushes the element onto the stack. Element

is also return.5) intsearch(Objectelement): - Searches for element in the stack. If found; its

offset from the top of the stack is returned, otherwise, -1 is returned.

Program :

// program to show the use of stack class.import java.util.*;class Amt054{ static void showpush(Stack st,double a){ st.push(new Double(a)); System.out.println("push("+a+")"); System.out.println("stack : "+st); } static void showpop(Stack st) { System.out.print("pop = "); Double a=(Double)st.pop(); System.out.println(a); System.out.println("stack: "+st); }

By: Amit Kumar Agrawal 128

The Smartest Way to Learn Java5

public static void main(String args[]) { Stack st=new Stack(); System.out.println("stack of Amit : "+st); showpush(st,42.06); showpush(st,75.00); showpush(st,414); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch(EmptyStackException e) { System.out.println("Amit the stack is empty"); } }}

Dictionary:

Dictionary is an abstract class that represents an entity/key storage repository and operates much like Map. Given a key and value, you can store the value in instance of Dictionary class.

Methods use for Dictionary are listed as follows:

Enumeration elements(): - Returns an enumeration of the values contained in the Dictionary.

Object get(Object key): - Return the object that contains the value associated with entity. If entity not found in the Dictionary, a null object is returned.

boolean isEmpty(): - It return true if Dictionary is empty, otherwise false. Enumeration keys(): - Return an enumeration of the keys contained in the

Dictionary. Object remove(Object key): - Removes key and its value. Return the value

associated with entity. If object key is not found a null object is return. intsize(): - Return the number of entries in the Dictionary.

By: Amit Kumar Agrawal 129

Map: -

An unordered collection class that allows duplicates. e.g. collection class and list.

Collection class: -

Data structures that facilitates rapid access and/or updates.

List: -

A dynamic collection class that can efficiently be updated (by adding and /or removing elements). A list has a natural order and allows delicacy.

The Smartest Way to Learn Java5

Hashtable:

It is associated with original java.util package, and a perfect implementation of a Dictionary.

Java2 reengineered Hashtable so that it also implements the Map interface. It is the integrated collection of framework, it is same as HashMap, but is

synchronized. Like HashMap, Hashtable stores key/value pairs in a hash table. We have to specify an object that used a key, and the value that we want

linked to the key. The key is then hashed, and result the hash code, which is used as the index at which the value is stored within the Hashtable.

The Hashtable constructers are as follows:

Hashtable ()Hashtable (int size)Hashtable (intsize, float fillRatio)Hashtable (Map m)

Methods for Hashtable:

void clear() – Resets and empties the hash table. Object clone() – Return a duplicate of the invoking object.

By: Amit Kumar Agrawal 130

The Smartest Way to Learn Java5

boolean contains (Object value) – Return true if some value equal to value exists within the hash table. Otherwise false.

boolean containsKey(Object key) – Returns true if key found within the hash table, otherwise false.

boolean containsValue(Object value) – Returns true if the value supplied in the method is present in the hash table, otherwise return false.

Enumeration elements() – Returns an enumeration of the values contained in the hash table.

Object get(Object key) – Returns the object that contain the value that is associated with the key. If the key is not present then a null object is returned.

boolean isEmpty() – Returns true if the hash table is empty. Otherwise, false value is return.

void rehash() – Increase the size of the hash table and rehashes all of its keys.

Object remove(Object key) – Removes key and its value. Returns the value associated with key. If key is not in hash table, a null object is returned.

int size() – Return the number of entries in the hash table. String toString() – Returns the string equivalent of a hash table.

Program :

// show the use of hash table.import java.util.*;class Amt055{ public static void main(String args[]) { Hashtable Am=new Hashtable(); Enumeration names; String A_str; double Amba; Am.put("Amit Agrawal",new Double(760.00)); Am.put("Lipsa Rath",new Double(662.00)); Am.put("Deepamala Mishra",new Double(572.00)); Am.put("Sasmita Naik",new Double(667.00)); names=Am.keys(); while(names.hasMoreElements()) { A_str=(String)names.nextElement(); System.out.println(A_str+" : "+Am.get(A_str)); } System.out.print("\n");

By: Amit Kumar Agrawal 131

The Smartest Way to Learn Java5

Amba=((Double)Am.get("Amit Agrawal")).doubleValue(); Am.put("Amit Agrawal",new Double(Amba+80)); System.out.println("Amit Agrawal's Present Mark : "+Am.get("Amit Agrawal")); }}

Properties:

It is a sub-class (child class) of Hash table. It is mainly used to manipulate lists of values; in which the key is a string. Property constructers, which is used to define a property class as follows.

Properties () Properties (properties prop default)

Methods used by properties are as follows:

String getProperty(String key) – Return the value associated with key. If the key not in the property lists and as well in the default property list. It, return a null object.

String getProperty(String key, String default property) – Return the value associated with key. Default property is returned if key is neither in the list nor in the default property list.

void list(PrintStream streamOut) – It sends the property list to the output stream linked to streamOut.

void list(PrintWriter streamOut) - It sends the property list to the output stream linked to streamOut.

Enumeration propertyNames() – It return the enumeration of the key. This includes those keys formed in the default property list too.

Program :

// program to show the use of property class.

import java.util.*;class Amt056{ public static void main(String args[]) { Properties CAP=new Properties();

Set STA;

By: Amit Kumar Agrawal 132

The Smartest Way to Learn Java5

String str;

CAP.put("Orissa","Bhubaneswar");

CAP.put("Bihar","Patna");

CAP.put("Chhattis Garh","Raipur");

CAP.put("Maharastra","Mumbai");

STA=CAP.keySet();

Iterator it=STA.iterator();

while(it.hasNext())

{

str=(String)it.next();

System.out.println("Amit says the Capital of "+str+" is

"+CAP.getProperty(str)+" ."); }

System.out.print("\n");

str=CAP.getProperty("Assam","Not present in the property list");

System.out.println("Amit says the Capital of Assam is

"+str+" .");

}}

Using an iterator:

Before we access a collection through iterator, we must obtain one. Each of the collection classes provides an iterator () method that returns an iterator to the start of the collection. By using this iterator object, we can access each element in the collection, one element at a time.We use following steps to contents of a collection through iterator:

By: Amit Kumar Agrawal 133

Iterators versus for Loops:

If we are coming to Java from Smalltalk, my use of an iterator here will seem quite natural. If most of we experienced in C or C++, however, we may wonder why I did not use an array and a for loop. The answer is that Java collections allow for dynamic resizing, and are usually easier to code than arrays with for loops.

The Smartest Way to Learn Java5

1. Obtain an iterator to start of the collection by calling the collection's iterator () method.

2. Set up a loop that makes a call to hasNext (). Have the loop iterate as long as hasNext () return true.

3. Within the loop, obtain each element by calling next ().

For the collection of List, we can obtain iterator by calling ListIterator. As explained in the program 53. It is just like iterator.

Some method used for iterator:

boolean hasNext () – Returns true if there is any more elements next to the current element. Otherwise it return false.

Object next () – Returns the next element. Throws NoSuchElementException if there is not a next element.

void remove () – Removes the current element from the collection. Throws IllegalStateException if an attempt is made to call remove() that is not preceded by a call to next().

void add (Object obj) – Inserts obj into the list in the front of the element that will be returned by calling the next ().

boolean hasPrevious () – Returns true if there is any more elements before the current element. Otherwise it return false.

Object previous () – Returns the previous element. NoSuchElementException is thrown if there is not a previous element.

int nextIndex () – Return the index of the next element. If there is not any next element, it returns the size of the list.

int previousIndex () – Returns the index of the previous element. If there is not any previous element, it returns –1.

void set (Object obj) – Assign obj to the current element. This is the element last returned by a call to either next (), previous ().

J2SE 1.5

The extra addition in J2SE1.5 or Java5Generics, Metadata, Syntax enhancements

Generics

By: Amit Kumar Agrawal 134

The Smartest Way to Learn Java5

Parameterized classes and methods

- Supports List<E>, AtomicReference<T>, etc

An extension of GJ (Wadler et al)

- Adds wildcards (“?”)- Supports void add(List<? extends Number>)

A compile-time only language extension

- Parameterized types are NOT macro expanded- Compiler can “erase” type parameters after checking them- Some usage limitations (arrays, instanceof) due to lack of guaranteed run-

time type knoweldge

Improves safety and (usually) readability

- Collections and related APIs are now generic

Using Generic Collections

Old:// Removes 4-letter words from c; elements must be strings

static void expurgate(Collection c) {

for (Iterator i = c.iterator(); i.hasNext(); )if (((String) i.next()).length() == 4)

i.remove();}

New:

static void expurgate(Collection<String> c)

By: Amit Kumar Agrawal 135

The Smartest Way to Learn Java5

{for (Iterator<String> i = c.iterator(); i.hasNext(); )

if (i.next().length() == 4)i.remove();

}

Metadata Annotations

Act as user-defined qualifiers- javadoc-like syntax

Compiler knows nothing about semantics- Just places annotations in classfile- Accessible at runtime using extensions to java reflection API

Manipulated by user-defined tools at any of several stages- IDEs, Compile-time preprocessors- J2EE code generation tools- Bytecode analysis and rewriting tools- Load-time tools- Runtime support packages

Annotations Example

Using:

@Persistent

@UseCases({"payroll", "taxprep"})

@Author(@Name(first = "John", last = "Doe"))

class Employee {@Nonnull private String name;@Transactional(mode = Transactional.readOnly)public getName();

// ...}

By: Amit Kumar Agrawal 136

The Smartest Way to Learn Java5

Defining:

public @interface Persistent {}

Enhanced for Loop

Old:

void cancelAll(Collection c) {

for (Iterator i = c.iterator(); i.hasNext(); ) {

TimerTask tt = (TimerTask) i.next();tt.cancel();

}}

New:

void cancelAll(Collection<TimerTask> c) {

for (TimerTask task : c)task.cancel();

}

Also works for arrays:

int sum(int[] a) {

int result = 0;for (int i : a) result += i;

return result;}

Autoboxing/ Unboxing:

Old:

By: Amit Kumar Agrawal 137

The Smartest Way to Learn Java5

public class Freq {

public static void main(String[] args) {

Map m = new TreeMap();for (int i=0; i<args.length; i++) {

Object freq = m.get(args[i]);m.put(args[i], (freq==null ? new Integer(1) :new Integer(((Integer)freq).intValue() + 1)));

}System.out.println(m);

}}

New:

public class Freq {

public static void main(String[] args) {

Map<String, Integer> m = new TreeMap<String, Integer>();for (String word : args) {

Integer freq = m.get(word);m.put(word, (freq == null ? 1 : freq + 1));

}System.out.println(m);}}

Static import:

Old:

import org.iso.Physics;...double molecules = Physics.AVOGADROS_NUMBER * moles;x = Math.cos(Math.PI * theta);

New:import static org.iso.Physics.*;import static java.Math.*;

By: Amit Kumar Agrawal 138

The Smartest Way to Learn Java5

...double molecules = AVOGADROS_NUMBER * moles;x = cos(PI * theta);

Wrapper class:

Vector can not handle primitive data type like int, char, float etc. hence

primitive may be converted into object type using Wrapper classes present

in java.lang package.

*//* convertion of primitive no. to object using constructer method:

Integer intvalue=new Integer(i);

Float floatvalue=new Float(f);

Character charvalue=new Character();

Conversion of object to primitive no. Using type value method:

Type value:

int i = Intvalue.intValue();

float f=Floatvalue.floatValue();

Conversion of no. to strings:

Str =Integer.toStrng(integer variable);

Conversion of string to numeric:

Intval=Integer.valueof (str);

By: Amit Kumar Agrawal 139

The Smartest Way to Learn Java5

Conversion of numeric string to primitive no.:

int i=Integer.parseInt (str);

Program :

/* program to show the use of wrapper class*/

class Amt035{ private final static Float _oneTenth=new Float(0.1); public static void main(String args[]) { Float aone=new Float(1.0); Float thesum=new Float(0); for(byte i=0;i<10;i++) thesum=new Float(thesum.floatValue()+_oneTenth.floatValue()); if(aone.equals(thesum)) System.out.println("the numbers are the same: "+aone+" and "+thesum+"\n"); else System.out.println("The numbers are different: "+aone+" and "+thesum+"\n"); }}

Program :

/* program to show the use of wrapper class(compound intrest calculation)*/import java.io.*;import java.lang.*;import java.util.*;class Amt041{ public static void main(String args[]) { double pri=0; double irt=0; int yr=0; try { DataInputStream in=new DataInputStream(System.in); System.out.print("Enter the principle amount : Rs. "); System.out.flush(); String prin=in.readLine(); System.out.print("Enter the intrestrate amount: ");

By: Amit Kumar Agrawal 140

The Smartest Way to Learn Java5

System.out.flush(); String irtn=in.readLine(); System.out.print("Enter the no. of year : "); System.out.flush(); String yrn=in.readLine(); pri=Double.parseDouble(prin); irt=Double.parseDouble(irtn); yr=Integer.parseInt(yrn); } catch(Exception e) {} int x=1; double sm=pri; while(x<=yr) { sm=sm*(1+(irt/100)); x++; } System.out.println("The Amount paid by the costumer is Rs. "+sm); }}

Program :

/* program to show the use of wrapper class(compound intrest calculation) by using function */import java.io.*;import java.lang.*;import java.util.*;class Amt042{ static double loan(double prin,double irtn,int yrn) { int x=1; double sm=prin; while(x<=yrn) { sm=sm*(1+(irtn/100)); x++; }

return sm; } public static void main(String args[]){ double pri=0; double irt=0; int yr=0;

By: Amit Kumar Agrawal 141

The Smartest Way to Learn Java5

try { DataInputStream in=new DataInputStream(System.in); System.out.print("Enter the principle amount : Rs. "); System.out.flush(); String prin=in.readLine(); System.out.print("Enter the intrestrate amount: "); System.out.flush(); String irtn=in.readLine(); System.out.print("Enter the no. of year : "); System.out.flush(); String yrn=in.readLine(); pri=Double.parseDouble(prin); irt=Double.parseDouble(irtn); yr=Integer.parseInt(yrn); } catch(Exception e){}

double ans=loan(pri,irt,yr); System.out.println("The Amount paid by the costumer is Rs. "+ans); System.out.println("The program is clossing now "); int j; System.out.print("\n "); for(int i=0;i<=10;i++) { System.out.print('-'); for(j=0;j<=13000000;j++) {;} System.out.print("\b \b"); System.out.print('|'); for(j=0;j<=13000000;j++) {;} System.out.print("\b \b"); System.out.print('/'); for(j=0;j<=13000000;j++) {;} System.out.print("\b \b"); System.out.print('-'); for(j=0;j<=13000000;j++) {;} System.out.print("\b \b"); System.out.print('|'); for(j=0;j<=13000000;j++) {;} System.out.print("\b \b"); System.out.print('\\'); System.out.print("\b \b");

By: Amit Kumar Agrawal 142

The Smartest Way to Learn Java5

} }}

Packages:

It consists of classes and interfaces grouped together according to functionality.

Advantage:

Classes contained in the packages of other program can be easily reused. Two classes in two different packages can have the same name. Packages provide a way to hide classes. Packages provide a way for separating design from coding.

API – Application Programming Interface.UDP – User Defined Package.

Java API:

java.lang :-

Language for support classes for primitive type, String, Math, Thread and Exception.

java.util :-

It contain language utility package it contain Vector, Hashtable, Randomnumber, Date, LinkedList, ListIterator etc.

java.io :-

This package consist of io support classes for all input and output task.

java.awt :- (Abstract Windowing Toolkit)

By: Amit Kumar Agrawal 143

The Smartest Way to Learn Java5

Classes for implementing GUI such as Windows, Menus, Buttons, List etc.

java.net : - (Internet)

It is used as networking.

java.applet :- This consists of classes for creating and manipulating applet.

java.rmi :- The basis for Java's Remote Method Invocation mechanism.

java.security :- Implements Java's Security mechanism.

System package: -

Classes stored in a System package can be accessed by two ways.

Fully qualified class name. Import statement.

e.g.: -

Fully qualified class name:

java.awt.font;

Import statement:import java.*;

By: Amit Kumar Agrawal 144

The Smartest Way to Learn Java5

Naming convention: -

Package begins with lower case letter. Every package name must be unique, to best use of package. To ensure uniqueness in naming packages, domain name as used as prefix

to package name.

e.g.:

Domain_name.package_name

We can create a hierarchy of packages with in package by separating different level with dots '.'.

Creating of package: - Format for declaring of package: -

package package_name;{ class A{ ...; ...; } class B{ ...; ...; }}

We can create a package by using keyword "package" followed by a Package name.

Package must be created at beginning of a file. Before declaration of class. Classes to be put in the packages may be declared as public to make it

accessible of the package. Dot class files must be located in the directory having same name as that of

package. This directory must be a sub directory of the directory where classes that

will import the package are located. We can specify multiple names in a package statement.

By: Amit Kumar Agrawal 145

The Smartest Way to Learn Java5

A Java package file can have more than one class, out of which one class may declare as public and that class name with dot java extinction is the source file name.

Accessing a package : -

import first_package.second_package.third_package.class_name; Compiler should search the entire package hierarchy if star or asterisk '*' is

mentioned.

Program :

This program is show the use of package and a complete reference to make a package.

c:\jdk1.5.0\bin>md p1c:\jdk1.5.0\bin>cd p1c:\jdk1.5.0\bin\p1>edit A.java

/* this is the program to check the package test */package p1;public class A{ public void displayA(){ System.out.println("This program test the package utility"); }}

Alt+F+Xc:\jdk1.5.0\bin\p1>javac A.javac:\jdk1.5.0\bin\p1>cd..

By: Amit Kumar Agrawal 146

The asterisk form of import is not a wildcard:

The asterisk in an import tells the compiler to look at every public class named in that package. It is not as the wildcard can be used in your command interpreter. You cannot write: Import java.awt.b*;to get all classes whose name starts with 'b'.

The Smartest Way to Learn Java5

c:\jdk1.5.0\bin>edit Amt038.java

/* this is the main programing body for package test program */import p1.A;class Amt038{ public static void main(String args[]) { A obj1=new A(); obj1.displayA(); }}

Alt+F+Xc:\jdk1.5.0\bin>javac Amt038.javac:\jdk1.5.0\bin>java Amt038

Program :

This program is used to show to manufacture more than one package and use of both package in a program.

c:\jdk1.5.0\bin>md p1c:\jdk1.5.0\bin>cd p1c:\jdk1.5.0\bin\p1>edit A.java

/* this is the program to check the package test */package p1;public class A{ public void displayA() { System.out.println("This program test the package utility"); }}

Alt+F+Xc:\jdk1.5.0\bin\p1>javac A.javac:\jdk1.5.0\bin\p1>cd..c:\jdk1.5.0\bin>md p2c:\jdk1.5.0\bin>cd p2c:\jdk1.5.0\bin\p2>edit B.java

package p2;public class B{ protected int m=10;

By: Amit Kumar Agrawal 147

The Smartest Way to Learn Java5

public void dispb() { System.out.println("Amit Kumar Agrawal"); System.out.println("Class B"); System.out.println("M = "+m); }}

c:\jdk1.5.0\bin\p1>javac B.javac:\jdk1.5.0\bin\p1>cd..c:\jdk1.5.0\bin>edit Amt043.java

// program to show the use of package

import p1.A;import p2.B;class Amt043{ public static void main(String args[]) { A obj1=new A(); B obj2=new B(); obj1.displayA(); obj2.dispb(); }}

Alt+F+Xc:\jdk1.5.0\bin>javac Amt038.javac:\jdk1.5.0\bin>java Amt038

Sub classing and imported class: -

Program :

c:\jdk1.5.0\bin\p1>edit A.java

// program to show the use of subclassing.

import p2.B;class C extends B{ int n=101; void display() { System.out.println("Class C"); System.out.println("\nAmit Kumar Singhal.\n");

By: Amit Kumar Agrawal 148

The Smartest Way to Learn Java5

System.out.println("M= "+m); System.out.println("N= "+n); }}class Amt059{ public static void main(String args[]) { C obj3=new C(); obj3.dispb(); obj3.display(); }}

c:\jdk1.5.0\bin\p1>javac Amt059.javac:\jdk1.5.0\bin\p1>java Amt059

Adding of class to a package:

Format of the class adding to a package.

package package_name;class class_name{ body of the class;}

Since a Java source file can have only one class declare as public we cannot put two or more classes declare as public in a .java file.

Hiding class:

When we import a package using '*' only one public classes are imported.

We may hide same classes to access from outside the package without

declaring it as public.

e.g.:

package package_name;{ public class class_name// this is public class name. { .........; }

By: Amit Kumar Agrawal 149

The Smartest Way to Learn Java5

class class_name// this is hided class. { .......; }}Setting CLASSPATH:

Whether we have used a build-in class, an import with a class name, an import statement with an asterisk symbol, or a fully qualified name in your code, this the instruction to the compiler to know the which package(s) contain the class. But where will it look for the package? That answer is determined by the environment variable named CLASSPATH.

How to set CLASSPATH.

CLASSPATH contains the list of places where you store the class libraries. We should follow the specific instructions, which Sun provides with your version of the SDK. In general, on a Windows machine, you set CLASSPATH by using the System control panel – choose start, select settings, choose control panel, double click the System control panel, and then choose the Environment tab. As shown in following figure shows the current CLASSPATH on my machine.

javac –classpath <complete path> <java_file_name.java>java –classpath <complete path> <class_file_name>

By: Amit Kumar Agrawal 150

The Smartest Way to Learn Java5

If you are a UNIX user, you can set environment variables in your startup file. The name of your startup file depends on which command interpreter (called a shell)

If you use the Bourne shell, put CLASSPATH=value; export CLASSPATH Into your profile file in your home directory. If you are a shell user, put Setenv CLASSPATH value Into the. Login file in your home directory.

If you are Macintosh user, it does not have environment variable. Instead, the Macintosh version of the SDK is smart enough to find the default classes, and will look in the current directory for other classes. Use the preferences dialog box in the Java compiler to specify other directories to the search pat.

How the compiler know about the search the CLASSPATH:

By: Amit Kumar Agrawal 151

The Smartest Way to Learn Java5

By default, the Java run-time system looks in the current directory as its stating point. Thus, our specified package is found in the current directory or a subdirectory of the current directory, it will be found. User can also specify its own path or paths by setting CLASSPATH environmental variable.

package AmitPackage;

Access protection:

It deals with the Java's access control mechanism and its access specifiers. For example, we already know that, access to a private member of a class, it granted only to access the same to the other member of the class not to the outside. Packages add another dimension to access control mechanism of the same language, as we know, Java provides many levels of protection to allow fine-grained control over visibility mode of the variables, methods within classes, sub-classes, and packages.Classes and packages both means of the encapsulating and containing the name

space and scope of variables and methods. Packages act as containers for the

classes and other sub-ordinate packages. Classes' act as container for data and code.

Java addresses four categories of visibility for class members:

Sub-classes in the same package. Non-subclasses in the same package. Sub-classes indifferent packages. Classes that are neither in the same package nor in the sub-classes.

A table to show the access of member of the classes:

By: Amit Kumar Agrawal 152

Private No-modifier Protected Public

Same class Yes Yes Yes YesSame package No Yes Yes YesSub-classSame package No Yes Yes YesNon subclassDifferent No No Yes YesPackageSub-classDifferent No No No YesPackageNon-subclass

The Smartest Way to Learn Java5

Program :

This is the program to show the use of an access control mechanism.

c:\jdk1.5.0\bin>cd p1c:\jdk1.5.0\bin\p1>edit AmitAccess.java

// program to show the use of access control mechanism of Java

package p1;

public class AmitAccess{ int n=1; private String nm="Amit"; protected String nm1="Singhal"; public String nm2="CrownEagle"; public AmitAccess()// base constructer { System.out.println("Displaying the contain of the class AmitAccess"); System.out.println("\nThe no. "+n+" Company in India"); System.out.println("\n\n"+"Company Name : "+nm2); System.out.println("\nName of the owner : "+nm+" "+nm1); }}

Alt+f+xc:\jdk1.5.0\bin\p1>javac AmitAccess.javac:\jdk1.5.0\bin\p1>cd..c:\jdk1.5.0\bin>edit Amt060.java

/* program to show the use of cntrol mechanism of Java*/

import p1.AmitAccess;class Amt060{ public static class ExcuseMe extends AmitAccess { ExcuseMe()

By: Amit Kumar Agrawal 153

The Smartest Way to Learn Java5

{ System.out.println("This is to implement use of AmitAccess inside another class"); System.out.println("\nNow see the print out the value of the AmitAccess class variable"); //System.out.println("The value of n = "+n); //System.out.println("The value of nm = "+nm); System.out.println("The value of nm1 = "+nm1); System.out.println("The value of nm2 = "+nm2); }} public static void main(String args[]) { AmitAccess Am1=new AmitAccess(); ExcuseMe Em= new ExcuseMe(); System.out.println("This is the all execution of Amt060"); }}

Alt+f+xc:\jdk1.5.0\bin>javac Amt060.javac:\jdk1.5.0\bin>java Amt060

In the above program I implement access control mechanism of the Java and as there are some error shown, while running of the program, I just use one line statement delaminate symbol provide by the Java "\\" so the above program have to check by eliminating these symbols from the program and test the access control mechanism provide by the Java.

Creating User Defined Sub-package in Java:

This is very important concept in Java. It is a package within another package. It is mainly used to compress the size of package. We can store same type of classes and use the same in all over the program development and Software preparation. By using this feature, we can also read the program very easily. It is also easy to understand the concept or the logic of the programmer.

By: Amit Kumar Agrawal 154

The Smartest Way to Learn Java5

Program :

Program to show the use of sub-package in Java.

c:\jdk1.5.0\bin\p1>md Tp1c:\jdk1.5.0\bin\p1>cd Tp1c:\jdk1.5.0\bin\p1\Tp1>edit Test.java

package p1.Tp1;

public class Test{ String nm1="Amit Agrawal's Sub-package test"; String nm2="Amit Singhal's sub-package closing now"; public Test() { System.out.println("\nNow We Didsplay The contain Of the SubPackage\n\n"); System.out.println(nm1); System.out.println(nm2); }}Alt+f+x

By: Amit Kumar Agrawal 155

The Smartest Way to Learn Java5

c:\jdk1.5.0\bin\p1\Tp1>javac Test.javac:\jdk1.5.0\bin\p1\Tp1>cd..c:\jdk1.5.0\bin\p1>cd..c:\jdk1.5.0\bin>edit Amt061.java

//program to show the use of sub-package in Java.import p1.Tp1.Test;import p1.AmitAccess;class Amt061{ public static void main(String args[]) { AmitAccess Am1=new AmitAccess(); Test TT=new Test(); }}

Program :

Program to show the use sub-package in real world problem.

c:\jdk1.5.0\bin>md mathc:\jdk1.5.0\bin>cd mathc:\jdk1.5.0\bin\math>edit AmMath.java

/* package of amit's math calculation */

package math;

public class AmMath{ public AmMath(){ System.out.println("Amit Kumar Agrawal's Math package"); }}Alt+f+xc:\jdk1.5.0\bin\math>javac AmMath.javac:\jdk1.5.0\bin\math>md Calcc:\jdk1.5.0\bin\math>cd Calcc:\jdk1.5.0\bin\math\Calc>edit Calculate.java/* sub package declared by Amit for Calculation*/package math.Calc;

public class Calculate{ public Calculate(){ System.out.println("This is the Sub package classes for mathemtical calculation"); }

By: Amit Kumar Agrawal 156

The Smartest Way to Learn Java5

public int add(int x, int y){ return(x+y); } public int sub(int x, int y){ return(x-y); } public int mul(int x, int y){ return(x*y); }}

Alt+f+xc:\jdk1.5.0\bin\math\Calc>javac Calculate.javac:\jdk1.5.0\bin\math\Calc>cd..c:\jdk1.5.0\bin\math>cd..c:\jdk1.5.0\bin>edit Amt062.java

/* program to show the use of sub-package in realworld sence*/

import math.Calc.Calculate;import math.AmMath;class Amt062{ public static void main(String args[]) { int add,mul,sub; AmMath ac=new AmMath(); Calculate cl1=new Calculate(); add=cl1.add(5,6); sub=cl1.sub(10,5); mul=cl1.mul(2,8); System.out.println("\n\nAddition of 5,6 is :"+add); System.out.println("Substraction of 10 from 5 is :"+sub); System.out.println("Multiplication of 2,8 is :"+mul); }}

Alt+f+xc:\jdk1.5.0\bin>javac Amt062.javac:\jdk1.5.0\bin>java Amt062.java

Program :

Program to show the use sub-package in real world problem by inputting the value from keyboard.

By: Amit Kumar Agrawal 157

The Smartest Way to Learn Java5

c:\jdk1.5.0\bin>edit Amt063.java

/* program to show the use of sub-package in realworld sence*/

import math.Calc.Calculate;import math.AmMath;import java.io.DataInputStream;

class Amt063{ public static void main(String args[]) { int a,b,add,mul,sub; AmMath ac=new AmMath(); Calculate cl1=new Calculate(); DataInputStream in=new DataInputStream(System.in); a=b=0; try { System.out.print("\nEnter the value of a in integer form : "); a=Integer.parseInt(in.readLine()); System.out.print("Enter the value of b in integer form : "); b=Integer.parseInt(in.readLine()); } catch (Exception e) {} add=cl1.add(a,b); sub=cl1.sub(a,b); mul=cl1.mul(a,b); System.out.println("\n\nAddition of "+a+","+b+" is :"+add); System.out.println("Substraction of "+a+" from "+b+" is :"+sub); System.out.println("Multiplication of "+a+","+b+" is :"+mul); }}

Alt+f+xc:\jdk1.5.0\bin>javac Amt063.javac:\jdk1.5.0\bin>java Amt063.java

Thread:

In order to explain threads, we need to back up and explain processes. In a modern operating system (Windows NT, Windows XP, UNIX etc), the computer may have a single processor but will be doing many things at once. These OS are said to be

By: Amit Kumar Agrawal 158

The Smartest Way to Learn Java5

Multiprocessing because there are many separate activities going on at once, all shares a single processor. The figure given below will explain you about the above concept how a single processor is used by many programs

By: Amit Kumar Agrawal 159

Get a list of processes on your Operating System:

The process list in the figure is from the Windows XP Task Manager. You can get this by pressing "Alt+Ctrl+Del" then choose Task manager and then select the process tab. In UNIX machine you have to type "ps –ef "at the command prompt if you are in UNIX operating System.

Figure to show the performance of the CPU while no. of program run at a time.

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 160

How many Threads can Your Computer Support?

Although the starting of a thread is "lightweight" when compared to a process,

there is still (in most computers) only one processor to go around. If we load

up our program by too many threads, the performance will suffer. Keep an eye

on your overall system, as shown in figure given on the above of this box. If

CPU or memory usage regularly goes above 50%, consider taking adding

resources or removing some of the load. This can be achieved by pressing the

performance tab of the task manager of the Windows NT\XP\... .

The Smartest Way to Learn Java5

Single threaded and Multi threaded:

Multi threaded:

It is a programming concept where a program is divided into two or more subprogram, which can be implemented simultaneously in parallel.

Thread is a program having single flow control. It has a beginning a body and an end and executes the command

sequentially. A program containing multiple thread of control is called as multi threaded program.

Single threaded:

class ABC{

..........}

Multi threading:

By: Amit Kumar Agrawal 161

The Smartest Way to Learn Java5

Here the main method is the main thread control, which is design to create

and start other three thread namely A, B, and C, one initiated by main

thread the threads A, B, and C can run concurrently and share the resources

jointly.

Since threads in Java are Subprogram of main application program and

share the same memory space, they are known as lightweight process.

Threads running in parallel do not mean that they actually run at the same

time. But Java interpreter handles the Switching of control between threads

in such a way that, it appears they are running concurrently.

Creating Threads:

Threads are implemented in the form of object, that contains a method

called run ().

The run method can implement by an object of the concern thread.

This can be achieved by creating the threads and initiating it with the help

of another help method start ().

A new thread can be created by two ways.

By creating a thread class. By converting a class to a thread.

By creating a thread:

By: Amit Kumar Agrawal 162

The Smartest Way to Learn Java5

Here we defined a class that extends thread class and override run () with the code required by the thread.

By converting a class to a thread:

Here we define a class that implement runnable interface has only one method run () that is to defined in the method that with the code to be executed by the thread.

Extending the thread class:

We can make our class runnable as a thread by extending the class thread to the define class.

import java.lang.Thread;Class C extends Thread{ ……..;}

Steps on extending thread class:

Class is declared to extend the Thread class. run() is implemented which is responsible for executing the sequence of

code that Thread will execute. Public void run () { ................. ................. .................// Thread code }

Starting new Thread:

A thread object is created and start method is called to initiate the Thread execution. C Thread1=new C (); Thread1.start();

By: Amit Kumar Agrawal 163

The Smartest Way to Learn Java5

Program :

This is the program to demonstrate the use of Thread class

c:\jdk1.5.0\bin>edit Amt064.java

// program to show the use of Thread Test By Amit Agrawalimport java.lang.Thread;

class A extends Thread{ public void run(){ for(int i=1;i<=25;i++) { System.out.println("From class A: "+i); } System.out.println("Amit Ending the class A"); }}class B extends Thread{ public void run() { for(int j=1;j<=25;j++) { System.out.println("From class B: "+j); } System.out.println("Amit Ending the class B");}}class C extends Thread{ public void run() { for(int z=1;z<=25;z++) { System.out.println("From class C: "+z); } System.out.println("Amit Ending the class C"); }}

class Amt064{ public static void main(String args[]) { A obj1=new A(); B obj2=new B(); C obj3=new C();

By: Amit Kumar Agrawal 164

The Smartest Way to Learn Java5

System.out.println("Now Amit start execution of the Thread\n\n\n"); obj1.start(); obj2.start(); obj3.start(); }}

Alt+f+x

c:\jdk1.5.0\bin>javac Amt064.java

c:\jdk1.5.0\bin>java Amt064

Stopping and blocking a Thread:

We can stop a Thread by calling stop ().

stop () causes the Thread to move to died state.

Blocking:

We can temporarily blocking a Thread from entering into runnable and

running state they using three methods.

sleep ();

suspend ()

wait ()

Sleep blocks the Thread for a specified time.

Suspend blocks the Thread for until further order.

resume () is used to reactivate the suspend block.

Wait block the statement when certain condition occurs.

notify () is used to reactivate the wait block.

By: Amit Kumar Agrawal 165

Method Delaminating Method

sleep () *suspend () resume ()wait () notify ()

The Smartest Way to Learn Java5

The above table sows the different methods for blocking the Thread execution and

the corresponding reverse function to reactivate the Thread execution.

State transaction diagram of Thread:

By: Amit Kumar Agrawal 166

Idle Thread

The Smartest Way to Learn Java5

The life cycle of Thread consist of five stage:

Newborn.

Runnable.

Running.

Blocked.

Died.

Newborn state:

When we create a Thread, object a Thread is born and it is new born state. In this state Thread is not yet schedule for running. At this state Thread can be schedule for running by using start (). Any other method causes Exception.

Runnable state:

Thread is ready for execution and waiting for availability of processor in

this state.

Time slicing is the process of assigning time to the Thread in ready-queue

in round robin fashion.

yield () method is used to shift the control to another Thread of equal

priority.

Running state:

Here processor has been assign to the Thread for execution. The Thread run until it shift control to another Thread of pre Amted by a

higher priority Thread.

By: Amit Kumar Agrawal 167

The Smartest Way to Learn Java5

Blocked state:

When a Thread is prevented to enter into running and runnable sate, it is said to be block.

A block Thread neither runnable nor died. Hence, block Thread can be fully qualified to run again by using resume () and notify ().

Died state:

A running Thread ends its life when it is completed executing the run method, which is called natural death.

We can kill a Thread by sending stop() method at any stage causing premature death.

Program :

Program to show the use of blocking statement

c:\jdk1.5.0\bin>edit Amt065.java

// program to show the use of Thread Test By Amit Agrawalimport java.lang.Thread;

class A extends Thread{ public void run() { for(int i=1;i<=5;i++) { if(i==1) yield(); System.out.println("From class A: "+i); } System.out.println("Amit Ending the class A"); }}class B extends Thread{ public void run() { for(int j=1;j<=5;j++){ if(j==4)

By: Amit Kumar Agrawal 168

The Smartest Way to Learn Java5

stop(); System.out.println("From class B: "+j); } System.out.println("Amit Ending the class B"); }}class C extends Thread{ public void run(){ for(int z=1;z<=5;z++) { System.out.println("From class C: "+z); if(z==2) { try { sleep(10); } catch (Exception e) {}}} System.out.println("Amit Ending the class C"); }}

class Amt065{ public static void main(String args[]) { A obj1=new A(); B obj2=new B(); C obj3=new C(); System.out.println("Now Amit start execution of the Thread\n\n\n"); obj1.start(); obj2.start(); obj3.start(); }}

Alt+f+xc:\jdk1.5.0\bin>javac Amt065.javac:\jdk1.5.0\bin>java Amt065.java

Thread exception:

By: Amit Kumar Agrawal 169

The Smartest Way to Learn Java5

The sleep method will throw an exception, which should be caught if we are

invoking a resume ()/ notify () methods because, a sleeping Thread cannot

receive any instruction.

Java run time system will throw illegal Thread state exception whenever

we attempt to invoke a method that a Thread cannot handle in given state.

Forms of catch statement:

catch(threadDeath e) { .........//killed Thread code }

catch(InteruptedException e) { .......// cannot handle it in current state }

catch(IllegalArgumentException e) { ........//code for illegal method agent ........ ........ }

catch(Exception e) {

.......// Any other illegal option ....... ....... }

Thread priority:

By: Amit Kumar Agrawal 170

The Smartest Way to Learn Java5

In Java, each Thread is assigned a priority, which affect the order in which it is schedule for running.

The Thread of same priority is given equal statement by scheduler and they will be allowed to get the CPU in FCFS (First Come First Serve) basis.

Java permits the user to get the priority of the Thread by using setpriority method.

Thread object_name.Setpriority (n)(1 – 10) Thread class define several priority constant. MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 Most user level process should use NORM_PRIORITY 1 Background task such as IO and screen process should use a value very

near to Lower limit.

Program :

Program to show the use of priority setup to Thread.

// program to show the use of Thread priority Test By Amit Agrawalimport java.lang.Thread;

class A extends Thread{ public void run(){ System.out.println("Amit Start's the Execution of Thread A"); for(int i=1;i<=25;i++){ System.out.println("From class A: "+i); } System.out.println("Amit Ending the class A"); }}class B extends Thread{ public void run() { System.out.println("Amit Start's the Execution of Thread B"); for(int j=1;j<=25;j++) { System.out.println("From class B: "+j); } System.out.println("Amit Ending the class B"); }}class C extends Thread

By: Amit Kumar Agrawal 171

//code to synchronized.}

The Smartest Way to Learn Java5

{ public void run() { System.out.println("Amit Start's the Execution of Thread C"); for(int z=1;z<=25;z++) { System.out.println("From class C: "+z); } System.out.println("Amit Ending the class C"); }}

class Amt066{ public static void main(String args[]) { A obj1=new A(); B obj2=new B(); C obj3=new C(); obj3.setPriority(10); obj2.setPriority(6); obj1.setPriority(5); System.out.println("Now Amit start execution of the Thread\n\n\n"); obj1.start(); obj2.start(); obj3.start(); }}

Synchronization of Thread:

Problem occurs when are Thread may try to read a record from a file while

another is still writing to the file. Java enables to solve this problem by

using a technique called Synchronization.

The method that will read information from a file and the method that will

write to the same file may be declared as synchronized.

Synchronized void Method_name()

{

........

By: Amit Kumar Agrawal 172

The Smartest Way to Learn Java5

........

........

}

When we declared a method-synchronized Java creates a monitor and hands

it over to the Thread that calls the method first time. As a Thread holds the

monitor no other, Thread can enter the synchronized section of code.

A monitor is like a key and Thread that holds the monitor can open the

lock.

By: Amit Kumar Agrawal 173

Need of Synchronization:

When two Threads fight over one object – in this case, a collision of data occurs. Let us take the example of a nuclear reactor. One pulls the control rods out – the other one gradually slide the rod in. as long as both work get about the same amount of time, the rods will stay in one position. If they are pushed in too far, the reactor shuts down and million of people go without electricity. If the rods are pulled too far out, the reactor overheats and goes into meltdown.

Synchronization:

If we want, two threads to communicate and share a complicated data structure, such as a linked list, we need some way to ensure that they do not conflict or in other words, they do not collide with each other. That is, we must prevent one thread from writing data while another thread is in the middle of reading it. For this purpose, Java provide an elegant twist on an age-old model of inter process called Synchronization.

The Smartest Way to Learn Java5

Program :

Program to show the data collision .

c:\jdk1.5.0\bin>edit Amt067.java

import java.awt.*;import java.applet.*;

public class Amt067 extends Applet{ java.awt.Panel buttonpanel; java.awt.Button Startbutton; java.awt.Panel mainpanel; java.awt.TextArea textarea; static final boolean KIn=true; static final boolean KOut=false; void started(java.awt.event.ActionEvent e) { TrodThread inThread=new TrodThread(KIn, textarea); inThread.setPriority(Thread.NORM_PRIORITY); inThread.start(); TrodThread outThread=new TrodThread(KOut, textarea); outThread.setPriority(Thread.NORM_PRIORITY); outThread.start();

Startbutton.setEnabled(false); } public void init(){ super.init(); buttonpanel=new java.awt.Panel(); buttonpanel.setBounds(0,240,426,21); add(buttonpanel); Startbutton=new java.awt.Button("Amit Start"); buttonpanel.add(Startbutton); mainpanel=new java.awt.Panel(); add(mainpanel); textarea=new java.awt.TextArea(); mainpanel.add(textarea); Startbutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e)

By: Amit Kumar Agrawal 174

The Smartest Way to Learn Java5

{ started(e); } });}}

class TrodThread extends Thread{ static short position=10; boolean direction; static TextArea textarea; short usecount=0; TrodThread(boolean thedirection,TextArea thetextarea){ if(textarea==null) textarea=thetextarea; direction=thedirection; } public void run() { String theDirectionString=direction?"In":"Out"; while(position>0 && position<20 && usecount<1000) { if(direction) position++; else position--; usecount++; textarea.setText(String.valueOf(usecount)+" : "+String.valueOf(position)+"\n"); } textarea.appendText("Amit Say's The Final Position= "+String.valueOf(position)+ "\n"); textarea.appendText("Moved " +theDirectionString+ " " +String.valueOf(usecount)+" times\n"); textarea.appendText("Amit Ends The Amit Collision Program\n"); }}

Alt+f+xc:\jdk1.5.0\bin>javac Amt067.javac:\jdk1.5.0\bin>edit Amt067.htm

<html><applet CODE=Amt067.class width=600 height=470></applet></html>

Alt+f+x

By: Amit Kumar Agrawal 175

The Smartest Way to Learn Java5

run the htm file by doubleclick on the icon of the Amt067.htm file in the "c" drive, "jdk1.5.0" directory, "bin" directory from the My Computer.

The output of the above program

17 : 20Amit Say's The Final Position= 20Moved In 17 timesAmit Ends The Amit Collision ProgramAmit Say's The Final Position= 20Moved Out 7 timesAmit Ends The Amit Collision Program

In the given program I designed to simulate a nuclear reactor, here on Thread is

gradually pulls the control rod and the other one is gradually slide it in. but it

causes a collision between data as we can see in the result the proportion of In and

Out is not same.

How to protect your entire Methods:

As we work through our Threads looking for critical sections, we need to ask our

self two questions – how big is the critical section and what is the shared resource.

Place the curly braces of the synchronized statement around the critical section, and

place the name of the shared resource object inside the parentheses of the

synchronized statement.

If we find that the critical section is equivalent to an entire method, and the shared

resource is the entire object, we can simply synchronized the method.

Format:

Synchronized void method_name(){ ............}

By: Amit Kumar Agrawal 176

The Smartest Way to Learn Java5

this code is equivalent to the following Format:

void method_name(){ synchronized (this) { ........... }}

Program :

Program to show the use of synchronized method in the program 64.

c:\jdk1.5.0\bin>edit Amt068.java

import java.awt.*;import java.applet.*;

public class Amt068 extends Applet{ java.awt.Panel buttonpanel; java.awt.Button Startbutton; java.awt.Panel mainpanel; java.awt.TextArea textarea; static final boolean KIn=true; static final boolean KOut=false; void started(java.awt.event.ActionEvent e) { TrodThread inThread=new TrodThread(KIn, textarea); inThread.setPriority(Thread.NORM_PRIORITY); inThread.start(); TrodThread outThread=new TrodThread(KOut, textarea); outThread.setPriority(Thread.NORM_PRIORITY); outThread.start();

Startbutton.setEnabled(false); } public void init() { super.init(); buttonpanel=new java.awt.Panel(); buttonpanel.setBounds(0,240,426,21); add(buttonpanel);

By: Amit Kumar Agrawal 177

The Smartest Way to Learn Java5

Startbutton=new java.awt.Button("Amit Start"); buttonpanel.add(Startbutton); mainpanel=new java.awt.Panel(); add(mainpanel); textarea=new java.awt.TextArea(); mainpanel.add(textarea); Startbutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { started(e); }});}}

class TrodThread extends Thread{ static short position=10; boolean direction; static TextArea textarea; short usecount=0; TrodThread(boolean thedirection,TextArea thetextarea) { if(textarea==null) textarea=thetextarea; direction=thedirection; } public void run() { String theDirectionString=direction?"In":"Out"; while(position>0 && position<20 && usecount<1000) { if(direction) position++; else position--; usecount++; textarea.setText(String.valueOf(usecount)+" : "+String.valueOf(position)+"\n"); } synchronized(textarea) { textarea.appendText("Amit Say's The Final Position= "+String.valueOf(position)+ "\n"); textarea.appendText("Moved " +theDirectionString+ " " +String.valueOf(usecount)+" times\n"); textarea.appendText("Amit Ends The Amit Collision Program\n"); }}}

By: Amit Kumar Agrawal 178

The Smartest Way to Learn Java5

Alt+f+xc:\jdk1.5.0\bin>edit Amt068.htm

<html><applet CODE=Amt068.class width=600 height=470 ></applet></html>

Alt+f+x

run the htm file by doubleclick on the icon of the Amt067.htm file in the "c" drive, "jdk1.5.0" directory, "bin" directory from the My Computer.

The output of the above program

20 : 20Amit Say's The Final Position= 20Moved In 20 timesAmit Ends The Amit Collision ProgramAmit Say's The Final Position= 20Moved Out 10 timesAmit Ends The Amit Collision Program

In the above program I designed to simulate a nuclear reactor, here on Thread is

gradually pulls the control rod and the other one is gradually slide it in. It does not

causes a collision between data as we can see in the result the proportion of In and

Out is same.

Implementing runnable interface:

Step:

Class is declared to implement runnable interface.

By: Amit Kumar Agrawal 179

The Smartest Way to Learn Java5

Run method is implemented.

A Thread is created by defining an object that is instantiated from runnable

class.

Start method will be invoked to run the Thread.

Program :

Program to show the use of Runnable interface.

/* program to implement runnable class*/

class XX implements Runnable{ public void run() { for(int i=1;i<=5;i++) { System.out.println("Amit say's From Thread XX i= " +i); } System.out.println("Amit Ends The Thread 'XX' Execution"); }}class Amt069{ public static void main(String args[]) { XX runn=new XX(); Thread THXX=new Thread(runn); THXX.start(); System.out.println("Ending the main Thread Excution"); }}

Daemon Thread

The Thread API allows Threads to be created which are at the mercy of their user threads. This is accomplished simply by passing true to the setDaemon() method and invoking the method off an instance of the thread wishing to set it's status.

By: Amit Kumar Agrawal 180

The Smartest Way to Learn Java5

Code:

public void setDeamon(boolean b)

Program to show the use of Daemon Thread

public class UserThread{ public static void main(String[] args){ Thread t = new Thread(new DaemonThread(525.00f, 0.09f)); t.setDaemon(true); t.start(); try{ Thread.sleep(250); // must give the deamon thread a chance to run! }catch(InterruptedException ei){ // 250 mills might not be enough! System.err.println(ei); } }}class DaemonThread implements Runnable{ private float principal; private float futureval; private float rate; private float i; public DaemonThread(float principal, float rate){ this.principal= principal; this.rate = rate; }

public void run(){ for(int year = 0; year <= 75; year++){ i = (1 + rate); futureval = principal * (float)Math.pow(i,year);System.out.print(principal + " compounded after " + year + " years @ " + rate + "% = " + futureval); System.out.println(); }}}

We mentioned that a Java program exits when all of its threads have completed, but

this is not exactly correct. What about the hidden system threads, such as the

By: Amit Kumar Agrawal 181

The Smartest Way to Learn Java5

garbage collection thread and others created by the JVM? We have no way of

stopping these. If those threads are running, how does any Java program ever exit?

These system threads are called daemon threads. A Java program actually exits

when all its non-daemon threads have completed. Any thread can become a

daemon thread. By calling the Thread.setDaemon() method You can indicate a

thread is a daemon thread. You might want to use daemon threads for background

threads that you create in your programs, such as timer threads or other

deferred event threads, which are only useful while there are other non-daemon

threads running.

Who creates threads?

Even if you never explicitly create a new thread, you may find yourself working

with threads anyway. Threads are introduced into our programs from a variety of

sources. There are a number of facilities and tools that create threads for you, and

you should understand how threads interact and how to prevent threads from

getting in the way of each other if you're going to use these facilities.

What about deadlock:

The longer we work with concurrent systems, the more bizarre occurrences we will

see. Many of these mishaps occur because of a phenomenon known as deadlock,

which is usually illustrated by something called the Dining Programmer problem.

Suppose that a group of Programmers has a dinner table set as shown in following

figure. There is one chopstick between each plate. If two adjacent Programmer

attempt to eat at the same time, they collide on the shared chopstick and neither is

able to eat.

By: Amit Kumar Agrawal 182

The Smartest Way to Learn Java5

Programmers have only two states- eating and programming. Suppose that the table is empty. A Programmer moves into position A, seizes the two sticks on either size of his plate, and begins to dine. Sometime later, a second Programmer arrives and takes position C. He/She has two chopsticks, so he/she can eat. In addition, a third Programmer moves into position B. This person have to wait until first two person are not finishes there eating.What happens if a Programmer moves into position E, and a moment later, another programmer sits down at position F? The programmer at position E can eat, but the one at position F seizes the one chopstick available and holds onto it. Now another diner joins the table at position D. He, too, unable to eat, since the chopstick between D and E is in use by the Programmer at position E. As soon as the diner at C leaves, the diner at position D seizes the chopstick ha shared with B.As time goes on, you may eventually get to the point where every position at the table is filled, and each programmer holds one chopstick. Unless someone is willing to give up his or her chopstick, no other can eat. The table is said to be deadlocked.

By: Amit Kumar Agrawal 183

Deadlock is also known as "The Deadly Embrace"

Sometimes we will find deadlock referred to in computer science literature as "The deadly embrace." It is the same phenomenon, but with a more colorful name.

The Smartest Way to Learn Java5

Deadlock is special type of error we need to avoid the same, it relates specially with multitasking. It occurs when two Thread have circular dependency on a pair of synchronized objects. As the above example shows.

It is a rarely concept, when the two Threads time-slice in just the right way. It may also involve two or more than two synchronized objects.

Program :

Program to show a deadlock execution.

// an example to show the deadlock occurance.class Amit{ synchronized void Crown(Singhal singhal) { String name=Thread.currentThread().getName(); System.out.println(name+"entered in Amit Crown"); try{ Thread.sleep(5); }catch(Exception e){ System.out.println("Amit is Interrupted"); } System.out.println("Amit is trying to Singhal.last()"); singhal.last();} synchronized void last(){ System.out.println("Inside Amit.last"); System.out.println("Exiting from the Amit.last"); }}class Singhal{ synchronized void Eagle(Amit amit) { String name=Thread.currentThread().getName(); System.out.println(name+" Entered in to the Singhal class"); try { Thread.sleep(5); }catch(Exception e) { System.out.println("Singhal Interrupted");

By: Amit Kumar Agrawal 184

The Smartest Way to Learn Java5

} System.out.println(name+" trying to call Amit.last"); amit.last();} synchronized void last() { System.out.println("Inside the Singhal.last()"); System.out.println("Exiting from the Singhal.last()"); }}class Amt070 implements Runnable{ Amit amit=new Amit(); Singhal singhal=new Singhal(); Amt070() { Thread.currentThread().setName("Amit's MainThread"); Thread t=new Thread(this,"Rambo Thread for Racing"); t.start(); amit.Crown(singhal); System.out.println("Back to the Amit's MainThread Now"); } public void run() { singhal.Eagle(amit); System.out.println("Back in other Thread"); } public static void main(String args[]) { new Amt070(); }}

Result:

Amit's main Threadentered in Amit CrownRambo Thread for Racing entered in to the Singhal classAmit is trying to Singhal.last()Rambo Thread for Racing trying to call Amit.last()

When we run the above program it produces the above result and has deadlocked, we need to press Ctrl+c to end the program.

Thread support the following methods:

activeCount() – Return the current number of the active threads in this thread group.

By: Amit Kumar Agrawal 185

The Smartest Way to Learn Java5

checkAccess() – Checks with the current securityManager to determine if the current thread has permission to modify this thread.

countStackFrames() – Count the depth of the stack, as measured in stack frames.

currentThread() – Returns a reference to the currently executing thread. destroy() – Causes the Thread to immediately exit, with no opportunity for

cleanup. dumpStack() – Prints a stack trace of the currently executing Thread. enumerate() – Prepares an array of Threads consisting of a copy of every

active Thread in this ThreadGroup and its subgroups. getClassLoader() – Returns the context ClassLoader for this Thread. getName() – Returns the Thread name. getPriority() – Returns the Thread's priority. By default, every thread has

the priority of the thread started it. A thread can change its priority by calling setPriority().

getThreadGroup() – Returns a reference to this Threads ThreadGroup. interrupt() – Interrupts the specified thread. inturrupted() – Tests to see if the current Thread has been interrupted() is a

static method; compare it with isInterrupted(); isAlive() – Returns true if the specified Thread is still alive. A Thread

becomes alive when its start() method is called, and remains alive until it dies.

isDaemon() – Returns true if the specified Thread is a daemon Thread. A thread is a daemon thread if it is design to run in the background independent of any user interface. When all user interface Threads have exited and the only Threads running are said to be daemons the JVM exits.

isInterrupted() – Returns true if this Thread has been interrupted; compare it with interrupted(), which is static.

join() – Merges two Threads by writing for another Thread to die. You can optionally limit the wait to a specified period of time.

run() – Begins to execute the Thread's target Runnable object, if any. setClassLoader() – Specifies a context ClassLoader for the Thread. setDaemon() – Marks the Thread either as a daemon Thread or as a user

Thread, depending upon the parameter. setName() – Changes the name of the Thread. setPriority() – Checks to make sure the Thread has permission to modify

its own priority. If it does, it sets the priority a requested. Note that in no case will setPriority() set the priority to a value greater than that permitted for the thread s ThreadGroup. Priority generally expressed in symbolic

By: Amit Kumar Agrawal 186

The Smartest Way to Learn Java5

constants like: MAX_PRIORITY, MIN_PRIORITY, and NORM_PRIORITY.

sleep() – Causes for current Thread to yield the processor and temporarily stop running for specified time.

start() – Calls for this thread to begin execution – the JVM calls the Threads run() method.

toString() – Returns a string representation of the thread with its name, priority, and ThreadGroup.

yield() – Causes the current Thread to yield the processor; the scheduler will allow other Threads to run.

Exception handling:

Errors are mistake committed in a program that may produce in-correct output or may terminate the execution of the program abruptly or even may cause the system to crash.

Types of errors:

Compile time error. Run time error.

Compile time error:

Syntax errors displayed by javac (compiler), during compilation are compile time error.

Javac will not create the .class, if compile time error will occurs e.g.: Typographical error.

Common compile time errors:

Missing semicolon (;). Mismatching bracket. Misspelled keywords. Missing double core in String. Undeclared variable. Incompatible type assignment. Bad reference to object. Use of invalid directory path.

By: Amit Kumar Agrawal 187

The Smartest Way to Learn Java5

Run time error:

Program may produce wrong result due to wrong logic or it may terminate during running the program by java interpreter.

Common Run time errors:

Dividing any numeric value with zero (0); Accessing the array element out of bound. Store incompatible type in an array. Cast instance of a class to its sub-class. Passing parameter not in a valid range. Use of (-)ve size of an array. Illegal change of state for Thread.

Exception:

It is a condition caused by runtime error in a program. When Java interpreter encounter an error it create an Exception object and

throw it. If exception object is not caught and handle properly, the interpreter will display error message and terminate the program execution.

Exception Handling:

It is the concept of catching the exception object shown by the error condition and this displaying the appropriate message for taking correct step.

Steps:

Fit the Exception. Throw the Exception. Catch the Exception. Take the corrective action.

Common Java Exception:

ArithmeticException. ArrayIndexOutOfBoundsException. ArrayStoreException.

By: Amit Kumar Agrawal 188

The Smartest Way to Learn Java5

ClassCastException. IllegalArgumentException. IllegalMonitorStateException. IllegalStateException. IllegalThreadStateException. IndexOutOfBoundsException. NegativeArraySizeException. NullPointerException. NumberFormatException. SecurityException. StringIndexOutOfBounds. UnsupportedOperationException. ClassNotFoundException. CloneNotSupportedException. IllegalAccessException. InstantiationException. InteruptedException. NoSuchFieldException. NoSuchMethodException. OutOfMemoryException.

Format:

By: Amit Kumar Agrawal 189

The Smartest Way to Learn Java5

If any statement generates exception, the remaining statement in the try block is skipped and exception is jumped to catch block.

Every try block must be followed by at least one catch block. Both try and catch block have more than one statement. Catch statement work like a method statement. Catch statement is passed a single parameter, which is reference to the

exception object thrown by try block. If catch parameter is matches with the type of exception object then

exception is caught and statement of catch block will be executed otherwise default exception handle will be executed otherwise default exception to terminate.

Use of Exception Handling to make a Bulletproof program:

By: Amit Kumar Agrawal 190

The Smartest Way to Learn Java5

There's a better way and designers of Java adopted. It is called exception handling. An exception is an event that occurs during the execution of a program and disrupts the normal flow of instruction. Implicit in that definition is the notion that there is a normal flow of instructions. The file-reading programs and other programs show such normal flow. The following procedure can help you learn to use exceptions.

Adding Exception Handling to your program:

1. Wrap the normal flow of instructions in a try block.

2. Note which errors can occur during the normal flow of instructions and

make sure each one throws an exception.

3. Catch and handle all exceptions in catch blocks.

Multiple catch:

We can use multiple catch statement after a try block, multiple catch works like a switch case block.

Use of finally statement:

It can be use to handle exception that is not caught by the any of the previous catch statement.This is guaranteed to execute regardless of whether an exception is throw or not.

try{

By: Amit Kumar Agrawal 191

One try block or many:

If you prefer, you can wrap each statement that might throw an exception in its own try block. I prefer to use a single try block for the entire method – I think it is easier to read. Some programmer prefers to switch back and forth, using the style that makers the most sense at the time.

The Smartest Way to Learn Java5

............;} catch(Exception_typ1 e){ ............;}catch(Exception_typ2 e){ ............;}.............finally{.............;}

Program :

Program to catching invalid arguments in command line.

C:\jdk1.5.0\bin>edit Amt071.java

/* program to show the use of exception handling for catching invalid no. of command line argument*/class Amt071{ public static void main(String args[]){ int invalid=0; int number,count=0;

{ for(int i=0;i<args.length;i++) { try { number=Integer.parseInt(args[i]); } catch(NumberFormatException e) { invalid++; System.out.println("Invalid no. is : "+args[i]); continue; } count++; }

By: Amit Kumar Agrawal 192

The Smartest Way to Learn Java5

} System.out.println("The no. of valid entry in the command line : "+count); System.out.println("The no. of Invalid entry in the command line : "+invalid); }}

Alt+f+xC:\jdk1.5.0\bin>javac Amt071.javaC:\jdk1.5.0\bin>java Amt071 1 2 3 4 5 amit lipi nami deepa 6 7

Result:Invalid no. is : amitInvalid no. is : lipiInvalid no. is : namiInvalid no. is : deepaThe no. of valid entry in the command line : 7The no. of Invalid entry in the command line : 4

Program :

Program to show the use of multiple exception handling.

C:\jdk1.5.0\bin>edit Amt072.java

/* program to show the use of multiple exception handling*/import java.lang.*;

class Amt072{ public static void main(String args[]){ int a[]={5,10},b=5; try{ int x=a[1]/(b-a[0]); } catch(ArithmeticException e) { System.out.println("Division by Zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Error in array index"); } finally { int y=a[1]/a[0]-b; System.out.println("The Value of y = " +y);

By: Amit Kumar Agrawal 193

The Smartest Way to Learn Java5

} }}

Alt+f+xC:\jdk1.5.0\bin>javac Amt072.javaC:\jdk1.5.0\bin>java Amt072

Result:Division by zeroThe value of y = -3

Program :

The above program to show the accepting the other error.

C:\jdk1.5.0\bin>edit Amt073.java

/* program to show the use of multiple exception handling*/import java.lang.*;

class Amt073{ public static void main(String args[]){ int a[]={5,10},b=5; try{ int x=a[2]/(b-a[0]); } catch(ArithmeticException e){ System.out.println("Division by Zero"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Error in array index"); } finally { int y=a[1]/a[0]-b; System.out.println("The Value of y = " +y); } }}

Alt+f+xc:\jdk1.5.0\bin>javac Amt073.javac:\jdk1.5.0\bin>java Amt073

Result:

By: Amit Kumar Agrawal 194

The Smartest Way to Learn Java5

Error in array indexThe value of y = -3

Throwing own Exception:

Programmer can create a class inherited from Exception class, throw the new class, and catch the Exception object when logical error occurs.

throw new class_name;

Program :

Program to show quickly implement some trivial user-defined exception.

//quikly implement some trival userdefined exceptions.class TImportantException extends Exception{}class TUnimportantException extends Exception{}public class Amt074{ protected void doImportantStuff() throws TImportantException { throw new TImportantException(); } protected void doUnimportantStuff() throws TUnimportantException { throw new TUnimportantException(); } public static void main(String args[]) throws TImportantException,TUnimportantException { Amt074 theDemo=new Amt074(); try{ theDemo.doImportantStuff(); }finally{ theDemo.doUnimportantStuff(); }}}

The output of the program is as followsResult:

Exception in Thread "main" TUnimportantException at Amt074.doUnimportantStuff(Amt074.java:12) at Amt074.main(Amt074.java:20)

By: Amit Kumar Agrawal 195

The Smartest Way to Learn Java5

What really happens in the above program?

When doImportantStuff() is called, it throws TImportantException. That exception is not caught inside main(). So control is about to leave main(). On the way out main()'s finally block is called. A new Exception is thrown inside the finally block. It is not caught, either. Now control passes outside main() (and, in this case, back to the runtime system), but the only exception visible is the TUnimportantException thrown in finally.You can ensure that this problem does not occur by catching all Exceptions inside the method (before finally can run) or by being careful that nothing we do in finally can throw an Exception.

Program :

Program to throw and catch own exception.

//program to show the use user defined exception

import java.lang.Exception;class AmtException extends Exception{ public String msg; AmtException(String ms) { msg=ms; }}class Amt075{ public static void main(String args[]){ float x=5,y=1000; try{ float z= x/ y; if(z<0.01){ throw new AmtException("no. is too small"); } } catch(AmtException e) { System.out.println("My Exception is caught"); System.out.println(e.msg); } finally { System.out.println("I am Here");

By: Amit Kumar Agrawal 196

The Smartest Way to Learn Java5

} }}

AWT:

AWT stands for Abstract Window Toolkit, AWT supports Graphical User Interface (GUI) programming. AWT features include:

A rich set of user interface components. (Button, CheckBoxes, Radio Button etc.)

A robust event-handling model. Graphics and imaging tools, including shape, color, and font classes.

(Java2D) Layout managers, for flexible window layouts that don't depend on a

particular window size or screen resolution; Data transfer classes, for cut-and-paste through the native platform

clipboard.

There is no doubt that The AWT was the driving force behind the popularity ofJava. We can use the AWT components in our programs. All the AWT components are found in a package java.awt, some most poular classes in AWT package.

Applet (For web based programming): Creates an Applet. Button: Creates a button.

By: Amit Kumar Agrawal 197

The Smartest Way to Learn Java5

Canvas: Creates a canvas you can draw in the canvas area. CheckBox: Creates a checkbox. Choice: Creates a choice control. ComboBox: Creates a combo box. Dialog: Creates a dialog box. Frame: Creates a frame for windowed application. Label: Creates a label. List: Creates a list control. Menu: Creates a menu. Panel: Creates a panel that can contain other controls. PopupMenu: Creates a popup menu. RadioButton: Creates a radio button. ScrollBar: Creates a scrollbar. ScrollPane: Creates a scrollable surface. TextArea: Creates a 2D text control. TextField: Creates a one-dimensional text control. TextPane: Creates a text surface. Windows: Creates a freestanding window.

Differentiate Containers and Components:

The place in which we draw is called a container, and the elements that are being drawn in the container is called components. The container is derived from java.awt.Container class, different components are java.awt.Button, java.awt.Canvas, java.awt.CheckBox, java.awt.List, java.awt.Label, java.awt.TextComponent etc. The all functionality and use of AWT tools are explained properly in the forthcoming chapters.

Applet:

These are small program, primarily use in Internet programming. It can be transported from one computer to another and run using applet

viewer or any other Web-Browser that support Java.

Types of Applet:

Local Applets. Remote Applets.

By: Amit Kumar Agrawal 198

The Smartest Way to Learn Java5

Applets are of two types as written in the above. These all are the sub-packages of Applet class under java class. Thus, every Applet must contain an import statement that isimport java.applet.*;Applets also must include java.awt sub-package. AWT stands for Abstract Window Toolkit. Since all the applets run under window environment, it is necessary that it must support for that window.

Local Applets:

An Applet developed locally and stored in a local PC (Personal Computer) is called local Applet.

It can be searched through directory of local system without Internet connection.

Incase of local Applet CODEBASE may be absent. We may specify a local directory along with his path to access a local

Applet.

Remote Applets:

Remote Applet is developed by someone in the remote PC and on that PC

connected to Internet.

It can be down loaded through Internet and we can run it.

To download a remote applet its address on the web (URL: Uniform

Resource Locator.) must be known and specified in applets HTML

document as value of CODEBASE attribute.

e.g.:

CODEBASE = http://www.netserver.com//...............

Difference between Applets and Application:

Applet does not use the main method for execution the code.

By: Amit Kumar Agrawal 199

The Smartest Way to Learn Java5

When loaded Applets automatically call certain method of Applet class

to start and execute the Applet code.

Applets cannot be run independently but they are run from a web page

using HTML code.

Applets cannot read from or write to a file in the local computer.

Applets cannot run any program from local computer.

Applets are restricted from using native method.

All restriction ensures that Applet cannot do any damage to local

system.

Writing Applets:

Java must be installed in your PC. Java Applet viewer or Java enable browser must be available.

1. Building Applet tag.2. Incorporating Applet tag into web page.3. Designing web page using HTML tags.4. Preparing Applet tags.5. Incorporating Applet tag into web page.6. Creating HTML file.7. Testing Applet code.

Building of Applet code:

Applet code uses services of two classes from java class libraries.

Applet. Graphics (AWT).

Applet:

By: Amit Kumar Agrawal 200

The Smartest Way to Learn Java5

init(); paint(); start(); (To run Applet.)

Applet class contain in Java. Applet package provide life to applet

through its method like. init(), paint(), start(), etc.

When Applet is loaded, Java automatically calls a series of Applet

class method for starting, running and stopping the Applet code.

paint method when called displays the result of Applet code on

screen. The output may be text graphics or sound.

pubic void paint (Graphics g)

General format for Applet Code: -

import java.awt.*;

import java.applet.*;

public class Applet_name extends Applet

{

..........

}

public void paint(Graphics g)

{

.........

}

.........

}

Program :

By: Amit Kumar Agrawal 201

The Smartest Way to Learn Java5

Program to display Hello Friends using Applet.

C:\jdk1.5.0\bin>edit Amt076.java

import java.awt.*;

import java.applet.*;

public class Amt076 extends Applet

{

public void paint(Graphics g){

g.drawString("Hello Friends",100,100);

g.drawString("This is Created By: Amit Kumar Agrawal.",50,300);

}

}

Alt+f+x

C:\jdk1.5.0\bin>javac Amt076.java

C:\jdk1.5.0\bin>edit Amt076.html

<html>

<applet code="Amt076.class"

width=420

height=420>

</applet>

</html>

Alt+f+x

Applet class name is the main class for the Applet. Java required main Applet class to be public. When Applet is loaded, Java creates an instance of this class then a series of

Applets methods are called on that instance to execute the code.

By: Amit Kumar Agrawal 202

The Smartest Way to Learn Java5

Applet Life Cycle:

Newborn state. Running state (display). Idle or stop state. Dead state or Destroyed state.

Every java Applet when loaded undergoes a series of state changes. There are four Applet state.

Newborn state:

By: Amit Kumar Agrawal 203

The Smartest Way to Learn Java5

Applets enter this state when it is first loaded by calling init () of Applet class. Initialization occurs only once.

In this state object may be created by Applet. Initial value may be setup. Images may be loaded or Colour may be set.

To provide any extra facility in any state we must override the corresponding method.

E.g.: public void init () { .......... .......... .......... }

Running state:

Applets enter this state, when the start () of Applet class is called.

Starting may occurs in idle stop state also. start () (method) can or may be called more than once. We may override a start () to create a thread to control the

Applet. E.g.:

Public void start () { .......... .......... .......... }

Idle or stop state:

Applet becomes idle when it is stop from running. Stopping

occurs automatically when we leave the page containing the

currently running Applet.

We can override a stop () explicitly. To change the state

from stop and enhanced more functionality in Idle state.

By: Amit Kumar Agrawal 204

The Smartest Way to Learn Java5

Dead state:

Applets in dead state, when it is remove from memory. This happens automatically when we quit the browser. It is done by invoking the destroy () (method).

Dead state occurs only once in an Applet life cycle.

Creating Executable Applet:

Executable Applet is the (.class) dot class file of compiled Applet program contain (.java) dot java file. Java compiler is used to compile the Java program.

Step:

Moving to directly containing source code. By typing, compile command. Compile output (.class) is placed in the same directory as source. Debugging if any error and then again re-compiling the file.

Structure of an HTML documents: -

<HTML> <HEAD> ...................... ...................... </HEAD> <BODY> ...................... ...................... </BODY></HTML>

Designing a web page.

Java Applets are programmed that resides Web Pages.

By: Amit Kumar Agrawal 205

Heading Section

Actual Text Section

The Smartest Way to Learn Java5

A Web Page is made up of text and HTML tags that can be interpreted by a Web-Browser (like MS Internet Explorer or Netscape Navigator) or Applet viewer.

Web Pages are store in a .HTML (dot HTML) file. HTML file should be store in the same directory as the compile code of

Applet.Web Page:

Comment section. (Optional section.) Head/Header section. (Optional section.) Body section. (Compulsory section.)

<HTML> <! Comment ................> <HEAD> .................. .................. </HEAD> <BODY> .................. ................. <APPLET> ....................................... </APPLET> ................. ................. </BODY></HTML>

Comment Section:

It begins with <! And ends with > tag. Web-browser will ignore the text enclosed in comment section. It can be included any where in the Web Page.

Head Section:

It contains title of the Web Page. Text enclosed in head section will appear in the title bar of Web Page.

By: Amit Kumar Agrawal 206

The Smartest Way to Learn Java5

Body Section:

It contains the entire information about the Web Page and its behavior. It also contains the Applet tag.

Applet Tag:

The Applet supplies the name of the Applet to be loaded and informs the browser about its space requirement.

e.g.: <APPLET CODE = "Hellojava.class" WIDTH = 200 HEIGHT = 200> </APPLET> Applet Tag must specify the name of the Applet, Width, and Height of the

Applet. We can put together various component of Web Page to create a file known

as HTML file. Applet tag is inserted in Web Page at appropriate place.

Running the Applet:

To run an Applet we must have a java enable Web Browser or a java Applet viewer.

If a Browser is used, we can see the entire Web Page containing Applet in the output.

If Applet viewer is used then we can see any Applet part output. We can run the whole page by using Applet viewer * . HTML.

Complete syntax of Applet tag:

<APPLET> [CODEBASE = URL Address.............]

CODE = "Applet File Name.class"

[ALT=Alternative Text.]

By: Amit Kumar Agrawal 207

The Smartest Way to Learn Java5

[NAME=Applet Instance class]

HEIGHT = Interims of Pixel.

WIDTH = Interims of Pixel.

[<PARAM NAME = String

VALUE = Val1>]

</APPLET>Passing parameter to Applet:

We can supply user-defined parameters to an Applet using <PARAM .............> tag.

Each <PARAM ............> tag has a NAME attribute and a VALUE attribute.

We can change the text to be displayed by an Applet by supplying new tags to the Applet. A <PARAM ..........> tag.

Program :

/* program to show the use of PARAM tag of Applet class*/import java.awt.*;import java.applet.*;

public class Amt077 extends Applet{ String str; public void init() { str=getParameter("Amit Singhal Well Come you all to in this new world of programming"); if (str==null) { str=" Java Program"; } str="Hello this is"+str; } public void paint(Graphics g) { g.drawString(str,10,200); }}

By: Amit Kumar Agrawal 208

The Smartest Way to Learn Java5

HTML file for the above Applet.

<HTML> <! parameter passing to Applet> <HEAD> <TITLE> JAVA APPLET OF AMIT SINGHAL </TITLE> </HEAD> <BODY> <APPLET CODE="Amt077.class" WIDTH=1100 HEIGHT=700> <PARAM NAME="AMIT KUMAR AGRAWAL" VALUE="APPLET"> </APPLET> </BODY></HTML>

Program :

The program is to give a animation program of Applet by passing parameter to the Applet.c:\jdk1.5.0\bin>edit animate.java

import java.awt.*;import java.applet.Applet;public class animate extends Applet implements Runnable{ int fFrame=-1; int fDelay; Thread fThread; Image[] fEarth; MediaTracker fTracker; Image foffScreenImage; Graphics foffScreenGraphics; public void init() { fEarth= new Image[10]; String theString; int theFramesPerSecond=10; fTracker=new MediaTracker(this); foffScreenImage=createImage(getSize().width,getSize().height); foffScreenGraphics=foffScreenImage.getGraphics(); foffScreenGraphics.setColor(Color.blue); foffScreenGraphics.fillRect(0,0,getSize().width,getSize().height); for(int i=1;i<=10;i++)

By: Amit Kumar Agrawal 209

The Smartest Way to Learn Java5

{ fEarth[i-1]=getImage(getCodeBase(),"./Earth"+i+".gif"); fTracker.addImage(fEarth[i-1],0); } theString=getParameter("fps"); try { if(theString!=null) { theFramesPerSecond=Integer.parseInt(theString); } }catch(NumberFormatException e) {} fDelay=(theFramesPerSecond>0)?(1000/theFramesPerSecond):10; } public void start() { if(fThread==null) { fThread=new Thread(this); } fThread.start(); } public void stop() { fThread=null; } public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); long theStartTime=System.currentTimeMillis(); try { fTracker.waitForID(0); }catch(InterruptedException e) { System.err.println("Interrupted Exception:"+e.getMessage()); return; } while(Thread.currentThread()==fThread) { fFrame++; repaint(); try { theStartTime+=fDelay; Thread.sleep(Math.max(0,theStartTime-System.currentTimeMillis()));

By: Amit Kumar Agrawal 210

The Smartest Way to Learn Java5

}catch(InterruptedException e) { break; } } } public void update(Graphics g) { foffScreenGraphics.setColor(Color.blue); foffScreenGraphics.clearRect(0,0,getSize().width,getSize().height); foffScreenGraphics.fillRect(0,0,getSize().width,getSize().height); paint(g); } public void paint(Graphics g){ if(fTracker.checkID(0)) { foffScreenGraphics.drawImage(fEarth[fFrame%30],0,0,this); g.drawImage(foffScreenImage,0,0,this); } }}

c:\jdk1.5.0\bin>edit animate.html

<HTML><APPLET CODE="animate.class" WIDTH=640 HEIGHT=480><PARAMNAME="fps"VALUE="Earth.gif"></APPLET></HTML>

In the above program, we have to create 10 interrelated images in the name of Earthn with extinction .GIF for the better out put. Here the n represents numerical value from 1 to 10.

Displaying numerical values in Applet programming:

In Applet we can display numerical values by first converting them into String then calling valueOf method of String class for getting the numerical value and finally using drawString method of Graphics class to displaying it on Applet viewer screen.

By: Amit Kumar Agrawal 211

The Smartest Way to Learn Java5

Program :

/* program for displaying numerical value in Applet programming*/import java.awt.*;import java.applet.*;

public class Amt078 extends Applet{ public void paint(Graphics g) { int val1=100; int val2=250; int sum=val1+val2; String s="Sum = "+String.valueOf(sum); String st1="Val1= " +String.valueOf(val1); String st2="Val2= " +String.valueOf(val2); String str="Val1 + Val2 = "; g.drawString(st1,10,180); g.drawString(st2,10,190); g.drawString(str+s,10,200); }}

C:\jdk1.5.0\bin>edit Amt078.html

<HTML> <HEAD> <TITLE> AMIT PRINTING A NUMERIC VALUE BY USING APPLET</TITLE> </HEAD> <BODY> <APPLET CODE="Amt078.class" WIDTH=1100 HEIGHT=700> </APPLET> </BODY></HTML>

Interactive input to an Applet:

As Applet box is a graphical environment, it treats all the inputs as text String.

We can create an area of String where user can type and edit input by using TextField class of Applet package.

By: Amit Kumar Agrawal 212

The Smartest Way to Learn Java5

setText and getText methods are used for invoking and setting text Strings as interactive inputs on the screen. (add(text)).

add(text) method can be used after instantiating text field class as objects.

Program :

Program to show the use of add(text) method and Label class.

/* program to demonstrate the use of add(text)and label*/

import java.awt.*;import java.applet.*;

public class Amt079 extends Applet{ public void init() { Label A=new Label("Amit"); Label B=new Label("Agrawal"); Label C=new Label("Kumar"); add(A); add(C); add(B); }}

c:\jdk1.5.0\bin>edit Amt079.html

<HTML> <HEAD> </HEAD> <BODY> <APPLET CODE="Amt079.class" WIDTH=1100 HEIGHT=700> </APPLET> </BODY></HTML>

Program :

/* program to demonstrate the use of TextField and getText()*/

import java.awt.*;import java.awt.event.*;import java.applet.*;

By: Amit Kumar Agrawal 213

The Smartest Way to Learn Java5

public class Amt080 extends Applet implements ActionListener{ TextField Lion,Tiger; public void init() { Label A=new Label("Name : ",Label.RIGHT); Label B=new Label("Password : ",Label.RIGHT); Lion=new TextField(20); Tiger=new TextField(8); Tiger.setEchoChar('#'); add(A); add(Lion); add(B); add(Tiger); Lion.addActionListener(this); Tiger.addActionListener(this); } public void actionPerformed(ActionEvent ae) { repaint(); } public void paint(Graphics g) { g.drawString("NAME : "+Lion.getText(),16,160); g.drawString("Selected Text : "+Lion.getSelectedText(),16,180); g.drawString("PassWord : "+Tiger.getText(),16,200); }}

c:\jdk1.5.0\bin>edit Amt080.html

<HTML> <HEAD> </HEAD> <BODY> <APPLET CODE="Amt080.class" WIDTH=1100 HEIGHT=700> </APPLET> </BODY></HTML>

Program :

/*program to demonstrate TextArea with Scroll Bar*/

import java.awt.*;

By: Amit Kumar Agrawal 214

The Smartest Way to Learn Java5

import java.awt.TextArea;import java.applet.*;

public class Amt081 extends Applet{ public void init() { String val="The New Millennium will witness the rise of the Information Technology"+ "\nAmit Kumar Agrawal Says in this intellectual society.\n"+ "Globally, Electronics technology has been growing \nin a geometric progression\n"+ "from a stand-alone PC to a networks\n- the growth has excceeded all progression \n"+ "This is IT sector which has no limit in its progrssion\n"+ "The IT sector is the imerging technology of this century\n"+ "there are so many have to done in this sector\n"+ "we all have to contribute ourself to this technology\n"+ "Now Amit Agrawal conclude his talk"; TextArea AmitText=new TextArea(val,10,30); add(AmitText); }}c:\jdk1.5.0\bin>edit Amt081.html

<HTML> <HEAD> </HEAD> <BODY> <APPLET CODE="Amt081.class" WIDTH=1100 HEIGHT=700 ALT="AMIT TEXT AREA"> </APPLET> </BODY></HTML>

Program :

/* program for moving a String in Applet*/// Thread with the Applet program.

import java.awt.*;import java.applet.*;

public class Amt082 extends Applet implements Runnable{ String str=" Amit Singhal String Moving Program ";

By: Amit Kumar Agrawal 215

The Smartest Way to Learn Java5

Thread t=null; int stat; boolean stBan; public void init() { setBackground(Color.blue); setForeground(Color.red); } public void start() { t=new Thread(this); stBan=false; t.start(); } public void run() { char ch; for(;;) { try { repaint(); Thread.sleep(245); ch=str.charAt(0); str=str.substring(1,str.length()); str+=ch; if(stBan) break; } catch(InterruptedException e) {} } } public void stop() { stBan=true; t=null; } public void paint(Graphics g) { g.drawString(str,250,150); }} c:\jdk1.5.0\bin>edit Amt082.html

<HTML> <HEAD>

By: Amit Kumar Agrawal 216

The Smartest Way to Learn Java5

</HEAD> <BODY> <APPLET CODE="Amt082.class" WIDTH=1100 HEIGHT=700 ALT="AMIT MOVING STRING"> </APPLET> </BODY></HTML>

Program :

import java.awt.*;import java.lang.Thread;import java.applet.Applet;import java.lang.Math;

public class animate1 extends Applet { static int xp=1; Graphics xxx; public void init() { setBackground(Color.cyan); } public void paint(Graphics g) { int ht=360; int wt=480; double res=0; int xx=480/2; int yy=360/2; for(int aj=1;aj>0;aj++) { for(double x=1;x<=480;x+=5) { for(int y=1;y<=360;y++) { for(int z=1;z<=480;z++) { res=Math.sqrt(((wt/2)-z)*((wt/2)-z)+((ht/2)-y)*((ht/2)-y)); if(aj%2==0) { if(res==x && (z!=240 && y!=180)) { g.drawString(" ",z,y); } if(res==x && (z!=240 && y!=180))

By: Amit Kumar Agrawal 217

The Smartest Way to Learn Java5

{ g.drawString("þ",xx+1,yy); } xx=z; yy=y; } else { if(res==x && (z!=240 && y!=180)) { g.drawString(" ",xx+1,yy); } if(res==x && (z!=240 && y!=180)) { g.drawString("þ",z,y); } xx=z; yy=y; }}}} switch(xp) { case 1: g.setColor(Color.darkGray); break; case 2: g.setColor(Color.red); break; case 3: g.setColor(Color.gray); break; case 4: g.setColor(Color.blue); break; case 5: g.setColor(Color.magenta); break; case 6: g.setColor(Color.pink); break; case 7: g.setColor(Color.green); break; case 8: g.setColor(Color.yellow); break; case 9: g.setColor(Color.lightGray); break;

By: Amit Kumar Agrawal 218

The Smartest Way to Learn Java5

} if(xp==10) { g.setColor(Color.white); xp=1; } xp++; repaint(); } }}

c:\jdk1.5.0\bin>edit animate1.html <html><applet CODE="animate1.class" width=480 height=360><PARAMNAME="fps"VALUE="Earth.gif"></applet></html>

Graphics programming:

The Applets can be used to draw lines, figure, images, and text in different

forms and size.

Every Applet has its own area on the screen where it creates. Its display.

(The area is known as canvas area.)

Size of Applet space is determines by the attribute of the Applet tag such as

HEIGHT & WIDTH.

Graphics class:

It includes methods to drawing different shapes.

By: Amit Kumar Agrawal 219

The Smartest Way to Learn Java5

All drawing method must have argument representing end point, corner,

starting, location or angle of a value in Applet coordinate system.

Drawing method:

1. clearRect() :- It erases a rectangular area of canvas. //clearRect(x,y, height,

width)

2. copyArea() :- It copies a rectangular area of canvas to another area.

3. drawArc() :- It draw a holo arc.

4. fillArc() :- It is use to draw the fill arc.

5. drawOval() :- It is use to draw a Oval.

6. drawPolygon() :- It is use to draw a Polygon.

7. drawRect() :- It is use to draw Rectangle.

8. drawString() :- It is use to display a string in Applet in the specified

position.

9. fillPolygon() :- It is use to draw fill polygon.

10. getColor() :- It is use to get the current color.

11. setColor() :- It is use to set a color to the current drawing.

12. getFont() :- It is use to retrieve the current font.

13. getFontMetrics() :- It returns all the information about the current font.

14. setFont() :- It is use to set a font style to the current string.

15. drawLine() :- It is use to draw line. // drawLine(x, y, x1, y1).

16. drawRoundRect() :- It is use to draw round rectangle.

17. fillRect() :- It is use to draw fill rectangle.

18. fillRoundRect() :- It is use to draw fill round rectangle.

19. getRed(), getGreen(), getBlue() :- It is use to get the Red, Green, and Blue

color independently.

By: Amit Kumar Agrawal 220

The Smartest Way to Learn Java5

Program :

/* progra to show the use of drawLine(),drawRect(), fillRect(), drawRoundRect()*/

import java.awt.*;import java.applet.*;

public class Amt083 extends Applet{ public void paint(Graphics g) { g.drawLine(95,105,95,305); g.drawRect(105,105,200,205); g.fillRect(315,105,200,205); g.drawRoundRect(520,105,150,200,50,30); }}c:\jdk1.5.0\bin>edit Amt083.html

<HTML> <HEAD> <TITLE> AMIT APPLET GRAPHICS PROGRAM </TITLE> </HEAD> <BODY> <APPLET CODE ="Amt083.class" WIDTH =800 HEIGHT =800> </APPLET> </BODY></HTML>

The output of the program is given below.

By: Amit Kumar Agrawal 221

The Smartest Way to Learn Java5

Drawing circle and ellipse by using drawOval () :

Graphics class does not have any method to draw Circle and Ellipse. drawOval() is use to draw a Circle and Ellipse. It takes four arguments, first and second denotes the starting point or in the

other words the initial co-ordinate of the rectangle, which covers in to the corresponding Oval. Next two parameter denotes the Height and Width of the covered rectangle.

If the value of last two parameter is not same then it's a Ellipse. If same then it's a Circle.

Drawing an arc:

drawArc method take six segment first four are same as drawOval method but the last represent starting angle of the Arc and the number of degree travels around the Arc from starting angle respectively.

Program :

By: Amit Kumar Agrawal 222

The Smartest Way to Learn Java5

The program to show the use drawOval(), fillOval(), fillArc().

import java.awt.*;import java.applet.*;

public class amit007 extends Applet{ public void paint(Graphics g) { g.drawOval(40,40,120,150); g.drawOval(57,75,30,20); g.drawOval(110,75,30,20); g.fillOval(68,81,10,10); g.fillOval(121,81,10,10); g.drawOval(85,100,30,30); g.fillArc(60,125,80,40,180,180);g.drawString("Amit Kumar Agrawal's Human Part Applet program.",25,250); }}

c:\jdk1.5.0\bin>edit amit007.html

<html>

<head>

<title> Amit Kumar Agrawal </title>

<h1 allign="CENTER"> This is the amit's first graphics program

</h1>

</head>

<body>

<applet code="amit007.class"

width=300

height=300>

</applet>

</body>

</html>

The output of the program is like the result given below.

By: Amit Kumar Agrawal 223

The Smartest Way to Learn Java5

Drawing polygon:

We can draw polygon by taking n side using drawLine method n times is succession.

drawPolygon take three arguments. First, one is an Array of integer containing x co-ordinate. Second, one is an Array of integer containing y co-ordinate. Third, one is an integer for total number of points.

Program :

The program to show the use of drawPolygon().

/* program to draw a polygon*/import java.awt.*;import java.applet.*;

By: Amit Kumar Agrawal 224

The Smartest Way to Learn Java5

public class Amt084 extends Applet{ public void paint(Graphics g) { int Aa[]={20,120,220,320,420}; int Lr[]={20,120,20,20,360}; int n=5; g.drawPolygon(Aa,Lr,n);}}c:\jdk1.5.0\bin>edit Amt084.html

<HTML> <HEAD> <TITLE> AMIT KUMAR POLYGON DRAWING PROGRAM </TITLE> </HEAD> <BODY> <APPLET CODE="Amt084.class" WIDTH=500 HEIGHT=500> </APPLET> </BODY></HTML>

Program :

/* program to draw a polygon*/import java.awt.*;import java.applet.*;

public class Amt085 extends Applet{ public void paint(Graphics g) { int Al[]={20,120,220,320,420}; int ar[]={20,215,315,415,499}; int n=5; g.fillPolygon(Al,ar,n); }} c:\jdk1.5.0\bin>edit Amt085.html

<HTML> <HEAD> <TITLE> AMIT KUMAR FILL POLYGON DRAWING PROGRAM </TITLE> </HEAD> <BODY> <APPLET CODE="Amt085.class"

By: Amit Kumar Agrawal 225

The Smartest Way to Learn Java5

WIDTH=500 HEIGHT=500> </APPLET> </BODY></HTML>

Program :

Program to display a CLOCK on Applet.

import java.util.*;import java.awt.*;import java.applet.*;import java.text.*;

public class Amt086 extends Applet implements Runnable{ Thread timer; int lastxs, lastys, lastxm, lastym, lastxh, lastyh; SimpleDateFormat formatter; String lastdate; Font clockFaceFont; Date currentDate; Color handColor; Color numberColor; public void init() { int x,y; lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0; formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy", Locale.getDefault()); currentDate = new Date(); lastdate = formatter.format(currentDate); clockFaceFont = new Font("Serif", Font.PLAIN, 14); handColor = Color.blue; numberColor = Color.darkGray; try { setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),16))); } catch (Exception E) { } try {

By: Amit Kumar Agrawal 226

The Smartest Way to Learn Java5

handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),16)); } catch (Exception E) { } try { numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"),16)); } catch (Exception E) { } resize(300,300); } public void plotpoints(int x0, int y0, int x, int y, Graphics g) { g.drawLine(x0+x,y0+y,x0+x,y0+y); g.drawLine(x0+y,y0+x,x0+y,y0+x); g.drawLine(x0+y,y0-x,x0+y,y0-x); g.drawLine(x0+x,y0-y,x0+x,y0-y); g.drawLine(x0-x,y0-y,x0-x,y0-y); g.drawLine(x0-y,y0-x,x0-y,y0-x); g.drawLine(x0-y,y0+x,x0-y,y0+x); g.drawLine(x0-x,y0+y,x0-x,y0+y); } public void circle(int x0, int y0, int r, Graphics g) { int x,y; float d; x=0; y=r; d=5/4-r; plotpoints(x0,y0,x,y,g); while (y>x) { if (d<0) { d=d+2*x+3; x++; } else { d=d+2*(x-y)+5; x++; y--; } plotpoints(x0,y0,x,y,g); }

By: Amit Kumar Agrawal 227

The Smartest Way to Learn Java5

} public void paint(Graphics g){ int xh, yh, xm, ym, xs, ys, s = 0, m = 10, h = 10, xcenter, ycenter; String today; currentDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("s",Locale.getDefault()); try { s = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { s = 0; } formatter.applyPattern("m"); try { m = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { m = 10; } formatter.applyPattern("h"); try { h = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { h = 10; } formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy"); today = formatter.format(currentDate)+" "; xcenter=180; ycenter=155; xs = (int)(Math.cos(s * 3.14f/30 - 3.14f/2) * 65 + xcenter); ys = (int)(Math.sin(s * 3.14f/30 - 3.14f/2) * 65 + ycenter); xm = (int)(Math.cos(m * 3.14f/30 - 3.14f/2) * 50 + xcenter); ym = (int)(Math.sin(m * 3.14f/30 - 3.14f/2) * 50 + ycenter); xh = (int)(Math.cos((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 40 + xcenter); yh = (int)(Math.sin((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 40 + ycenter); g.setFont(clockFaceFont); g.setColor(handColor);

By: Amit Kumar Agrawal 228

The Smartest Way to Learn Java5

circle(xcenter,ycenter,95,g); g.setColor(numberColor); g.drawString("IX",xcenter-80,ycenter+3); g.drawString("III",xcenter+75,ycenter+3); g.drawString("XII",xcenter-5,ycenter-72); g.drawString("VI",xcenter-3,ycenter+80); g.setColor(getBackground()); if (xs != lastxs || ys != lastys) { g.drawLine(xcenter, ycenter, lastxs, lastys); g.drawString(lastdate, 5, 325); } if (xm != lastxm || ym != lastym) { g.drawLine(xcenter, ycenter-1, lastxm, lastym); g.drawLine(xcenter-1, ycenter, lastxm, lastym); } if (xh != lastxh || yh != lastyh) { g.drawLine(xcenter, ycenter-1, lastxh, lastyh); g.drawLine(xcenter-1, ycenter, lastxh, lastyh); } g.setColor(numberColor); g.drawString("", 5, 325); g.drawString(today, 5, 325); g.drawString("CLOCK program By : Amit Kumar Agrawal.",3,350); g.drawLine(xcenter, ycenter, xs, ys); g.setColor(handColor); g.drawLine(xcenter, ycenter-1, xm, ym); g.drawLine(xcenter-1, ycenter, xm, ym); g.drawLine(xcenter, ycenter-1, xh, yh); g.drawLine(xcenter-1, ycenter, xh, yh); lastxs=xs; lastys=ys; lastxm=xm; lastym=ym; lastxh=xh; lastyh=yh; lastdate = today; currentDate=null; } public void start() { timer = new Thread(this); timer.start(); } public void stop() { timer = null; } public void run()

By: Amit Kumar Agrawal 229

The Smartest Way to Learn Java5

{ Thread me = Thread.currentThread(); while (timer == me){ try{ Thread.currentThread().sleep(100); } catch (InterruptedException e) {} repaint(); }} public void update(Graphics g) { paint(g); }

public String getAppletInfo() { return "Title: A Clock \nAuthor: Amit Kumar Agrawal."; }

public String[][] getParameterInfo() { String[][] info = { {"bgcolor", "hexadecimal RGB number", "The background color. Default is the color of your browser."}, {"fgcolor1", "hexadecimal RGB number", "The color of the hands and dial. Default is blue."}, {"fgcolor2", "hexadecimal RGB number", "The color of the seconds hand and numbers. Default is dark gray."} }; return info; }}

c:\jdk1.5.0\bin>edit Amt086.html

<HTML>

<HEAD>

<TITLE> AMIT KUMAR CLOCK PROGRAM </TITLE>

</HEAD>

<BODY>

<APPLET CODE="Amt086.class"

WIDTH=500

By: Amit Kumar Agrawal 230

The Smartest Way to Learn Java5

HEIGHT=500>

</APPLET>

</BODY>

</HTML>

The output of the above program is.

Program :

Program for a text animation program.

import java.awt.event.*;import java.awt.Graphics;import java.awt.Font;import java.applet.Applet;import java.awt.*;import java.applet.*;

public class Amt087 extends Applet implements Runnable, MouseListener

By: Amit Kumar Agrawal 231

The Smartest Way to Learn Java5

{ String banner; char ban_Chars[]; char atrs[]; Thread IM_runner = null; boolean threadSuspended; static final int IM_RER_WD = 15; static final int IM_RER_HT = 36; static final int IM_SML_WD = 12; static final int IM_SML_HT = 24; Font regularFont = new Font("TimesRoman", Font.BOLD, IM_RER_HT); Font smallFont = new Font("TimesRoman", Font.BOLD, IM_SML_HT); public void init(){ banner = getParameter("text"); setForeground(Color.blue); setBackground(Color.cyan); if (banner == null){ banner = "Amit Kumar Agrawal's Applet in Java"; } int bannerLength = banner.length(); StringBuffer bc = new StringBuffer(bannerLength); StringBuffer attrs = new StringBuffer(bannerLength); int wd = 0; for (int i = 0; i < bannerLength; i++){ char c = banner.charAt(i); char a = 0; if (c == '^'){ i++; if (i < bannerLength){ c = banner.charAt(i); a = '^'; wd += IM_SML_WD - IM_RER_WD; } else { break; } } bc.append(c); attrs.append(a); wd += IM_RER_WD;} bannerLength = bc.length(); ban_Chars = new char[bannerLength]; atrs = new char[bannerLength]; bc.getChars(0, bannerLength, ban_Chars, 0); attrs.getChars(0, bannerLength, atrs, 0); threadSuspended = false; resize(wd + 10, 50);

By: Amit Kumar Agrawal 232

The Smartest Way to Learn Java5

addMouseListener(this); } public void destroy(){ removeMouseListener(this); } public void start(){ IM_runner = new Thread(this); IM_runner.start(); } public synchronized void stop() { IM_runner = null; if (threadSuspended) { threadSuspended = false; notify(); } } public void run() { Thread me = Thread.currentThread(); while (IM_runner == me) { try { Thread.sleep(100); synchronized(this) { while (threadSuspended) { wait(); } } } catch (InterruptedException e) {} repaint(); } } public void paint(Graphics g) { int length = ban_Chars.length; for (int i = 0, x = 0; i < length; i++) { int wd, ht; if (atrs[i] == '^') { wd = IM_SML_WD;

By: Amit Kumar Agrawal 233

The Smartest Way to Learn Java5

ht = IM_SML_HT; g.setFont(smallFont); } else{ wd = IM_RER_WD; ht = IM_RER_HT; g.setFont(regularFont); } int px = (int) (10 * Math.random() + x); int py = (int) (10 * Math.random() + ht); g.drawChars(ban_Chars, i, 1, px, py); x += wd; } } public synchronized void mousePressed(MouseEvent e) { e.consume(); threadSuspended = !threadSuspended; if (!threadSuspended) notify(); } public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public String getAppletInfo() { return "Title: Applet By: Amit Kumar Agrawal"; } public String[][] getParameterInfo() { String pinfo[][] = { {"text", "string", "Text to display"}, }; return pinfo; }}

c:\jdk1.5.0\bin>edit Amt087.html

</HTML> <HEAD> <title>Amit Kumar Agrawal Animation program</title>

By: Amit Kumar Agrawal 234

The Smartest Way to Learn Java5

</HEAD> <BODY> <hr> <applet code="Amt087.class" width=700 height=50> <param name=text value="Amit Kumar Agrawal Animation program"> </applet> <hr> </BODY></HTML>

Program :

The program to show the use of loops in side the Applet.

import java.awt.*;import java.applet.*;

public class classloop extends Applet{ public void paint(Graphics g) { for (int i=0;i<=4;i++) { if((i%2)==0) { g.drawOval(120,i*60+10,50,50); } else { g.fillOval(120,i*60+10,50,50); } } }}

c:\jdk1.5.0\bin>edit classloop.html

<html> <head>

<title> Amit Kumar Agrawal </title>

<h1> This is the Amit's second Graphics program </h1>

</head>

<body>

By: Amit Kumar Agrawal 235

The Smartest Way to Learn Java5

<applet code="classloop.class"

width=300

height=400>

</applet>

</body>

</html>

The output of the given program is

Program :

The program to show the use of claerRect() method.

C:\jdk1.5.0\bin>edit Amt088.java/*program to show the use of clearRect()*/

import java.awt.*;import java.applet.*;

public class Amt088 extends Applet{

By: Amit Kumar Agrawal 236

The Smartest Way to Learn Java5

Font regularFont=new Font("Times New Roman",Font.BOLD,26); public void init(){ setBackground(Color.cyan); setForeground(Color.red); } public void paint(Graphics g){ int A=0; int B=0; int C=700; int D=500; for(;;){ g.setFont(regularFont); g.clearRect(A,B,C,D); g.drawString("It is Amit Agrawal clearRect method testing program",20,100); try{ Thread.sleep(1000); } catch(Exception e){} g.clearRect(A,B,C,D); g.drawString("Now I am again print the previous message",20,100); try { Thread.sleep(1000); } catch(Exception e){} g.clearRect(A,B,C,D);}}}

Alt+f+xc:\jdk1.5.0\bin>edit Amt088.html

</HTML> <HEAD> <title>Amit Kumar Agrawal clearRect method testing program</title> </HEAD> <BODY> <hr> <applet code="Amt088.class" width=700 height=250> </applet> <hr> </BODY> </HTML>

Program :

The program shows the use of copyArea method.

By: Amit Kumar Agrawal 237

The Smartest Way to Learn Java5

/*program to show the use of copyRect()*/

import java.awt.*;import java.applet.*;

public class Amt089 extends Applet{ Font MyFont=new Font("Times New Roman",Font.BOLD,20); public void init(){ setBackground(Color.yellow); setForeground(Color.red); } public void paint(Graphics g){ int A=0; int B=0; int C=700; int D=500; for(;;){ g.setFont(MyFont); g.clearRect(A,B,C,D); g.drawString("It is Amit Agrawal copyArea method testing program",20,100); try{ Thread.sleep(1000); } catch(Exception e){} g.copyArea(A,B,C,D,A,B+150); g.drawString("Copy of above text is here",20,225); try{ Thread.sleep(5000); } catch(Exception e){}}}}

c:\jdk1.5.0\bin>edit Amt089.html

</HTML> <HEAD> <title>Amit Kumar Agrawal copyArea method testing program</title> </HEAD> <BODY> <hr> <applet code="Amt089.class" width=700 height=350> </applet> <hr> </BODY></HTML>

Event Handling in Applet:

By: Amit Kumar Agrawal 238

The Smartest Way to Learn Java5

Events:

In the Applet program construct, an event is an object that describes about the different state of changes in the source. It can be implemented because of the user interacting with the different element in a GUI(Graphical User Interface). The other activities that cause event to be generated are Pressing of button, Entering character by the keyboard, Selecting an item from a list, and Mouse events(Double click, Mouse Wheel Event, Click etc.).The event is a sub class of java.awt class. By import the java.awt.event class, we can give any event to the program(Applet program or Graphics program in Java). The event class is also called as Java's event handling mechanism.addKeyListener() and addMouseMotionListener() are: method that is use to add a keyboard event listener and the method, which registers a mouse motion listener respectively. When an event occurs, all recognized listener(all register listener) are notified and receive a copy of the event object. This process is called as multicasting the event. In all cases, the notification is sent only to the listener, which are register to receive them.

Format of declaring or registering a listener: public void addTypeListner(TypeListener el);

Throws java.util.TooManyListnersException

format to Un-register a listener:

public void removeTypeListener(TypeListener el);

Event Classes:

The classes, which represent events, are at the core of Java's event handling mechanism. Thus, we start our study with event handling of event classes. As we know the events provide consistent, easy to handle, this means of encapsulating events.At the root of the Java event class hierarchy is EventObject, which is in java.util, it is the super class of the all events in other words it is the container of the all events provided by the Java.

By: Amit Kumar Agrawal 239

The Smartest Way to Learn Java5

EventObject(Object src);

Here, src is the instance of the same class that generates this event. The EventObject class contain two methods: getSource() and toString(). The getSource() method returns the source of the event. Its form is:

Object getSource();As the name, suggest the toString() returns the string equivalent of the event.The class AWTEvent, defined within the java.awt package, it is a sub-class of the EventObject. It is the super class (either directly or indirectly) of all AWT based events used by the delegation event model. Its getID() method can be used to determine the type of the event. The signature of this method is:

int getID();

The package java.awt.event defines several types of the events that are generated by different user interface elements. The table given below will gives you an overall view of the important event provide by the same class and supply a brief note on the same.

By: Amit Kumar Agrawal 240

The Smartest Way to Learn Java5

The ActionEvent Class:

The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. In addition, there is an integer constant, ACTION_PERFORMED, which can be used to identify action events.ActionEvent has following three constructers:

ActionEvent(Object src, int type, String str)ActionEvent(Object src, int type, String cmd, int modifiers)

By: Amit Kumar Agrawal 241

The Smartest Way to Learn Java5

ActionEvent(Object src, int type, String cmd, long when, int modifiers)

You can access the command name for the invoking ActionEvent object by using the getActionCommand() method is used.

String getActionCommand()

You can access the modifier keys (ALT, CTRL, META, or SHIFT) value by using the getModifiers() method. It returns an integer value.

int getModifiers()

similarly getWhen() method is used to access the time at which the event took place. This is called as the event's timestamp.

long getWhen()

The adjustmentEvent class:

The AdjustmentEvent class defines integer constants that can be used to identify

them. The constants and their meanings are:

BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its

value.

BLOCK_INCREMENT The user clicked inside the scroll bar to increase its

value.

TRACK The slider was dragged.

UNIT_DECREMENT The button at the end of the scroll bar was clicked to

decrease its value.

UNIT_INCREMENT The button at the end of the scroll bar was clicked to

increase its value.

AdjustmentEvent Constructer:

By: Amit Kumar Agrawal 242

The Smartest Way to Learn Java5

AdjustmentEvent(Adjustable src, int id, int type, int data)

getAdjustable() method : To get the object that generate the event.

Adjustable getAdjustable()

getAdjustmentType() method : To get the type of the adjustment event in the form

of integer.

int getAdjustmentType()

getValue() method : To get the amount of the adjustment can be obtained from the

same in the form of integer.

int getValue()

The ComponentEvent class:

The ComponentEvent class defines integer constants that can be used to identify them.

COMPONENT_HIDDEN The component was hidden.

COMPONENT_MOVED The component was moved.

COMPONENT_RESIZED The component was resized.

COMPONENT_SHOWN The component became visible.

Component event constructer:

ComponentEvent(Component src, int type)

getComponent() : It is used to access the component that generate the event.

Component getComponent()

By: Amit Kumar Agrawal 243

The Smartest Way to Learn Java5

The ContainerEvent class:

The ContainerEvent class defines int constant that can be identify them: COMPONENT_ADDED and COMPONENT_REMOVED. They indicate that a component has been added to or removed from the container.

ContainerEvent is a sub-class of ComponentEvent and has this constructer.

ContainerEvent(Component src, int type, Component comp)

getContainer() : It return a reference to the container that generate by the event.

Container getContainer()

getChild() : It return a reference to the component to that was added to or removed from the container. Its general form is:

Component getChild()

The FocusEvent class:

The FocusEvent are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.

Focus Event is a sub-class of ComponentEvent and has three constructer.

FocusEvent(Component src, int type)FocusEvent(Component src, int type, bollean temporaryFlag)FocusEvent(Component src, int type, bollean temporaryFlag, Component other)

getOppositeComponent() : We can determine the other component by the same method.

Component getOppositeComponent()

isTemporary() : This method is indicates if this focus change is temporary.

boolean isTemporary()The method returns true if the change is temporary. Otherwise, it returns false.

By: Amit Kumar Agrawal 244

The Smartest Way to Learn Java5

The InputEvent class:

The InputEvent class is the sub-class of ComponentEvent and is the supper-class

of for Component input events. Its sub-classes are KeyEvent and MouseEvent.

InputEvent class represents eight values to represent the modifiers.

ALT_MASK BUTTON2_MASK META_MASKALT_GRAPH_MASK BUTTON3_MASK SHIFT_MASKBUTTON1_MASK CTRL_MASK

Some other extended modifiers to avoid possible conflicts between the modifiers used by the keyboard events and mouse events, and other issues.

ALT_DOWN_MASK ALT_GRAPH_DOWN_MASKBUTTON2_DOWN_MASK BUTTON3_DOWN_MASKMETA_DOWN_MASK SHIFT_DOWN_MASKBUTTON1_DOWN_MASK CTRL_DOWN_MASK

Some methods are use to check whether the modifier was pressed or not at the time of an event is generated. We use the following methods:

isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown() and isShiftDown() methods. The formats for these methods are:

boolean isAltDown()boolean isGraphDown()boolean isControlDown()boolean isMetaDown()boolean isShiftDown()

getModifiers() : It is use to access a value that contains all of the original modifier flags by calling the same.

int getModifiers()

getModifiersex() : It is use to access a value that contains all of the extended modifier by calling the same.

By: Amit Kumar Agrawal 245

The Smartest Way to Learn Java5

int getModifiersEx() The ItemEvent class:

There are two types of item events, which can identified by the following integer constants:

DESELECTED The user deselected an item.SELECTED The user selected an item.

There is a special integer constant ITEM_STATE_CHANGED in addition. That signifies a change of state.

ItemEvent has this constructer:

ItemEvent(ItemSelectable src, int type, Object entry, int state)

getItem() : It is the reference to that item that generated by an event.

Object getItem()

getItemSelectable() : It is the reference to that ItemSelectable object that is generated by an event.

ItemSelectable getItemSelectable()

getStateChange() : It is the method returns the state change for the event.

int getStateChange()

The KeyEvent class:

There are three types of integer constant which can identified a key event:

KEY_PRESSED, KEY_RELEAED, KEY_TYPED.

The first two constant occurs when any key is pressed and released. The third one

is occurs only when a character is generated.

By: Amit Kumar Agrawal 246

The Smartest Way to Learn Java5

There are some other integers constants are identified by KeyEvent. VK_0 to

VK_9 and VK_A to VK_Z define the ASCII equivalent of the number and letters.

Here are some others:

VK_ENTER VK_ESCAPE VK_CANCEL VK_UPVK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWNVK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL

KeyEvent is a subclass of InputEvent. Here are two of its constructers:

KeyEvent(Component src, int type, long when, int modifiers, int code)KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

The KeyEvent class has some function to perform special tasks.

getKeyChar() : It return the character that was entered.getKeyCode() : It return the key code.

char getKeyChar()int getKeyCode()

if no valid character is available then the getKeyChar() method is returns

CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode() returns

VK_UNDEFINED.

The MouseEvent class:

The MouseEvent class defines the following integer constants:

MOUSE_CLICKED The user clicked the mouse.MOUSE_DRAGGED The user dragged the mouse.MOUSE_ENTERED The mouse entered a component.MOUSE_EXITED The mouse exited from a component.MOUSE_MOVED The mouse moved.MOUSE_PRESSED The mouse was pressed.MOUSE_RELEASED The mouse was released.

By: Amit Kumar Agrawal 247

The Smartest Way to Learn Java5

MOUSE_WHEEL The mouse wheel was moved.

The MouseEvent is a sub-class of InputEvent. The constructers:

MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggerpopup)

The most commonly used method specified for the MouseEvent class is:

getX() : It return a integer value of x coordinate of the mouse pointer.getY() : It return a integer value of y coordinate of the mouse pointer.

int getX()int getY()

getPoint() : It return the coordinates of the mouse.

Point getPoint()

It returns a Point object that contains the X, Y coordinates in its integer members: x and y. the translatePoint(int x, int y)

Void translatePoint(int x, int y)

getClickCount() : It return the number of mouse clicks for the event.

int getClickCount()isPopupTrigger() : It return true if the event causes a popup menu to appear on the

platform. Otherwise it return false.

boolean isPopupTigger()

getButton() : It return a value which represent the button that caused the event. It

return the following values defined by MouseEvent.

NOBUTTON, BUTTON1, BUTTON2, BUTTON3.

The NOBUTTON value indicates that there is no button was pressed or released.

By: Amit Kumar Agrawal 248

The Smartest Way to Learn Java5

The MouseWheelEvent class:

Mouse wheels are used for scrolling. MouseWheelEvent defines the following two integer constants.

WHEEL_BLOCK_SCROLL A Page-up and Page-down scroll event occured

WHEEL_UNIT_SCROLL A Line-up and Line-down scroll event occured

The MouseWheelEvent class defines following constructer:

MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggerspopup, int scrollHow, int amount, int count)

getWheelRotation() : It return number of rotation to the wheel event.

int getWheelRotation()

getScrollType() : It return the type of scroll.

int getScrollType()

the getScrollType() method return either WHEEL_UNIT_SCROLL, WHELL_BLOCK_SCROLL.

If the scroll type is WHEEL_UNIT_SCROLL, we can access the number of units of scroll by calling a method getScrollAmount().

int getScrollAmount()

The TextEvent class:

By: Amit Kumar Agrawal 249

The Smartest Way to Learn Java5

The object of this class describes text events. These are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant EXT_VALUE_CHANGED.The constructer of the same class is:TextEvent(Object src, int type)

The WindowEvent class:

The WindowEvent class contain ten integer constant, which can be used to identify the same. Those are:

WINDOW_ACTIVATED The window was activated.WINDOW_CLOSED The window has been closed.WINDOW_CLOSING The user requested that the window be

closed.WINDOW_DEACTIVATED The window was deactivated.WINDOW_DEICONIFIED The window was deiconified.WINDOW_GAINED_FOCUS The window gained input focus.WINDOW_ICONIFIED The window was iconified.WINDOW_LOST_FOCUS The window lost input focus.WINDOW_OPENED The window was opened.WINDOW_STATE_CHANGED The state of the window changed.

The WindowEvent is a sub-class of ComponentEvent. It defines several constructers those are:

WindowEvent(Window src, int type)WindowEvent(Window src, int type, Window other)WindowEvent(Window src, int type, int fromstate, int tostate)WindowEvent(Window src, int type, Window other, int fromstate, int tostate)

getWindow() : It return the Window object that generated the event.

Window getWindow()

Some other method to access the object of the opposite window, the value of the previous window state, and the current window state.

By: Amit Kumar Agrawal 250

The Smartest Way to Learn Java5

Window getOppositeWindow()int getOldState()int getNewState()

Delegation event model:

The delegation event model have two important parts those are: Sources and Listeners.

The event sources:

The table given below give a idea about the Event Source and its description:

Event Listener interfaces:

By: Amit Kumar Agrawal 251

The Smartest Way to Learn Java5

Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. Some of the regular used Listeners are given below:

The event Listener interfaces:

Different methods for the Event Listener:

void actionPerformed(ActionEvent ae)void adjustmentValueChanged(AdjustmentEvent ae)void componentResized(ComponentEvent ce)void componentMoved(ComponentEvent ce)void componentShown(ComponentEvent ce)

By: Amit Kumar Agrawal 252

The Smartest Way to Learn Java5

void componentHidden(ComponentEvent ce)void componentAdded(ContainerEvent ce)void componentRemoved(ContainerEvent ce)void focusGained(FocusEvent fe)void focusLost(FocusEvent fe)void itemStateChanged(ItemEvent ie)void keyPressed(KeyEvent ke)void keyReleased(KeyEvent ke)void keyTyped(KeyEvent ke)void mouseClicked(MouseEvent me)void mouseEntered(MouseEvent me)void mouseExited(MouseEvent me)void mousePressed(MouseEvent me)void mouseReleased(MouseEvent me)void mouseDragged(MouseEvent me)void mouseMoved(MouseEvent me)void mouseWheelmoved(MouseEvent me)void textChanged(TextEvent te)void windowGainedFocus(WindowEvent we)void windowLostFocus(WindowEvent we)void windowActivated(WindowEvent we)void windowClosed(WindowEvent we)void windowClosing(WindowEvent we)void windowDeactivated(WindowEvent we)void windowDeiconified(WindowEvent we)void windowIconified(WindowEvent we)void windowOpened(WindowEvent we)

Adapter Classes

Java supports a special feature, called adapter class that can simplify the creation of event handler in certain situation. An adapter class provides an empty implementation of all methods in a listener interface.

Different Adapter Classes and the corresponding Listener Interface:

By: Amit Kumar Agrawal 253

The Smartest Way to Learn Java5

Some programs to show the image handling.

Program :

/* program to load a image on the screen*/

import java.awt.*;import java.applet.*;

public class Amt090 extends Applet{ Image amitg; public void init() { amitg=getImage(getDocumentBase(),getParameter("amitg")); } public void paint(Graphics g) { g.drawImage(amitg,5,5,this); }}

c:\jdk1.5.0\bin>edit Amt090.html

</HTML> <HEAD> <title>Amit Kumar Agrawal Image testing program</title> </HEAD> <BODY> <hr> <applet code="Amt090.class" width=155 height=120> <param name="amitg" value="Amt090.gif">

By: Amit Kumar Agrawal 254

The Smartest Way to Learn Java5

</applet> <hr> </BODY></HTML>

Program :

/* program to check wheather the image is laoded or not*/

import java.awt.*;import java.applet.*;

public class Amt091 extends Applet{ Image amitimg; boolean amerr=false; String Amtstr; public void init() { setBackground(Color.cyan); Amtstr=getParameter("amitimg"); amitimg=getImage(getDocumentBase(),Amtstr); } public void paint(Graphics g){ if (amerr){ Dimension dd=getSize(); g.setColor(Color.red); g.fillRect(0,0,dd.width,dd.height); g.setColor(Color.black); g.drawString("Sorry I M unable to load your image : "+Amtstr,15,dd.height/2); } else{ g.drawImage(amitimg,5,5,this); }} public void update(Graphics g){ paint(g); } public boolean imageUpdate(Image Amtimg,int fg,int x,int y,int w,int h){ if((fg&SOMEBITS)!=0){ repaint(x,y,w,h); } else{ if((fg&ABORT)!=0){ amerr=true; repaint();}

By: Amit Kumar Agrawal 255

The Smartest Way to Learn Java5

} return(fg&(ALLBITS|ABORT|ERROR))==0; }}

c:\jdk1.5.0\bin>edit Amt091.html

</HTML> <HEAD> <title>Amit Kumar Agrawal Image testing program</title> </HEAD> <BODY> <hr> <applet code="Amt091.class" width=255 height=120> <param name="amitimg" value="Amt091.gif"> </applet> <hr> </BODY></HTML>

Program :

/* program to display the use of Double Buffer class*/

import java.awt.event.*;import java.awt.*;import java.applet.*;

public class Amt092 extends Applet{ int gap=3; int ma,mb; boolean flicker=true; Image AmtBuff=null; int wt,ht; public void init() { Dimension dd=getSize(); wt=dd.width; ht=dd.height; AmtBuff=createImage(wt,ht); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent me) { ma=me.getX(); mb=me.getY(); flicker=false; repaint(); }

By: Amit Kumar Agrawal 256

The Smartest Way to Learn Java5

public void mouseMoved(MouseEvent me) { ma=me.getX(); mb=me.getY(); flicker=true; repaint(); } }); } public void paint(Graphics g) { Graphics amitScreen=null; if(flicker) { amitScreen=g; g=AmtBuff.getGraphics(); } g.setColor(Color.blue); g.fillRect(0,0,wt,ht); g.setColor(Color.red);

for(int i=0;i<wt;i+=gap)

g.drawLine(i,0,wt-i,ht);

for(int i=0;i<ht;i+=gap)

g.drawLine(0,i,wt,ht-i);

g.setColor(Color.green);

g.drawString("Press mouse for double buffer",48,ht/2);

g.setColor(Color.yellow);

g.fillOval(ma-gap,mb-gap,gap*2+1,gap*2+1);

if(!flicker)

{

amitScreen.drawImage(AmtBuff,5,5,null);

}

}

public void update(Graphics g)

{

paint(g);

}

}

By: Amit Kumar Agrawal 257

The Smartest Way to Learn Java5

c:\jdk1.5.0\bin>edit Amt092.html

</HTML> <HEAD>

<title>Amit Kumar Agrawal Image testing program</title>

</HEAD>

<BODY>

<hr>

<applet code="Amt092.class" width=250 height=250>

</applet>

<hr>

</BODY>

</HTML>

The output of the above program is:

The program is run when we double click on the Amt092.html document or by opening the Amt092.html on any browser (Internet Explorer or Netscape Navigator) then click on the applet body and then only we can access perfect output of the above program and got the result as shown in the picture. Then if we move

By: Amit Kumar Agrawal 258

The Smartest Way to Learn Java5

the star mark with help of mouse gradually we get double buffer class flicker free image.

Program :

/* program to show the use of MediaTracker*/import java.util.*;import java.applet.*;import java.awt.*;

public class Amt093 extends Applet implements Runnable{ MediaTracker amitTrack; int Amttrk; int frame_rate=4; int current_img=0; Thread motor; static final int MAXIMAGES=10; Image img[]=new Image[MAXIMAGES]; String NAME[]=new String[MAXIMAGES]; boolean stopfg; public void init(){ amitTrack=new MediaTracker(this); StringTokenizer str=new StringTokenizer(getParameter("img"),"+"); while(str.hasMoreTokens() && Amttrk <= MAXIMAGES){ NAME[Amttrk]=str.nextToken(); img[Amttrk]=getImage(getDocumentBase(),NAME[Amttrk]+".gif"); amitTrack.addImage(img[Amttrk],Amttrk); Amttrk++; } }

public void paint(Graphics g){ String loadMe=""; int dncnt=0;

for(int i=0;i<Amttrk;i++){ if(amitTrack.checkID(i,true)){ dncnt++; loadMe+=NAME[i]+" "; } }

Dimension dd=getSize(); int w=dd.width; int h=dd.height;

By: Amit Kumar Agrawal 259

The Smartest Way to Learn Java5

if(dncnt==Amttrk) { frame_rate=1; Image i=img[current_img++]; int iw=i.getWidth(null); int ih=i.getHeight(null); g.drawImage(i,(w-iw)/2,(h-ih)/2,null); if(current_img>=Amttrk) current_img=0; }

else

{ int x=w*dncnt/Amttrk; g.setColor(Color.black); g.fillRect(0,h/3,x,16); g.setColor(Color.white); g.fillRect(x,h/3,w-x,16); g.setColor(Color.black); g.drawString(loadMe,15,h/2); }}

public void start() { motor=new Thread(this); stopfg=false; motor.start(); }

public void stop() { stopfg=true; }

public void run() { motor.setPriority(Thread.MIN_PRIORITY); while(true) { repaint(); try { Thread.sleep(1000/frame_rate); } catch(Exception e) {} if(stopfg)

By: Amit Kumar Agrawal 260

The Smartest Way to Learn Java5

return; } }}

c:\jdk1.5.0\bin>edit Amt093.html

</HTML> <HEAD> <title>Amit Kumar Agrawal Image testing program</title> </HEAD> <BODY> <hr> <applet code="Amt093.class" width=700 height=750> <param name="img" value="algodata+alice+amit+clone+globe+HotJava-16+I_PUBL~1+IMAGE002+IMAGE004+IMAGE008"> </applet> <hr> </BODY></HTML>

Program :

/* program to show the use of MemoryImageSource

*<applet code="Amt094" width=450 height=450>

</applet>*/

import java.applet.*;

import java.awt.*;

import java.awt.image.*;

public class Amt094 extends Applet

{

Image img;

public void init()

{

Dimension d=getSize();

int w=d.width;

By: Amit Kumar Agrawal 261

The Smartest Way to Learn Java5

int h=d.height;

int pixels[]=new int[w*h];

int i=0;

for(int y=0;y<h;y++) { for(int x=0;x<w;x++) { int r=(x^y)&0Xff;

int g=(x*2^y*2)&0Xff;

int b=(x*4^y*4)&0Xff;

pixels[i++]=(220<<29)|(r<<19)|(g<<9)|b;

} } img=createImage(new MemoryImageSource(w,h,pixels,0,w)); } public void paint(Graphics g) { g.drawImage(img,0,0,this); }}

The output of the above program is.

The output of the program is shown by the help of Appletviewer.

C:\jdk1.5.0\bin>appletviewer Amt094.java

By: Amit Kumar Agrawal 262

The Smartest Way to Learn Java5

Program :

/* program to show the use of PixelGrabber*<applet code=Amt095 height=200 width=100> <param name="img" value=alice.gif> </applet>*/

import java.awt.*;import java.applet.*;import java.awt.image.*;

public class Amt095 extends Applet{ Dimension d; int iw,ih; Image img; int pixels[]; int w,h; int hist[]=new int[256]; int max_hist=0; public void init() { d=getSize(); w=d.width;

By: Amit Kumar Agrawal 263

The Smartest Way to Learn Java5

h=d.height; try { img=getImage(getCodeBase(),getParameter("img")); MediaTracker tr=new MediaTracker(this); tr.addImage(img,0); tr.waitForID(0); iw=img.getWidth(null); ih=img.getHeight(null); pixels=new int[iw*ih]; PixelGrabber pigg=new PixelGrabber(img,0,0,iw,ih,pixels,0,iw); pigg.grabPixels(); } catch(Exception er) {}

for(int i=0;i<iw*ih;i++) { int p=pixels[i]; int r=0xff&(p>>16); int g=0xff&(p>>8); int b=0xff&(p); int y=(int)(.33*r+.56*g+.11*b); hist[y]++; } for(int i=0;i<256;i++) { if(hist[i]>max_hist) max_hist=hist[i]; } }

public void update() {}

public void paint(Graphics g) { g.drawImage(img,0,0,null); int x=(w-256)/2; int lasty=h-h*hist[0]/max_hist; for(int i=0;i<256;i++,x++) { int y=h-h*hist[i]/max_hist; g.setColor(new Color(i,i,i)); g.fillRect(x,y,1,h); g.setColor(Color.red); g.drawLine(x-1,lasty,x,y); lasty=y;

By: Amit Kumar Agrawal 264

The Smartest Way to Learn Java5

} }}

The output of the above program is.

The output of the above program in Applet Viewer is given in the picture and the command pass for the Applet Viewer is given below.

C:\jdk1.5.0\bin>appletviewer Amt095.java

The output of the command supply you the output as shown in the figure, the figure shows the picture of Alice and then it plot a histogram on the same picture this what we can get after run the above program.

Program :

By: Amit Kumar Agrawal 265

The Smartest Way to Learn Java5

/* progra m toshow a tiled image *//*<applet code="Amt096.class" width=160 height=160> <param name="img" value="monalisa.gif"> </applet>*/import java.awt.*;import java.applet.*;import java.awt.image.*;

public class Amt096 extends Applet{ Image img; Image cell[]=new Image[4*4]; int iw,ih; int tw,th; public void init() { try { img=getImage(getDocumentBase(),getParameter("img")); MediaTracker t=new MediaTracker(this); t.addImage(img,0); t.waitForID(0); iw=img.getWidth(null); ih=img.getWidth(null); tw=iw/4; th=ih/4; CropImageFilter f; FilteredImageSource fis; t=new MediaTracker(this); for(int y=0;y<4;y++) { for(int x=0;x<4;x++) { f=new CropImageFilter(tw*x,th*y,tw,th); fis=new FilteredImageSource(img.getSource(),f); int i=y*4+x; cell[i]=createImage(fis); t.addImage(cell[i],i); }} t.waitForAll(); for(int i=0;i<32;i++) { int si=(int)(Math.random()*16); int di=(int)(Math.random()*16); Image tmp=cell[si]; cell[si]=cell[di]; cell[di]=tmp; }}

By: Amit Kumar Agrawal 266

The Smartest Way to Learn Java5

catch(Exception er) {} } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { for(int y=0;y<4;y++) { for(int x=0;x<4;x++) { g.drawImage(cell[y*4+x],x*tw,y*th,null); } } }}

the output of the above program is:

By: Amit Kumar Agrawal 267

The Smartest Way to Learn Java5

Program :

The program to show the use Thread Racing.

import java.awt.Graphics;import java.awt.Color;

public class AmitRacer extends java.awt.Canvas implements Runnable{ private short fPosition=0; private String fName; static private final short kNumberOfSteps=1000; TSuspendable fAncestor; public AmitRacer(String theName, TSuspendable theAncestor) { fName=new String(theName); fAncestor=theAncestor; } public AmitRacer(String theName) { fName=new String(theName); fAncestor=null; } public synchronized void paint(Graphics g) { g.setColor(Color.black); g.drawLine(0,getSize().height/2,getSize().width,getSize().height/2); g.setColor(Color.red); g.fillOval(fPosition*getSize().width/kNumberOfSteps,0,15,getSize().height); } public void run() { while(fPosition<kNumberOfSteps) { fPosition++; repaint(); try { Thread.currentThread().sleep(10); if(fAncestor!=null) { synchronized(fAncestor) {

By: Amit Kumar Agrawal 268

The Smartest Way to Learn Java5

if(fAncestor.isSuspended()) fAncestor.wait(); } } } catch(InterruptedException e) { System.err.println("Thread "+fName+" interrupted."); System.exit(1); }} System.out.println("Thread "+fName+" has finished the race."); } public static void main(String argv[]){ java.awt.Frame theFrame=new java.awt.Frame("one Racer"); AmitRacer aRacer=new AmitRacer("Test"); theFrame.setSize(400,200); theFrame.add(aRacer,java.awt.BorderLayout.CENTER); theFrame.show(); aRacer.paint(theFrame.getGraphics()); theFrame.pack(); aRacer.run(); System.exit(0); }}

the output of the above program is:

By: Amit Kumar Agrawal 269

The Smartest Way to Learn Java5

then it display a message on the screen that is:

Thread Test has finished the race.The above program will run we have to make first TSuspendable.java file.

C:\jdk1.5.0\bin>edit TSuspendable.java

public interface TSuspendable{ public boolean isSuspended();}

The TSuspenadable.java file is then compiled then only the compilation of the

AmitRacer.java file can be possible.

File Input/Output:

The Java I/O classes and Interfaces:

By: Amit Kumar Agrawal 270

The Smartest Way to Learn Java5

Classes:

BufferInputStream FileWriter PipedInputStreamBufferedOutputStream FilterInputStream PipedOutputStreamBufferedReader FilterOutputStream PipedReaderBufferedWriter FilterReader PipedWriterByteArrayInputStream FilterWriter PrintWriterByteArrayOutputStream InputStream PrintStreamDataInputStream ObjectInputStream RandomAccessFileDataOutputStream ObjectOutputStream StreAmtokenizerFilePermission OutputStream StringWriterFileReader OutputStreamWriter WriterStringReader

Interfaces:

DataInput FilenameFilter ObjectOutputDataOutput ObjectInput ObjectStreamConstantsExternalizable ObjectInputValidation SerializableFileFilterFile:

Most of the java.io operate on streams, the File class does not operate on file handling task. It deals directly with the files and the files system. This means the File class does not specify how information, data can be retrieved from the stored file. A File object is used to manipulate the information associated with a disk file.

Files are primary source and destination for the data within many programs. Although there are severe restrictions on their use within Applets for security reasons, files are still a central resource for storing persistent and shared information. A directory in Java is treated simply as a File with one additional property a list of filenames that can be examined by the list () method.

The following constructer can be used to create a File Objects:

File(String directoryPath)File(String directoryPath, String filename)File(File dirObj, String filename)

By: Amit Kumar Agrawal 271

The Smartest Way to Learn Java5

File(URL urlObj)

Here directory path is the path name of the file, filename is the object specifies a directory, and urlObj is a URL object that describes a file. The fourth constructer was added by Java 2, version 1.4.e.g.:File f1=new File("/");File f2=new File("/","autoexec.bat");File f3=new File(f1,"autoexec.bat");

If you need to output character, use rather than an Output Stream:

By: Amit Kumar Agrawal 272

The Smartest Way to Learn Java5

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

Different Methods for File Handling and its Description:

By: Amit Kumar Agrawal 273

The Smartest Way to Learn Java5

Methods Description

void deleteOnExit() Removes the file associated with the invoking object when the Java Virtual Machine terminates.

boolean isHidden() Return true if the invoking file is hidden otherwise it return false.

boolean setLastModified(long millisec) Sets the time stamp on the invoking file to that specified by millisecond from January 1,1970, coordinated Universal Time(UTC).

boolean setReadOnly() Sets the invoking file to read-only.

InputStream:

int available() Returns the number of bytes of the input currently available for reading.

void close() Closes the input source. Further read attempts will generate an IOException.

void mark() Places a mark at the current point in the input stream that will remain valid until numbyte bytes are read.

boolean markSupported() Returns true if mark()/reset() are supported by the invoking stream.

int read() Returns an integer representation of the next available byte of input. –1 is returned when the EOF is encountered.

int read(byte buffer[], int offset, Attempts to read up to numbytes bytes into buffer starting at buffer[offset], returning the number of bytes successfully read. –1 is returned when EOF is encountered.

void reset() Resets the input pointer to the previously set mark.

By: Amit Kumar Agrawal 274

int numbytes)

The Smartest Way to Learn Java5

Methods Description

long skip(long numbytes) Ignores(that is, skips) numbytes bytes of

input, returning the number of bytes

actually ignored.

OutputStream:

void close () Closes the output stream. Further, write

attempts will generate an IOException.

void flush () Finalizes the output state so that any

buffer are cleared. That is, it flushes the

output buffers.

void write (int b) Writes a single byte to an output stream.

Note that the parameter is an int, which

allows you to call write() with

expressions without having to cast them

back to byte.

void write(byte buffer[]) Writes a complete array of bytes to an

output stream.

void write(byte buffer[], int offset, Writes a subrange of numbytes bytes

from the array buffer, beginning at

buffer[offset].

By: Amit Kumar Agrawal 275

The Smartest Way to Learn Java5

FileReader:

abstract void close() Closes the input source. Further read attempts will generates an IOException.

void mark(int numchar) Places a mark at the current point in the input stream that will remain valid until numchar characters are read.

boolean markSupported() Returns true if mark()/reset() are supported on this stream.

int read() Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the EOF is encountered.

Methods Description

abstract int read(char buffer[], Attempts to read up to numChars character into buffer starting at buffer[offset], returning the number of characters successfully read. –1 is returned if EOF is encountered.

boolean ready() Returns true if the next input request will not wait. Otherwise, it returns false.

void reset() Resets the input pointer to the previously set mark.

long skip(long numChars) Skips over numChars characters of input, returning the number of characters actually skipped.

By: Amit Kumar Agrawal 276

int offset, int numChars) int offset, int numChars)

The Smartest Way to Learn Java5

FileWriter:

abstract void close() Closes the output stream. Further write attempts will generates an IOException.

abstract void flush() Finalizes the output state so that any

buffers are cleared. That is, it flushes the

output buffers.

void write() Writes a single character to the invoking

output stream. Note that the parameter is

an int, which allows you to call write

with expressions without having to cast

them back to char.

void write(char buffer[]) Writes a complete array of characters to

the invoking output stream.

abstract void write(char buffer[], Writes a sub-range of numChars

characters from the array buffer,

beginning at buffer[offset] to the

invoking output stream.

void write(String str) Writes str to the invoking output stream.

void write(String str, int offset, Writes a sub-range of numChars

characters from the array str, beginning

at the specified offset.

By: Amit Kumar Agrawal 277

int offset, int numChars)

int numChars)

The Smartest Way to Learn Java5

Methods Description

ObjectOutput:

void close() Closes the invoking stream. Further write attempts will generates an IOException.

void flush() Finalizes the out state so that any buffer are cleared. That is, it flushes the output buffers.

void write(byte buffer[]) Writes an array of bytes to the invoking stream.

void write(byte buffer[], int offset, Writes a sub-range of numBytes bytes from the array buffer, beginning at buffer[offset].

void write(int b) Writes a single byte to the invoking stream. The byte written is the low-order byte of b.

void writeObject(Object obj) Writes object obj to the invoking stream.

ObjectOutputStream:

void close() Closes the invoking stream. Further write attempts will generates an IOException.

By: Amit Kumar Agrawal 278

int numBytes)

int offset, int numChars) int offset, int numChars)

The Smartest Way to Learn Java5

void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers.

void write(byte buffer[]) Writes an array of bytes to the invoking stream.

void write(byte buffer[], int offset, Writes a sub-range of numBytes bytes from the array buffer, beginning at buffer[offset].

void write(int b) Writes a single byte to the invoking stream. The byte written is the low-order byte of b.

void writeBoolean(boolean b) Writes a boolean to the invoking stream.

void writeByte(int b) Writes the bytes to the invoking stream. The byte written is the low-order byte of b.

Methods Description

void writeBytes(String str) Writes the bytes representing str to the invoking stream.

void writeChar(int c) Writes a char to the invoking stream.

void writeChars(String str) Writes the characters in str to the invoking stream.

void writeDouble(double d) Writes a double to the invoking stream.

void writeFloat(float f) Writes a float to the invoking stream.

void writeInt(int i) Writes a int to the invoking stream.

void writeLong(long l) Writes a long to the invoking stream.

void writeObject(Object obj) Writes obj to the invoking stream.

By: Amit Kumar Agrawal 279

int numBytes)

The Smartest Way to Learn Java5

void writeShort(int i) Writes a short to the invoking stream.

ObjectInput:

int available() Returns the number of bytes that are now

available in the input buffer.

void close() Closes the invoking stream. Further read attempts will generates an IOException.

int read() Returns an integer representation of the next available byte of input. –1 is returned when EOF is encountered.

void read(byte buffer[]) Attempts to read up to buffer. Length

bytes into buffer, returning the number

of bytes that were successfully read. –1

is returned when the EOF is

encountered.

void read(byte buffer[], int offset, Attempts to read up to numBytes bytes

into buffer starting at buffer[offset],

returning the number of bytes that were

successfully read. –1 is returned if EOF

is encountered.

void readObject() Reads an object from the invoking

stream.

By: Amit Kumar Agrawal 280

int numBytes)

The Smartest Way to Learn Java5

long skip(long numBytes) Skips numBytes bytes in the invoking

stream, returning the number of

characters actually skipped.

Methods Description

ObjectInputStream:

int available() Returns the number of bytes that are now available in the input buffer.

void close() Closes the invoking stream. Further read attempts will generates an IOException.

int read() Returns an integer representation of the next available byte of input. –1 is returned when EOF is encountered.

int read(byte buffer[], int offset, Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes that successfully read. –1 is returned if EOF is encountered.

boolean readBoolean() Reads and returns a boolean from the invoking stream.

byte readBytes() Reads and returns a byte from the invoking stream.

char readChar() Reads and returns a char from the invoking stream.

double readDouble() Reads and returns a double from the invoking stream.

By: Amit Kumar Agrawal 281

int numBytes)

The Smartest Way to Learn Java5

float readFloat() Reads and returns a float from the invoking stream.

int readInt() Reads and returns a int from the invoking stream.

Methods Description

long readLong() Reads and returns a long from the invoking stream.

final Object readObject() Reads and returns a Object from the invoking stream.

short readShort() Reads and returns a short from the invoking stream.

int readUnsignedByte() Reads and returns an Unsigned byte from the invoking stream.

int readUnsignedShort() Reads and returns an Unsigned short from the invoking stream.

void readFully(byte buffer[]) Reads buffer, length bytes into buffer. Returns only when all bytes have been read.

void readFully(byte buffer[], Reads numBytes bytes into buffer starting at buffer[offset]. Returns only when numbyte have been read.

Different Constructer for different type of classes:

FileInputStream:

By: Amit Kumar Agrawal 282

int offset, int numBytes) int offset, int numChars)

The Smartest Way to Learn Java5

FileInputStream(String filepath)

FileInputStream(Filoe fileobj)

They can throw FileNotFoundException. Here the filepath is the full path to the

file. And the fileobj is the File object that dwscribes the file.

FileOutputStream:

FileOutputStream(String filepath)

FileOutputStream(Filoe fileobj)

FileOutputStream(String filepath, boolean append)

FileOutputStream(Filoe fileobj, boolean append)

They can throw FileNotFoundException or a SecuriityException. Here the filepath

is the full path to the file. And the fileobj is the File object that dwscribes the file. If

append is true then the file is open in append mode. The fourth constructer is added

by the Java 2, version 1.4.x onwards

ByteArrayInputStream:

ByteArrayInputStream(byte array[])

ByteArrayInputStream(byte array[], int start, int numBytes)

Here array is the input source. The second constructer creates an Inputstream from

a subset of your byte array that begins with the character at the index specified by

start and is numByte long.

By: Amit Kumar Agrawal 283

The Smartest Way to Learn Java5

ByteArrayOutputStream:

ByteArrayOutputStream()ByteArrayOutputStream(int numBytes)Here in the first constructer a buffer creates 32 bytes. In the second, a buffer is created with a size that is equal to that the size specified numByte.

Filtered Byte Stream:

FilterOutputStream(OutputStream os)FilterInputStream(InputStream is)

Buffered Byte Stream:

BufferedInputStream

BufferedInputStream(InputStream inputStream)BufferedInputStream(InputStream inputStream, int bufSize)

The first constructer creates a buffered stream using a default size. In the second one the size of the buffer is passed in bufSize.

BufferedOutputStream

BufferedOutputStream(OutputStream outputStream)BufferedOutputStream(OutputStream outputStream, int bufSize)

The first constructer creates a buffered stream using a 512 bytes size. In the second one the size of the buffer is passed in bufSize.

PushbackInputStream

PushbackInputStream(InputStream inputStream)

PushbackInputStream(InputStream inputStream, int numBytes)

By: Amit Kumar Agrawal 284

The Smartest Way to Learn Java5

Beyond the familiar methods of InputStream, PushbackInputStream provides unread().

void unread(int ch)void unread(byte buffer[])void unread(byte buffer[], int offset, int numChars)

SequenceInputStream

SequenceInputStream(InputStream first, InputStream second)SequenceInputStream(Enumeration streamEnum)

PrintStream

PrintStream(OutputStream outputStream)PrintStream(OutputStream outputStream, boolean flushOnNewline)

RandomAccessFile

RandomAccessFile(File fileObj, String access)RandomAccessFile(String filename, String access)

Here both of the constructer throws FileNotFoundException. FileObj specifies the name pf the file to open as a file object. The filename is the name of the file. In the both cases the access determines the mode of opening.

FileReader

FileReader(String filepath) FileReader(File fileObj)

FileWriter

FileWriter(String filepath)

FileWriter(File fileObj)

FileWriter(String filepath, boolean append)

By: Amit Kumar Agrawal 285

The Smartest Way to Learn Java5

FileWriter(File fileObj, boolean append)

Here the all constructer may throw IOException.

CharArrayReader

CharArrayReader(char array[])CharArrayReader(char array[], int start, int numChars)

CharArrayWriter

CharArrayWriter()CharArrayWriter(int numChars)

BufferedReader

BufferedReader(Reader inputStream)BufferedReader(Reader inputStream, int bufSize)

BufferedReader

BufferedWriter(Writer outputStream)BufferedWriter(Writer outputStream, int bufSize)

PushbackReader

PushbackReader(Reader inputStream)

PushbackReader(Reader inputStream, int bufSize)

PushbackReader provides unread().

void unread(int ch)void unread(byte buffer[])void unread(byte buffer[], int offset, int numChars)

PrintWriter

By: Amit Kumar Agrawal 286

The Smartest Way to Learn Java5

PrintWriter(OutputStream outputStream)

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

PrintWriter(Writer outputStream)

PrintWriter(Writer outputStream, boolean flushOnNewline)

Externalizable

void readExternal(ObjectInput inStream)

void writerExternal(ObjectOutput outStream)

Here both of the constructer throws IOException and ClassNotFoundException.

ObjectOutputStream

ObjectOutputStream(OutputStream outStream)

Here it throws IOException.

ObjectInputStream

ObjectInputStream(InputStream inStream)

Here it throws IOException and StreamCorruptedException.

Program :

/* Program for Demonstrate the File.*/

import java.io.*;

class Amt101{ static void p(String s) { System.out.println(s); } public static void main(String args[])

By: Amit Kumar Agrawal 287

The Smartest Way to Learn Java5

{ File f1=new File("/jdk1.5.0/COPYRIGHT"); System.out.println("\nAmit Is Going To Represent The File Detail

Of a File"); System.out.println("\n"); p("File Name: "+f1.getName()); p("Path : "+f1.getAbsolutePath()); p("Parent : "+f1.getParent()); p(f1.exists() ? "File Exists" : "Doesn't Exist"); p(f1.canWrite() ? "Can Writable" : "Can not Writable"); p(f1.canRead() ? "Can Readable" : "Can not Readable"); p("File Last Modified: "+f1.lastModified()); p("File size : "+f1.length()+ " Bytes."); }}

The output of the above program is:

Program :

//Demonstrate FileInputStream

import java.io.*;class Amt098{ public static void main (String args[])throws Exception { int size; InputStream f=new FileInputStream("Amt098.java"); System.out.println("Total Available Bytes: "+

(size=f.available())); int n=size/40; System.out.println("First " + n + " bytes of the file one read()

at atime"); for(int i=0;i<n;i++) { System.out.print((char)f.read()); }

By: Amit Kumar Agrawal 288

The Smartest Way to Learn Java5

System.out.println("\nStill Available: "+f.available()); System.out.println("Reading the next " + n + " with one

read(b[])"); byte b[]=new byte[n];

if(f.read(b)!=n) { System.err.println("Couldn't read"+n+" bytes."); }

System.out.println(new String(b,0,n)); System.out.println("\n Still avilable : "+(size=f.available())); System.out.println("skipping half of remaining bytes with

skip()");

if(f.read(b,n/2,n/2)!=n/2) { System.err.println("couldn't read "+n/2+" bytes."); }

System.out.println(new String(b,0,b.length)); System.out.println("\nStill avialable : "+f.available()); f.close();

}}

The output of the program is:

By: Amit Kumar Agrawal 289

The Smartest Way to Learn Java5

Program :

/* Demonstrate unread()*/import java.io.*;

class Amt099{ public static void main(String args[])throws IOException{ String s="if(a==4) a=0;\n"; byte buf[]=s.getBytes(); ByteArrayInputStream in=new ByteArrayInputStream(buf); PushbackInputStream f=new PushbackInputStream(in); int c; while((c=f.read())!=-1){ switch(c){ case '=': if((c=f.read())=='='){ System.out.print(" .eq. ");} else{ System.out.print(" <- "); f.unread(c);} break; default: System.out.print((char)c); break; }}}}

The output of the program is:

Program :

//demonstrate Filereader.

import java.io.*;

class Amt100{ public static void main(String args[])throws Exception { FileReader afr=new FileReader("Amt100.java"); BufferedReader abr=new BufferedReader(afr); String str; while((str=abr.readLine())!=null) { System.out.println(str);

By: Amit Kumar Agrawal 290

The Smartest Way to Learn Java5

} afr.close(); }}

The output of the above program is:

Program :

/* Program to demonstrate the FileWriter*/

import java.io.*;

class Amt102{ public static void main(String args[])throws Exception { String AmitSource="Amit Kumar Agrawal is The Programmer of this Program"+ "\n This program is to demonstrate the FileReader"+ "\n\nNow Amit Ends The File"; char buffer[]=new char[AmitSource.length()]; AmitSource.getChars(0,AmitSource.length(),buffer,0); FileWriter f0=new FileWriter("Amit007.txt"); for(int i=0;i<buffer.length;i+=2) { f0.write(buffer[i]); } f0.close();

FileWriter f1=new FileWriter("Amit008.txt");

By: Amit Kumar Agrawal 291

The Smartest Way to Learn Java5

f1.write(buffer); f1.close();

FileWriter f2=new FileWriter("Amit009.txt"); f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4); f2.close(); }}

The output of the above program is it creates three text file named Amit007.txt, Amit008.txt, Amit009.txt and store the data as shown below:

Amit007.txt

Ai ua gaa sTePorme fti rgaTi rga st eosrt h ieedro mtEd h ie

Amit008.txt

Amit Kumar Agrawal is The Programmer of this Program This program is to demonstrate the FileReader

Now Amit Ends The File

Amit009.txt

Reader

Now Amit Ends The File

Program :

/* Program to demonstrate the FileWriter data entry through keyboard*/

import java.io.*;

class Amt103{ public static void main(String args[])throws Exception {

String ASource;

By: Amit Kumar Agrawal 292

The Smartest Way to Learn Java5

System.out.println("Amit Say's Enter the data For the file : "+args[0]); System.out.println("Press ENTER after entering all data\n");

DataInputStream in=new DataInputStream(System.in); FileWriter f0=new FileWriter(args[0]); try {

ASource=(in.readLine()); char buffer[]=new char[ASource.length()];

ASource.getChars(0,ASource.length(),buffer,0);

for(int i=0;i<buffer.length;i++) { f0.write(buffer[i]); } f0.close(); } catch (Exception e) {} }}

The output of the above program is given below:

This program file creates a file in the name of amit.txt and contains the text Amit Kumar Agrawal. As shown in the output.

Improving the performance of your Java program's:

There is a rule thumb among Java developers: A JDK 1.0/1.2/1.3 Java program runs about 20 times slower than an equivalent native application. Before we erase our copy of javac in shock, let me ask a question: is that that level of performance a problem? Modern computers (Pentium 4, 1.9 GHz processor and so on) are so fast that in fact, many machine are running the idle loop nearly all the time. I just spent few minutes pounding my Windows XP Home Edition machine fairly hard – opening files, editing text, and running a java compile. The figure given below is

By: Amit Kumar Agrawal 293

The Smartest Way to Learn Java5

show the results – the only task I could find that pounded the CPU was compiling Java (That's what it was doing as this screen shot was taken, which accounts for the fact that the processor is 79% utilized as the Windows XP task manager shows)

The machine configuration is given below:

*****************************************************************************HCL Systems Analyser (c) 1999 HCL InfoSystems Ltd., PEG/PMO Ver 2.0-28/11/02**************************************************************************** Computer : AT (ID=FCh / Subm=01h / Vers=0) BIOS date / name : 05/07/03 Award Modular BIOS v6.00PG : i845G-6A69VM4VC-00 : W6714IMS V1.2 050703 VIVION-S HCL Infosystems Limited : CPU type : Intel(R) Pentium(R) 4 CPU 1.90G Clock speed : 1900.0 MHz Multipl=19 FSB=400 MHz QDR (100 MHz) Main memory : 640 kB (A0000h) Used=69 kB Free=571 kB Extended memory : 121792 kB Display adapter : VGA in mode 03h Memory (Vesa info) : 8000 kB Monitor (PS/2 info) : VGA Color display (Vert=70.0 Hz / Horiz=31.47 kHz) Logical drive(s) : 4 named A: to D: Floppy disk drive(s) : 1 0/A:1.44 MB (80T 2H 18S) : 0/B:1.44 MB (80T 2H 18S) Hard disk drive(s) : 80a/C:37004 MB (33692 MB) HCL Fat32 Active : 80b/D: 2092 MB ( 895 MB) HCL Fat32

ATA info : (39121MB / 8257MB 16383T 16H 63S) SAMSUNG SP4002H Parallel ports : 1) Lpt1=0378h IRQ=7 ECP DMA=3 Fifo=16 Byte E4 Serial ports : 1) Com1=03F8h Chip=16550A 2400,N,8,1 00 Keyboard : BIOS=83/84 key Keyboard=XT : 8042 Controller=yes Intercept=yes INT16/9=no

This Machine is Loaded With WINXP Home Edition With SP1 & Msplus.This Machine is Loaded With Vivion-S MBD driver.This Machine is Loaded With NIS2003. This Machine is Loaded With Latest Navup def.This Machine is Loaded With MSUPDATES.This Machine is Loaded With Hcl Expert Series s/w. This Machine is Loaded With Monitor drivers.This Machine is Loaded With Valufon Dialer.This Machine is Loaded With Beanstalk DEMO s/w.

This Machine is Loaded With DACE Modem Driver.This Machine is Loaded With 16xSam DVDROM Driver.This Machine is Loaded With BE100 KBD Driver.

----------------------+-------------------------------------------------------- MIDI : port=0330h Machine Serial No:503PAQ018415 FT Done By : HCL System designer.

The task manager shows the performance of the Java program at time of compiling the program:

By: Amit Kumar Agrawal 294

The Smartest Way to Learn Java5

It is better to be slow rather than Fast and wrong:

For a certain class of software designer, performance is a major issue, this class is small – much smaller than most people think. For such a project, address performance concerns as part of the design activity. For the rest of the programmer they concentrate on the quality, and tune the code later.

Now I describe two approaches to increase the performance of your Java programs:

Writing more efficient Java source code. Executing Java bytecodes more efficiently.

I will cover first what slows the Java code down and how to write around it. Later in this section titled" Taking Advantage of Just-In-Time Compilers" and "Introducing Hotspot," I will talk little about JIT and sun's new JVM, based on project HotSpot.

Do not compare the overall performance with raw code speed:

By: Amit Kumar Agrawal 295

The Smartest Way to Learn Java5

Overall performance is only loosely relates to the raw speed of your code because your program might spend time waiting for user input or other I/O. while you're working on improved performance, you're not working on other issues, such as code quality or new features, both of which might allow the user to get his work done more quickly. Get your raw code speed into an acceptable range, and then make tradeoff decisions to decide whether its better tweak the speed or work on something else.

Designing for Adequate Performance:

During the analysis activity, determine "how fast is fast enough" for this application. We will use this information later, during code tuning, to decide when to quit code tuning and go to work on other aspects of the product. If we know that, this combination of hardware and application is going to demand high performance, consider taking the following steps:

Consider changing the hardware- With hardware costs low and getting lower, adding a faster processor, more RAM, or a wider data bus can often give you the performance you need without requiring tricky, hard – to – maintain code.

Define a time and memory budget, and allocate it to each method. Pay attention to data structures. Determine early on whether our program's performance is limited by the

speed of the processor, the size of the memory, or the speed of the I/O. if we

spend our more time waiting on the drive to deliver data, no amount of

conventional code tuning will have a significant impact on performance. (In

that case, we most want to explore the benefit of a cache, use buffered I/O,

or optimize the layout of the data on the hard drive.)

Optimizing Hot Spots in your Code:

Most software follows the "Pareto Principle" also know as 80/20 rules. This rule

state that "Twenty percent of your code often accounts for eighty percent of your

performance problems." In a study, by Barry Boehm of TRW ("ISM- Industrial

By: Amit Kumar Agrawal 296

The Smartest Way to Learn Java5

Software Metrics Top Ten List," IEEE (Institute of Electrical and Electronics

Engineers) software 4, no. 9: 84-85) found that twenty percent of a program's

routine consumes eighty percent of execution time. Another famous study ("An

Empirical Study of FORTRAIN programs" by Donald Knuth, software- Practice

and experience 1:105-33) revealed that less than four percent of a program usually

accounts for more than fifty percent of its runtime.

The following procedure can give a big performance boost to your code.

Optimizing Hot Spots:

Once your code passes a functional test, run a

profiler to tell you where the code is spending most

of its time.

Make small optimizations and return the optimizer.

If your optimizations are having the opposite effect

than you intended, analyze this behavior and

change your code.

Continue to profile and optimize until your code

meets your performance objectives.

Measuring Program speed:

For some ideas on how to measure the speed of your program, look at the JMark 2.0 benchmark developed by PC Labs. You will find it at www.zdnet.com/vlabs/index.html.

Know what you are measuring:

By: Amit Kumar Agrawal 297

The Smartest Way to Learn Java5

Make sure that your profiler measures only the execution time of your program. Some poorly written utilities do not work correctly in a multitasking or multi-user environment- you will end up optimizing code that is already efficient.

Here is list of time waster we should avoid the same if we think that performance is important:

Avoid unnecessary disk I/O-If your computer has enough memory, do not write to disk files. If you design cries out for external storage, use a ByteArrayStream and save the data in memory. As rule of thumb, RAM is around 1,000 times faster than that of hard drive.

Avoid unnecessary screen I/O-An innocent write to a java.awt.TextArea can have a big impact on program performance. In general, command-line I/O is faster than GUI I/O, and no I/O is faster still.

Put I/O in its own thread- remember when you do I/O, that is read and write blocks. Move the I/O to its own Thread, give it lower PRIORITY, and make sure that it yield() or sleep() each time through the run() loop so that user thread doesn't starve.

Avoid floating point operation-If we target machine doesn't have a floating point coprocessor or a floating point processor built into the CPU, floating point operations will expensive. Look for an alternative, such as fixed-point arithmetic.

Stay in real RAM-Use your operating system utilities to see whether you are paging. UNIX's vmstat utility or Windows NT's Task manager will tell you this. If our program spends most of its time in swapping pages, it will not run quickly. If it is possible, add RAM. Failing that attempt to redesign the program to use caches more efficiently.

Wrap your streams in BufferedRedear() or BufferedInputStream(). Wherever possible remove common code from loops. For example change

for(int i=0; i<Limi; i++){ if(theType == kFirst){ processTheFirstType(i); } else{

processTheSecondType(i);

} }

By: Amit Kumar Agrawal 298

The Smartest Way to Learn Java5

change the given code to:

if(theType == kFirst) { for(int i=0; i<Limi; i++)

processTheFirstType(i); } else { for(int i=0; i<Limi; i++)

processTheSecondType(i); }

The redesigned code avoids doing an unnecessary comparison inside the loop.

Remember that the second and third clauses of a for loop are also "In the loop":

Instead of

for( int i=0; i<myString.length(); i++)

write int theLength=myString.length(); for( int i=0; i< theLength; i++)

Caution: Be careful that the saved value does not need to change

If you save a value that depends upon, say, i, and i changes, your saved value is

worthless. Be sure that common expressions are truly common; rebuild them

when necessary.

Caution: Be sure that two loops are compatible before fusing them

By: Amit Kumar Agrawal 299

The Smartest Way to Learn Java5

The two loops must have the same index limits to be fused. To keep your code

maintainable, make sure that there's a practical reason the index limits are likely

to stay the same on these two loops.

Where possible, eliminate tests in loops.

While(i<theAmit.length) { if(theAmit[i++]==theDesireValue) break; }

In general, we can get better performance if we replace

Multiplication with Addition.

Exponentiation with Multiplication.

Trigonometric routines with Trigonometric identities.

Double precision floating point number with single precision floating

point numbers.

Floating point numbers with fixed-point numbers.

Long integers with shorter integers.

Integer multiplication and division by multiplies of two with left and

right shift operators.

Arrange tests in order of likelihood-If we have to test three tests and one of three is far more likely then other two then place it in first.

Some versions of the JVM deal with arrays-within-arrays better than other.

Array access can be computationally expensive.

By: Amit Kumar Agrawal 300

The Smartest Way to Learn Java5

If you have to search large, complex data structure repeatedly, build an index.

If you have a hot spot that includes an API call, consider whether you may able to substitute a less expensive API call.

If you have a hot spot that includes an API call, consider whether you might be able to substitute a custom method for the API call.

Building Multidimensional Arrays in Java

Java does not support multidimensional Arrays, but you can get the same effect by building arrays of arrays.

JVM's Evolution to Optimization

The first generation of the JVM was essentially an interpreter, with all the performance problems associated with that technology. The second generation is based on JIT (Just-In-Time) compilation, and is part of nearly every Java environment today. The third generation-HotSpot-is based on adaptive optimization, and promises to change everything we know about Java optimization.

Always avoid thread synchronization. Avoid doing garbage collection. Minimize object allocation. Write method to avoid extra method invocations. Use static and final methods to help the compiler optimize.

Taking Advantage of Just-In-Time Compiler:

Just-In-Time (JIT) compiler runs on the end-user's machine, and is integrated into

the JVM. The first time the JIT compiler sees piece of code, it passes the code

through to the interpreter in the JVM, but it also compiles it and saves the native

code. If the program loops back through this section and the JIT compiler sees this

code again, it does not bother to run the interpreter-it just executes the native code.

By: Amit Kumar Agrawal 301

The Smartest Way to Learn Java5

One way of looking at JIT compiler is to think of them like conventional

optimizing compiler.

Java2 SDK Includes JIT Compilers

In addition to the environments shown in the table given below, the Java 2 SDK includes JIT compilers for Windows95, Windows NT, Windows XP, and Solaris system etc.

PC Magazine Picks "JVM of the year"

The 1998"Editors Choice" for JVM was Microsoft's JVM for Windows. They write, "for the second year in a row, Microsoft has produced the fastest and most reliable Java. Implementation available." Read more at www.pcmag.com/features/java98.html.

Operating System JVMVersion JIT

Mac OS 8 Microsoft Internet Explorer 4.0 YesMac OS 8 Mac OS Runtime for Java 2.0 YesWindows 95/NT 4.0 Microsoft Internet Explorer 4.0 YesWindows 95/NT 4.0 Netscape Communicator 4.04 YesWindows 95/NT 4.0 Sun JDK 1.1.5 NoWindows 95/NT 4.0 Sun JDK with Win32 1.1.5 Yes

Performance packWindows 95/NT 4.0 Symantec visual cafe for 2.1 Yes

JavaOS/2 Warp 4.0 IBM Java for Wrap 1.1.4 YesSolaris 2.6 Microsoft Internet Explorer 4.0 No

PreviewSolaris 2.6 Netscape Communicator 4.04 NoSolaris 2.6 JDK 1.1.3 YesSolaris 2.6 JDK 1.1.5 NoSolaris 2.6 JDK with Native Threads Pack 1.1.5 No

By: Amit Kumar Agrawal 302

The Smartest Way to Learn Java5

Java 2 offers Native Threads in both Windows and Solaris

Sun has used Microsoft's native thread package to good effect. Starting in SDK 1.2/1.3, they also offer native threads on the Solaris versions of the SDK.

Allowing the Compiler to Compress Your strings

In order to take advantage of this new feature, your Strings must truly be identical. If you have two or more classes with similar Strings, consider making them identical so that the compiler can eliminate all but one copy.Introducing HotSpot The next generation of JVM from sun is codenamed project HotSpot. HotSpot relies on adaptive optimization-a two-step process that offers better optimization than even static optimization compilers offer. The following shows adaptive optimization works:

1. The JVM profiles the Java program as it runs and finds the critical "hot spots" where the program is spending most of its time.

2. The JVM uses runtime information (not available to a static compiler) as well as traditional optimization techniques in order to optimize the code on the fly.

In addition to adding adaptive optimization, Sun's designers included two new features in HotSpot:

An improved garbage collector. A performance breakthrough in thread synchronization.

Sun experts Java to run at the same speed as native code

The combination of adaptive optimization, improved garbage collection, and the

breakthrough in thread synchronization means that your users can enjoy the

benefits of platform-independent programs in Java without a performance

disadvantage relative to platform-specific code.

By: Amit Kumar Agrawal 303

The Smartest Way to Learn Java5

The Improved Garbage collection technique

Traditional garbage collectors run as a low-priority thread. When memory is low,

they must deal with large amount of data. This process may take time, during

which the program must not move any objects. The effect is that the garbage

collector locks the threads while it's running, effectively freezing the program.

The garbage collector in HotSpot having two components. For short-lived objects,

it will rely on scavenging mechanism that claims objects quickly-usually within a

few milliseconds. For longer-lived objects, it will employ incremental collection

that does not disrupt the running program.

The Sun's Thread synchronization advances

In the first generation of JVMs, thread synchronization was very expensive in

terms of computing time. JIT compilers can do little to improve synchronization,

through second-generation JVMs typically include native thread support, which

offers some improvement.

Why do traditional Optimization Not Give Big Performance Boosts? As we know object-oriented languages encourage you to write small, highly focused methods rather than big functions. This means that you have a large number of method invocations, which, in an object-oriented language like Java, means dynamic dispatch. This dynamic dispatch is slow, and becomes the bottleneck.

Using JNI to Optimize HotSpot

By: Amit Kumar Agrawal 304

The Smartest Way to Learn Java5

If we are not ready to give up the benefits of Java but have some hot spots that

resist further optimization, consider coding just those methods in a native language

such as C, C++. If you distribute our program (such as an Applet) on many

different platforms, we will need to write a different version of the library for each

platform, but that impact might be acceptable compared to impact of distributing

the entire executable in native code.

Use JNI (Java Native Interface) to add a native method to a Java program. By using

JNI, we can guarantee that Java binaries (Byte code file or .class files plush the

native library) will run on any JVM that runs on any platform. Our Java code will

continue to take advantages of any improvements. As HotSpot matures, we may

consider bringing your native methods back into Java.

JDBC (Java DataBase Connectivity)

The ambition of this section is to lay the groundwork for the Java Database Connectivity explaining the underlying concepts of Relational Database Management Systems. Understanding these concepts, facts and ruke is the key to be a successful Java database programmer. In my experience, just understanding how to handle the Java side of the problem is not enough. It is important to understand how relational databases work and to have a reasonable command of Structured Query Language (SQL) before you can do any serious Java database programming.

Understanding Relational Database Management Systems:

A database is a structured collection of meaningful information stored over a period

of time in machine-readable form for subsequent retrieval. This definition is fairly

intuitive and says nothing about structure or methodology. By this definition, any

file or collection of files can be considered a database. However, to be useful in

practical terms, a database must form part of a system that provides for the

By: Amit Kumar Agrawal 305

The Smartest Way to Learn Java5

management of the data it contains. Seen from this perspective, a database must be

more than a mere collection of files. It must be a complete system.

A practical database management system combines the physical storage of data with the capability to manage and interact with the data. Such a system must support the following tasks:

Creation and management of a logical data structure Data entry and retrieval Manipulation of the data in a logical and consistent manner Storage of data reliably over a significant period of time

Prior to the development of modern relational databases, a number of different

approaches were tried. In many cases, these were simple, proprietary datastorage

systems designed around a specific application. However, large corporations,

notably IBM, were marketing more general solutions.

The Relational Model

The biggest step torward database technology was the development of the relational database model. The relational database derives from work done in the late 1960s by E.F. Codd, a mathematician at IBM. His model is based on the mathematics of set theory and predicate logic. In fact, the term relational has its roots in the mathematical terminology of Codd's paper entitled "A relational model of data for large shared data banks," which was published in Communications of the ACM, Vol. 13, No. 6, June 1970, pp. 377-387. In this paper, Codd uses the terms relation, attribute , and tuple where more common programming usage refers to table, column, and row, respectively.

The importance of Codd's ideas is such that the term "database" generally refers to a relational database. Similarly, in common usage, a Database Management System, or DBMS, generally means a Relational Database Management System. The terms are used interchangeably in this section, and throughout the discusion. Codd's model covers the three primary requirements of a relational database: structure, integrity, and data manipulation. The fundamentals of the relational model are as follows:

A relational database consists of a number of unordered tables.

By: Amit Kumar Agrawal 306

The Smartest Way to Learn Java5

The structure of these tables is independent of the physical storage medium used to store the data.

The contents of the tables can be manipulated using nonprocedural operations that return tables.

Codd's Rules (For Relational Database)

1. Information Rule: All data in a relational database must be explicitly represented at the logical level as values in tables and in no other way.

2. Guaranteed Access Rule: Every data element must be logically accessible through the use of a combination of its primary key name, primary key value, table name, and column name.

3. Systematic Nulls Rule: The RDBMS is required to support a representation of missing and inapplicable information that is systematic, distinct from all regular values, and independent of data type.

4. Dynamic Catalog Rule: The database description or catalog must also be stored at the logical level as tabular values. The relational language must be able to act on the database design in the same manner in which it acts on data stored in the structure.

5. Sub Language Rule: An RDBMS must support a clearly defined datamanipulation language that comprehensively supports data manipulation and definition, view definition, integrity constraints, transactional boundaries, and authorization.

6. View Update Rule: Data can be presented to the user in different logical combinations called views. All views must support the same range of data-manipulation capabilities as are available for tables.

7. High Level Language Rule: An RDBMS must be able to retrieve relational data sets. It has to be capable of inserting, updating, retrieving, and deleting data as a relational set.

8. Physical Data Independence Rule: Data must be physically independent of application programs.

9. Logical Data Independence Rule: Applications software must be independent of changes made to the base tables.

10.Integrity Independence Rule: Integrity constraints must be specified separately from application programs and stored in the catalog. It must be possible to change such constraints when appropriate without unnecessarily affecting existing applications.

11.Distribution Independence Rule: Existing applications should continue to operate successfully when a distributed version of the DBMS

By: Amit Kumar Agrawal 307

The Smartest Way to Learn Java5

isintroduced or when existing distributed data is redistributed around the system.

12.Non Subversion Rule: If an RDBMS has a low-level (record-at-a-time) interface, that interface cannot be used to subvert the system or to bypass a relational security or integrity constraint.

Open Database connectivity is the driver developed by Microsoft.

ODBC (Open DataBase Connectivity) provides a common API( Application Programming Interface) to interact with any database whichhas an ODBC service providers implements written in Native API that can be used in your application.

Java never directly support ODBC because of some problems:

Application becomes vendor dpendent. The application has to use JNI to interact with native library which may

cause serious problems in platform independent features of Java.

Java Database Connectivity (JDBC) is a standard developed by Sun microsystem.JDBC is a specification given by Sun microsystem and standard followed by X/Open SAG (SQL Access Group) CLI (Call Level Interface) to interact with any Database.

JDBC API lets the programmer to invoke SQL commands from Java programming language methods. The JDBC API provides Database independent connectivity between Java Application and wide range of databases.

JDBC technology allows:

Manage transaction. Executes stored procedures. Perform connection and authentication to a database server. Inspects and modifies the results from select statements.

By: Amit Kumar Agrawal 308

The Smartest Way to Learn Java5

JDBC core API (Jave SQL package)

Establish a connection to a database.

Getting database detail.

Getting driver detail.

Maitening local transaction.

Getting results through resultset.

Executing Querys.

Preparing pre-compiled SQL queries.

Executing procedures and function.

JDBC Extension API

Resources objets with distributed transaction management support. Connection pooling.

By: Amit Kumar Agrawal 309

The Smartest Way to Learn Java5

Type of JDBC Driver

1. Type 1 :- JDBC-ODBC Bridge.

2. Type 2 :- Java Native API Driver.

3. Type 3 :- Net Protocol Driver.

4. Type 4 :- Java Native Protocol Driver.

Type 1 :-

ARCHITECTURE

By: Amit Kumar Agrawal 310

The Smartest Way to Learn Java5

This type of driver is designed to convert the JDBC result call to ODBC call and

ODBC response call to JDBC call. JDBC uses this interface in order to

communicate with the database. However ODBC binary code must be installed on

each client machine that uses this driver. This driver uses a configured Data-source.

ADVANTAGE:-

i. Simple to use.ii. JDBC-ODBC Driver comes with JDK.

DIS - ADVANTAGE:-

i. More number of users between the application & database.ii. Slower than Type-2.

Where to USE:-

This type of drivers are generally used at the development time to test your

applications.

Setting environment to use this driver:-

i. Software:

By: Amit Kumar Agrawal 311

The Smartest Way to Learn Java5

ODBC libraries has to be installed.ii. Class path:

C:\Program Files\Java\JDK1.5.0\jre\lib\rt.jar

How to use this Driver:-

1. Driver class name – sun.jdbc.odbc.JdbcOdbcDriver2. Driver URL - jdbc.odbc:<DSN>

(NB: - DSN – Data Source Name)

Type 2 :-

ARCHITECTURE

This driver converts the JDBC call given by the application to a database specific native call by using JNI (Java Native Interface).

ADVANTAGE

Faster then Type-1 driver.

DIS-ADVANTAGE

By: Amit Kumar Agrawal 312

The Smartest Way to Learn Java5

Preferably work in LAN because network server name must be configured in the client.

Database specific native client library has to be istalled in the client machine.

Where to USE

This type of driver are suitable to be used in server side application. Example of this type of driver OCI8 (Oracle call interface) for oracle.

Setting environment:-

Software: - Oracle client software has to be installed in client machine.

Classpath:- %ORACLE HOME%\ora81\bin

How to use this driver

Driver class Name :- oracle.jdbc.driver.OracleDriverDriver URL :- jdbc:oracle:oci8:@TNSName

TNS names of oracle is available in oracle installed folder –

%ORACLE_HOME%\ora81\network\admin\tnsnames.ora

Type 3 :-

ARCHITECTURE

By: Amit Kumar Agrawal 313

The Smartest Way to Learn Java5

This type of drivers responsibility is to convert JDBC call to net protocol or middle

ware listener dependent format and re-direct the client request to the middleware

listener and middle ware listener inturn uses Type-1, Type - 2 or Type – 4 driver to

interact with Database.

ADVANTAGE

In the absence of database vendor supplied driver we can use this driver. Suitable for applet clients to connect database.

DIS-ADVANTAGE

From client to server communication this driver uses java libraries, but from

server to database connectivity this driver uses native libraries, hence

number of API conversion decrease performance.

Where to USE

This type of driver is suitable for applets when connecting to database. Example of

this type of driver IDS server driver available for most of databases.

Setting environment:-

Software: - IDS SoftwareClass path: - c:\IDSServer\classes\jdk1.6drv.jar

How to use this driver

Driver class Name: - ids.sql.IDSDriverDriver URL : - jdbc:ids||localhost:12|conn?dsn=” “

DSN name must be created in serverDSN

By: Amit Kumar Agrawal 314

The Smartest Way to Learn Java5

Type 4 :-

ARCHITECTURE

This type of driver converts JDBC call to a Database defined native protocol.

ADVANTAGE

No client native libraries required to be installed bin client machine. Comes with most of the database.

DIS-ADVANTAGE

Slower in execution.

Where to USE

This type of driver are suitable to be used with server side application, client side java application and applets.

Example of this type of driver: Thin Driver for oracle

Setting environment:-

Classpath:- %ORACLE_HOME%\ora81\jdbc\lib\classes111.zip

By: Amit Kumar Agrawal 315

The Smartest Way to Learn Java5

How to use this driver

Driver class Name :- oracle.jdbc.driver.OracleDriverDriver URL :- jdbc:oracle:thin:@Hostname:

<Port Number>:<sid> 1521 orcl

Interfaces available in java.sql package:-

java.sql.DriverManagerjava.sql.Driverjava.sql.connectionjava.sql.statementjava.sql.PreparedStatementjava.sql.CallableStatementjava.sql.ResultSet

public class Interface extends connection{

//Connection c=new Connection(); // Error in executionConnection c=new Interface(); // Correct statement

}

Connection Management:-

Driver Manager:

This class provides the functionalities that are necessary for managing one or more database Driver. Each driver inturn lets u connect to a specific database.

Driver:

This interface abstracts the vendor specific connection protocol. You may find implementations of this interface from database vendors as well as third party database driver vendors.

By: Amit Kumar Agrawal 316

The Smartest Way to Learn Java5

Connection

This interface abstracts most of the interaction with the database using connetion, you can send SQL statements to the database and read the result of execution.

Database Access:-

Statement: This interface lets you execute SQL statements over the underlying conection and access the results.

Prepared statement: This interface allowing for parameterized SQL statements. Parameterized SQL statements includes parameter maker as “?”, which can be replaced with actual values later on.

Callable statement: This interface lets you execute stored procedures.

By: Amit Kumar Agrawal 317

The Smartest Way to Learn Java5

Result set: This interface abstracts results of executing SQL selet statements. This interface provides methods to access results row by row. You can use this interface to access results row by row. You can use this interface to access various fields in each row.

Data Type:

Array: SQL type arrayBLOB: Bit Long OBjectCLOB: Character Long OBjectDate: SQL type date.Time: SQL type TimeTimeStamp: SQL type TimeRef: SQL Types REFStructs: SQL structure typesTypes: Set of constant integers.

Steps of JDBC program:

Load Driver : Class for database connectivityClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Create ConnectionCreate StatementExecute SQL statementIterate ResultSetClose Connection

ResultSet contains some predefined methods:

getInt(int i);getInt(String S);getFloat(float f);getFloat(String S);getDate(int i);getDate(String S);next();close();getMetaData();

By: Amit Kumar Agrawal 318

The Smartest Way to Learn Java5

Statement: createStatement();Prepared Statement: preparedStatement();Callable Statement: prepareCall();

To INSERT data in a table:

String s1=”INSERT INTO emp VALUES(1,’Amit’);

Statement s=null;

s.executeUpdate(s1);

NB: executeUpdate() method returns an integer indicating the number of rows affected.

To execute SELECT statement:

Statement s=con.createStatement();String s1=”SELECT * FROM emp”;ResultSet rs=s.executeQuery(s1);

In-Order to create a Bi-Directional ResultSet

Statement s1=con.createStatement( ResultSet TYPE_SCROLL_SENSITIVE,

ResultSet CONCUR_READ_ONLY);String s2=”SELECT * FROM dept”;ResultSet rs=s1.executeQuery(s2);System.out.println(rs.getRow());//TO DISPLAY THE ROWrs.next();//TO MOVE NEXT RECORDrs.next();//TO MOVE NEXT RECORDrs.next();//TO MOVE NEXT RECORD

Scrollable ResultSet

There are two types of Scrollable ResultSets are available:

By: Amit Kumar Agrawal 319

The Smartest Way to Learn Java5

1. Scroll.SENSITIVE2. Scroll.INSENSITIVE

Scroll.SENSITIVE

This ResultSet will be able to pickup the changes that are made to the database after opening the ResultSet.

Scroll.INSENSITIVE

This ResultSet will not pickup the changes that are made after opening the ResultSet. Some of the JDBC drivers does not pickup the changes even if you use Scroll.SENSITIVE ResultSet. To get fresh data with SENSITIVE ResultSet we most use rs.refreshRow() method.

Stored Procedures:

A piece of code in a language like PLSQL and stored inside the database is called as stored procedures. The popular technique used to separate the business logic from the presentation logic is to implement the business logic using stored procedure.

Most of the database server supports the concept of stored procedures. Different databases supports different language from implementing the stored procedure. For example, PLSQL is supported by ORACLE, TSQL is supported by MSSQL server etc.

By: Amit Kumar Agrawal 320

The Smartest Way to Learn Java5

CallableStatement stmt=con.prepareCall(“{Call MyProcedure}”);

Step - 1 create a callable statement

Step – 2 call the method execute()

When this method is called JDBC secure ask the database server to execute the stored procedure.

st.execute();

CREATE OR REPLACE PROCEDURE MyProcedure(Phone IN Number,Name IN varchar2) as

BEGININSERT INTO MyTab VALUES(Phone,Name);

END MyProcedure;

Java code invoke the procedure MyProcedure

import java.sql.*;public class Demo{

Public static void main(String arg[]) throws Exception{

By: Amit Kumar Agrawal 321

The Smartest Way to Learn Java5

Class.forName(“Oracle.jdbc.drivers.OracleDriver”);Connection con=DriverManager;getConnection(“jdbc.oracl:thin@localhost:1521:orcl”,”scott”,”tiger”

);CallableStatement st=con.prepareCall(“{call

MyProcedure(?,?)});st.setInt(1,1234);st.setString(2,”Amit”);st.registerOutParameter(1,Types.NUMBER);st.registerOutParameter(2,Types.VARCHAR);System.execute();System.out.println(st.getInt(1)+”\n”+st.getString(2));

}}

Another Program

import java.sql.*; // imports the JDBC core packagepublic class JdbcDemo{

public static void main(String args[]){

int qty;float cost;String name;String desc;// SQL Query stringString query = "SELECT Name,Description,Qty,Cost FROM

Stock";try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the DriverConnection con = DriverManager.getConnection

("jdbc:odbc:Inventory");// get a connectionStatement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(query); // execute querywhile (rs.next())// parse the results

By: Amit Kumar Agrawal 322

The Smartest Way to Learn Java5

{name = rs.getString("Name");desc = rs.getString("Description");qty = rs.getInt("Qty");cost = rs.getFloat("Cost");System.out.println(name+", "+desc+"\t:

"+qty+"\t@ $"+cost);}con.close();

}catch(ClassNotFoundException e){e.printStackTrace();}catch(SQLException e){

e.printStackTrace();}

}}

registerOutParameter(<Parameter Index>,Types.TYPE);

Create a CallableStatement. Set the value of input parameter. Register the output data types. Call execute() method. Get the values of output parameter.

To DELETE the last row

ResultSet rs=st.executeQuery(s1);rs.last();rs.absolute(4);DriverManager.setLogStream(System.out);rs.deleteRow();con.close();

To UPDATE a row

ResultSet rs=st.executeQuery(s1);rs.first();rs.updateString(“ename”,”AMIT SINGHAL”);rs.updateString(“address”,”MAITREEVIHAR”);DriverManager.setLogStream(System.out);

By: Amit Kumar Agrawal 323

The Smartest Way to Learn Java5

rs.updateRow();con.close();

PROGRAM

import java.sql.*;public class JdbcTest{

public static void main(String args[])throws Exception{Connection con=null;Statement st=null;ResultSet rs=null;try{

Class.forName("oracle.jdbc.driver.OracleDriver");con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");st=con.createStatement();rs=st.executeQuery("SELECT * FROM emp");while(rs.next()){

int x=rs.getInt("Sal");String y=rs.getString("EName");System.out.println("SALARY IS : "+x+" NAME IS : "+y);

}rs.close();st.close();con.close();

}catch(Exception e){

e.printStackTrace();}

}

By: Amit Kumar Agrawal 324

The Smartest Way to Learn Java5

}

PROGRAM

import java.sql.*;import java.awt.*;import java.awt.event.*;class Cont extends Frame implements ActionListener{

Frame f;TextField t1,t2,t3;Button b1,b2;Cont(){

f=new Frame("DEMONSTRATE");t1=new TextField(20);t2=new TextField(20);t3=new TextField(20);b1=new Button("OK");b2=new Button("CANCEL");f.setLayout(new FlowLaout());f.add(t1);f.add(t2);f.add(t3);f.add(b1);f.add(b2);f.setSize(300,3000);f.setVisible(true);b1.addActionListener(this);b2.addActionListener(this);

}public void actionPerformed(ActionEvent ae){

try{Connection con=null;Statement st=null;ResultSet rs=null;Class.forName("oracle.jdbc.driver.OracleDriver");Con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");st.createStatement();

By: Amit Kumar Agrawal 325

The Smartest Way to Learn Java5

if(ae.getSource()==b1){

st.executeUpdate("INSERT INTO empVALUES('amit','admin','user'));

System.out.println("ISERTED THE DATASUCCESSFULLY");

}else{

System.out.println("VISIT US AGAIN");}

}catch(Exception e){

e.printStackTrace();}con.close();st.close();

}}

public class JDBC01{

public static void main(String args[]){

Cont cn=new Cont();}

}

PROGRAM

import java.sql.*;public class CallTest{

public static void main(String args[])throws Exception{

Connection con=null;Statement st=null;ResultSet rs=null;PreparedStatement ps=null;

By: Amit Kumar Agrawal 326

The Smartest Way to Learn Java5

CallableStatement cs=null;try{

Class.forName("sun.jdbc.odbc.JdbcOdbcdriver");con=DriverManager("jdbc.odbc:amit","scott","tiger");st=con.craeteStatement();cs=con.preparedCall("{CALL getSal(?,?)}");cs.setint(1,10);cs.register.OutParameter(2,Types.INTEGER);cs.execute();int x=cs.getInt(2);System.out.println(x);con.close();st.close();

}catch(Exception e){}}}

PROGRAM

import java.sql.*;

public class CallTest01{

public static void main(String args[])throws Exception{

Connection con=null;Statement st=null;ResultSet rs=null;PreparedStatement ps=null;CallableStatement cs=null;try{

Class.forName("sun.jdbc.odbc.JdbcOdbcdriver");con=DriverManager("jdbc.odbc:amit","scott","tiger");st=con.craeteStatement();cs=con.preparedCall("{CALL getSal(?,?)}");cs.setint(1,10);cs.register.OutParameter(2,Types.INTEGER);cs.execute();int x=cs.getInt(2);System.out.println(x);

By: Amit Kumar Agrawal 327

The Smartest Way to Learn Java5

con.close();st.close();

}catch(Exception e){}

}}

Batch File

Set PATH= C:\Program Files\Java\JDK1.6.0\BIN; C:\ORACLE\Ora81\BIN;C:\ORACLE\ora81\jdbc\lib\classes111.zip;

Set CLASSPATH = C:\Program Files\Java\JDK1.6.0\BIN;C:\ORACLE\Ora81\BIN; C:\ORACLE\ora81\jdbc\lib\classes111.zip;

TRANSACTION

In some application, we might like to group together a series of statements that need either all to succeed or to fail. A group of SQL operations constitue one unit of work. When multiple statements are executed in a single transaction, all operation can be commited or rolled back.

void setAutoCommit( Boolean auto)void commit()throws SQLExceptionvoid rollback()

In oreder to begin transaction, we call setAutoCommit(false);

try{//BEGIN A TRANSACTIONCon.setAutoCommit(false);Statement st;st=con.createStatement();st.executeUpdate(“INSERT INTO order VALUES(12,25000);if(){

St.execute(“INSERT INTO oreder VALUES( )”);con.commit();

By: Amit Kumar Agrawal 328

The Smartest Way to Learn Java5

}else{

con.rollback();}

}catch(Exception e){}

Scrollable & Updateable ResultSet

A ResultSet object is created by executing a statement was by default forwardonly

scrollable. We traverse ResultSet using next(). next() returns false when the last

record is reached.

Scrollable :

ResultSet objects are Scrollable, This ResultSet has the ability to move the cursor backword also supports positioning of the cursor at a particular row in the ResultSet.

TYPE_FORWARD_ONLY: Supports forward scrolling. TYPE_SCROLL_INSENSITIVE: Supports scrolling in both direction. TYPE_SCROLL_SENSITIVE: Supports sensitive to update make to the

data after the ResultSet has been populated.

Updatable ResultSet :

By default ResultSet are readonly. When a ResultSet is updated, the update operation also updates the original data corresponding to the ResultSet.

COCUR_READONLY CONCUR_UPDATABLE

javax.sql.package

JDBC DataSource:

By: Amit Kumar Agrawal 329

The Smartest Way to Learn Java5

javax.sqql package provides a replacement for DriverManager class. DataSource is an interface is used to create database connection.

Instead of explicitly loading the driver manager clases in the run time from the client application, we used a centralized JNDI service lookup to obtain a java,sql.DataSource object.

Instead of using java.sql.Drivermanager class, we use a javax.sql.DataSource interface, which provides facilities for getting database connection.

Methods:

Connection getConnection()int getLoginTimeOut()void setLoginTimeOut(int seconds)PrintWriter getLogWriter()void setLogWriter(LogWriter c)

The driver or application server implements the javax.sql.DaraSource interface.

By: Amit Kumar Agrawal 330

The Smartest Way to Learn Java5

The application server creates an instance of the object implementing the javax.sql.DataSource interface and binds it with a logical name in the JNDI service.

The JDBC Application (Client) does a lookup in the JNDI service the object by implementing the DataSource interface.

The JDBC application (client) uses the DataSource object and obtains database connection. The DataSource implementation may use JDBC driver to retrieve a connection.

The JDBC application (client) uses the connection object for all its database access, using the standard JDBC API.

Creating the DataSource

XDataSource x=new XDataSource();try{

Context con=new InitialContext();Con.bind(“ “, x);

}Catch(NamingException ne){}Retrieving:

try{Context con=new InitialContext();DataSource data=(DataSource)con.lookup(“ “);

}catch(NamingException ne){}

By: Amit Kumar Agrawal 331

The Smartest Way to Learn Java5

JNDI (Java Naming and Directory Interface)

JNDI are designed to simplify access to the directory infrastructure used in the development of advanced network applications. Directories are a special type of databases that provide quick access to their data stores. A directory service is optimized for read access by using various indexing, caching and disk access technique.

The Lightweight Directories Access Protocol (LDAP) was developed in early 1980’s as standard directory protocol. JNDI can access LDAP. LDAP defines how clients should access data on the server, But LDAP does not specify how the data should be stored on the server. Data in LDAP is organized in a hierarchical tree, called as Directory Information Tree (DIT). CORBA (Common Object Request Brokers Architecture) is a language & platform independent architecture that enables distributed application, where an application on one machine can access a function of a different application located on a different machine as if it was calling on internal function. CORBA uses the CORBA object service to define the location of available objects. JNDI is very very important for the long term development of java. A key component of EJB technology is the ability to store & retrieve java objects on the network through JNDI. When objects are loaded on the network, we

By: Amit Kumar Agrawal 332

The Smartest Way to Learn Java5

want to be able to locate them quickly and a directory service enables very fast lookup and retrieval of data. Each directory service requires its own API.

By: Amit Kumar Agrawal 333

The Smartest Way to Learn Java5

JNDI API can be used to access the directory servers. There are so many directory servers are available in the market, some of the them are:

RMIRegistry MicroSoft Active Directory Server Novell Directory Server Domain Name Server (DNS) Light Weight Directoory Access Protocol (LDAP) Server NIS Plus Server of sun.

Directory server is same as database server we can manage (storing, removing, finding and modifying) the data using database server but we manage data using a directory server. Most of the directory servers are designed to managed less amount of data efficiently. Directory servers are used to develop an application that has to perform searching operation frequently. To access various directory servers we require different JNDI SPI (JNDI Service Provider Interface). JNDI SPI is a set of classes implementing the interfaces specified by java soft as a part of JNDI API. JNDI API is not a part of J2EE but it is the part of J2SE. In a directory server we

By: Amit Kumar Agrawal 334

The Smartest Way to Learn Java5

can organize the information by using a tree structure similar to how we organize the files in a file system. In case of a directory server the starting point is called asINITIAL CONTEXT

Under the initial context, we can create other context as well as stores the information or bind objects. In case of JNDI to deal with a directory server first we need to get the reference of initial context object. In JNDI we must use, a set of properties to get the initial context.

NB: If you run the program before running the block that contain initialcontext part of the program it will return

javax.naming.NoInitialContextException.

To create Sub Context

C1.createSubContext(“Interface”);C1.createSubContext(“Amit”);

import javax.naming.*;import java.util.*;public class JNDIDemo{

public static void main(String args[])throws Exception{

HashTable ht=new HashTable();

ht.put(Context.INITIAL_CONTEXT_FACTORY,

"weblogic.jndi.WLInitialContextFactory");

ht.put(Context.PROVIDER_URL,"http://localhost:7001");

ht.put(Context.SECURITY_PRINCIPAL,"admin");

ht.put(Context.SECURITY_CREDENTIALS,"interface");

Context c1=new InitialContext(ht);

System.out.println(ht);

}}

By: Amit Kumar Agrawal 335

The Smartest Way to Learn Java5

weblogic.jndi.WLInitialContextFactory :

It take care of the code to create object of type InitialContext. If you provide wrong user name or/ password or/ both, it throws Exception i.e. javax.naming.SecurityException. If you enter wrong port number, it throwsjava.net.ConnectionException.

To remove a SubContext we can use destorySubContext()

is.destorySubContext(“Amit”);

we will destroy the suncontext only if it is empty. If the context is not empty it throws an Exception i.e. javax.naming.ContextNotEmptyException.

To store information we use bind()

Integer i1,i2;String str;i1=new Integer(190);i2=new Integer(210);str=new String(“JAI SHREE RAM”);is.bind(“one”,i1);is.bind(“two”,i2);is.bind(“STORE”,str);

To remove any object from Context we use unbind()

is.unbind(one);

To search the object from Directory server.

Object o=is.lookUp(“two”);

How to create a DSN (Data Source Name)

Start – Setting – Control Panel – Administratie Tools – Data Sources Then it will

display a set of DSN and then press the [Add] button to create new DSN for the

system.

By: Amit Kumar Agrawal 336

The Smartest Way to Learn Java5

Then select the driver for the database that we want to access. E.g.: MS-Access, dBase, Paradox etc..

Then set a Data Source Name and may or may not provide a description for the DSN, but it is always better to set a description to know about the DSN.

Then select the Database by using [Select] button. By using [Advanced] button we can set a Username and Password to access

the database for secure access.

This is how we can create DSN

By: Amit Kumar Agrawal 337

The Smartest Way to Learn Java5

Here is some more JDBC program with a DSN “AKA” which is a DSN for Amit.mdb database, and a table Amit01.

Program – JdbcDemo

//SQL SELECT STATEMENT

import java.sql.*; // imports the JDBC core packagepublic class JdbcDemo{

public static void main(String args[]){

int Roll;String crs;String name;// SQL Query stringString query = "SELECT Name,Roll, Course FROM Amit01";try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the DriverConnection con =

DriverManager.getConnection("jdbc:odbc:AKA");// get a connectionStatement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(query); // execute querywhile (rs.next())// parse the results{

name = rs.getString("Name");crs = rs.getString("Course");Roll = rs.getInt("Roll");System.out.println("\n\nNAME :"+name+"\nROLL

:"+Roll+"\nCOURSE:"+crs);}con.close();

}catch(ClassNotFoundException e){

e.printStackTrace();}

By: Amit Kumar Agrawal 338

The Smartest Way to Learn Java5

catch(SQLException e){e.printStackTrace();}

}}

Program JdbcDemo01

//INSERT STATEMENT

import java.sql.*; // imports the JDBC core packageimport java.io.DataInputStream;public class JdbcDemo01{

public static void main(String args[]) {int Roll;String crs;String name;DataInputStream in=new DataInputStream(System.in);// SQL Query stringtry{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the DriverConnection con =

DriverManager.getConnection("jdbc:odbc:AKA");// get a connectionStatement stmt = con.createStatement();System.out.print("ENTER A NAME:");name = in.readLine();System.out.print("ENTER THE COURSE:");crs = in.readLine();System.out.print("ENTER THE ROLL:");Roll = Integer.parseInt(in.readLine());stmt.executeUpdate("INSERT INTO Amit01VALUES('"+name+"',"+Integer.toString(Roll)+",'"+crs+"')"); // execute querySystem.out.println("SuccsesFully Done");con.close();}

catch(ClassNotFoundException e){e.printStackTrace();}catch(SQLException e){

By: Amit Kumar Agrawal 339

The Smartest Way to Learn Java5

e.printStackTrace();}catch(Exception e){}}}

Program JdbcDemo02

//SQL SELECT STATEMENT WITH CONDITION

import java.sql.*; // imports the JDBC core package

public class JdbcDemo02{public static void main(String args[]){

int Roll;String crs;String name;// SQL Query stringString query = "SELECT Name,Roll, Course FROM Amit01 where

Roll<4";try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the DriverConnection con =

DriverManager.getConnection("jdbc:odbc:AKA");// get a connectionStatement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(query); // execute querywhile (rs.next())// parse the results{

name = rs.getString("Name");crs = rs.getString("Course");Roll = rs.getInt("Roll");System.out.println("\n\nNAME :"+name+"\nROLL

:"+Roll+"\nCOURSE:"+crs);

}con.close();}

catch(ClassNotFoundException e){e.printStackTrace();}

catch(SQLException e){e.printStackTrace();

}

By: Amit Kumar Agrawal 340

The Smartest Way to Learn Java5

}}

Program JdbcDemo03

//UPDATE STATEMENT

import java.sql.*; // imports the JDBC core packageimport java.io.DataInputStream;public class JdbcDemo03{

public static void main(String args[]){int Roll;DataInputStream in=new DataInputStream(System.in);

// SQL Query stringtry{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // load the DriverConnection con =

DriverManager.getConnection("jdbc:odbc:AKA");// get a connectionStatement stmt = con.createStatement();System.out.print("ENTER THE ROLL:");Roll = Integer.parseInt(in.readLine());stmt.executeUpdate("UPDATE Amit01 set Name='Mr.'+Name WHERE Roll="+Integer.toString(Roll)); // execute querySystem.out.println("UPDATED");con.close();

}catch(ClassNotFoundException e){

e.printStackTrace();}catch(SQLException e){

e.printStackTrace();}catch(Exception e){}

By: Amit Kumar Agrawal 341

The Smartest Way to Learn Java5

}}

Swings (A light weight GUI component set)

Swing in Java is a set of classes that provides powerful and flexible set of components that can be used in the replacement of AWT standard components. It is also a part of JFC (Java Foundation Class). Some of the general components include such as buttons, check boxes, and labels, Swing supplies several excitingadditions, including tabbed panes, scroll panes, trees, and tables. Even the components such as buttons have more capabilities in Swing as compare to the standard component. Due to this, many Java programmers use Swing while working with applets. AWT components are platformspecific whereas Swing components are not platformdependent. As swings are totally written in Java and, therefore, swings are platformindependent. The term lightweight is used to describe such elements. Although the Swing offer an alternatives to those components that are supplied by the AWT, it makes the swing to be understand upon the foundation of the AWT. Thus, a concrete understanding of the AWT is required to use Swing effectively. Now we will ready to see how Swing components can be used. In this section we have a tour of the Swing components and features that we’ll probably use in most of our Java projects. Each program in this section are specially design to make you understand the art of programming with Java Swing.

Some important disclosure before we goto the actual topic:

1. The Javadoc provided by java.sun.com have all the swing classes and methods but in this section we will discuss few of them.

2. All the naming conventions are quit easily guessable by any programmer (how to write and install a handler for a particular type of events).

3. Till the complition of this chapter you graduate to a GUI builder.

Diffrence of Swing with AWT components:

a. Swings are lightweight, Swings are with very few exceptions.

b. Swings allow a pluggable look and feel (PLAF).

By: Amit Kumar Agrawal 342

The Smartest Way to Learn Java5

c. AWT components use native code resources, this makes the same

heavyweight, but in the same time Swings are totally written in Java this

makes the swing more flexible and as well as platform independent.

A catalog to swing component:

All the component reside inside the javax.swing package, this package need to be imported before start programming in swing. Most of the classes in this package has a common prefix J (only those classes those are available in AWT).

JApplet, JButton, JCheckBox, JCheckBoxMenuItem, JColorChooser, JComboBox, JComponent, JDesktopPane, JDialog, JEditorPane, JFileChooser, JFormattedTextField, JFrame, JInternalFrame, JLabel, JLayeredPane, JList, JMenu, JMenuBar, JMenuItem, JOptionPane, JPanel, JPasswordField, JPopupMenu, JProgressBar, JRadioButton, JRadioButtonMenuItem, JRootPane, JSchrollBar, JSchrollPane, JSeparator, JSlider, JSpinner, JSplitPane, JTabbedPane, JTable, JTextArea, JTextField, JTextPane, JTogglebutton, JToolBar, JToolTip, JTree, JViewport, JWindow etc.

The MVC Connection: (Model View Controller)

Generally, every visual component is a composite of three distinct aspects:

This ensure the store of internal state in a set of class called model. Shows the data in a view (from the model). Change of data in the model in a controller (available set of controllers).

Use of component ensure that it is architect independent, it must contain all the mentioned component implicitly, This Model proven to be the effective architecture during these period.

By: Amit Kumar Agrawal 343

The Smartest Way to Learn Java5

Feature of swing: (Advantage of swing over AWT components)

a. Borders : we can set border in different styles around components by using setBorder method.

b. Graphics debugging: we can setup graphics debugging option with help of setDebuggingGraphicsOptions method.

c. Easy mouseless operation: The swings supports keystrokes to components.d. Tooltips: You can use the setTooolTipsText method of JComponent to provide

ToolTip to the swing components.e. Pluggable look and feel: You can set the appearance of applets and applications

to one of three standards looks: Windows, Motif(UNIX), or Metal(The standard swing look).

And many more …..

PROGRAM TO INTRODUCE YOU WITH JAVA SWING

//file: SwStrt.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;

By: Amit Kumar Agrawal 344

The Smartest Way to Learn Java5

public class SwStrt extends JComponent implements MouseMotionListener,ActionListener{

// Coordinates for the messageint X = 115, Y = 85;String theMessage;JButton theButton;// Current index into someColorsint clr;static Color[] someColors = { Color.black, Color.red,Color.green,

Color.blue, Color.magenta };public SwStrt(String msg){

theMessage = msg;theButton = new JButton("Change Color");setLayout(new FlowLayout( ));add(theButton);theButton.addActionListener(this);addMouseMotionListener(this);

}public void paintComponent(Graphics g){

g.drawString(theMessage,X,Y);}public void mouseDragged(MouseEvent e){

// Save the mouse coordinates and paint the message.X = e.getX( );Y = e.getY( );repaint( );

}public void mouseMoved(MouseEvent e){}public void actionPerformed(ActionEvent e){

// Did somebody push our button?

if (e.getSource( ) == theButton)

changeColor( );

}

By: Amit Kumar Agrawal 345

The Smartest Way to Learn Java5

synchronized private void changeColor( ){

// Change the index to the next color.

if (++clr == someColors.length)

clr = 0;

setForeground(currentColor( )); // Use the new color.

repaint( ); // Paint again so we can see the change.

}synchronized private Color currentColor( ){

return someColors[clr];}

public static void main(String[] args){

JFrame f = new JFrame("SWING STARTING PROGRAM");

// Make the application exit when the window is closed.

f.addWindowListener(new WindowAdapter( ){public void

windowClosing(WindowEvent we) { System.exit(0);}

});

f.setSize(300, 300);

f.getContentPane( ).add(new SwStrt("HELLO THIS IS AMIT"));

f.setVisible(true);

}}

By: Amit Kumar Agrawal 346

The Smartest Way to Learn Java5

This program is use full to demonstrate you the properties JButton, setLayout(), and ActionListener in swing programming. This program enable you to change the color of the message “HELLO THIS IS AMIT” by using the button ‘Change Color’.

//file: HelloJava.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class HelloJava extends JComponent implements MouseMotionListener, ActionListener, Runnable{

// Coordinates for the messageint messageX = 15, messageY = 95;String theMessage;JButton theButton;int colorIndex; // Current index into someColors.static Color[] someColors = { Color.black, Color.red,Color.green,

Color.blue, Color.magenta };boolean blinkState;public HelloJava(String message)

By: Amit Kumar Agrawal 347

The Smartest Way to Learn Java5

{theMessage = message;theButton = new JButton("Change Color");setLayout(new FlowLayout( ));add(theButton);theButton.addActionListener(this);addMouseMotionListener(this);Thread t = new Thread(this);t.start( );

}public void paintComponent(Graphics g){

g.setColor(blinkState ? getBackground() : currentColor( ));g.drawString(theMessage, messageX, messageY);

}public void mouseDragged(MouseEvent e){

messageX = e.getX( );messageY = e.getY( );repaint( );}

public void mouseMoved(MouseEvent e){}public void actionPerformed(ActionEvent e){

// Did somebody push our button?if (e.getSource( ) == theButton)changeColor( );

}synchronized private void changeColor( ){

// Change the index to the next color.if (++colorIndex == someColors.length)

colorIndex = 0;setForeground(currentColor( )); // Use the new color.repaint( ); // Paint again so we can see the change.

}synchronized private Color currentColor( ){

return someColors[colorIndex];

By: Amit Kumar Agrawal 348

The Smartest Way to Learn Java5

}public void run( ){

try{while(true){blinkState = !blinkState; // Toggle blinkState.repaint( ); // Show the change.Thread.sleep(500);}

} catch (InterruptedException ie) {}}public static void main(String[] args){

JFrame f = new JFrame("HelloJava4");// Make the application exit when the window is closed.f.addWindowListener(new WindowAdapter( ) {public void windowClosing(WindowEvent we) { System.exit(0); }

});f.setSize(300, 300);f.getContentPane( ).add(new HelloJava("Hello, I LOVE JAVAPROGRAMMING"));f.setVisible(true);

}}

By: Amit Kumar Agrawal 349

The Smartest Way to Learn Java5

In this program the text”Hello, I LOVE JAVA PROGRAMMING” blinking and when ever we click the button the color changes

//HotelMenu.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class HotelMenu extends JFrame{

public HotelMenu( ){

super("HOTEL MENU");setSize(200, 200);setLocation(200, 200);// create the DESI menuJMenu desi = new JMenu("DESI");desi.setMnemonic(KeyEvent.VK_U);desi.add(new JMenuItem("PAKHAL"));desi.add(new JMenuItem("DALMA"));desi.add(new JMenuItem("BHAJA"));JMenu hybrid = new JMenu("Hybrid");hybrid.add(new JMenuItem("PAKHAL"));hybrid.add(new JMenuItem("DALMA"));hybrid.add(new JMenuItem("BHAJA"));desi.add(hybrid);desi.addSeparator( );// do some fancy stuff with the Quit itemJMenuItem quitItem = new JMenuItem("Quit");quitItem.setMnemonic(KeyEvent.VK_Q);quitItem.setAccelerator(

KeyStroke.getKeyStroke(KeyEvent.VK_Q,Event.CTRL_MASK));

quitItem.addActionListener(new ActionListener( ) {public void actionPerformed(ActionEvent e) { System.exit(0); }});utensils.add(quitItem);// create the contiental menuJMenu conti JMenu("CONTINENTAL");

By: Amit Kumar Agrawal 350

The Smartest Way to Learn Java5

conti.setMnemonic(KeyEvent.VK_S);conti.add(new JCheckBoxMenuItem("GENERAL"));conti.add(new JCheckBoxMenuItem("SPECIAL"));conti.add(new JCheckBoxMenuItem("EXTRA", true));conti.add(new JCheckBoxMenuItem("ORDINARY"));// create the Cheese menuJMenu cheese = new JMenu("Chinese");cheese.setMnemonic(KeyEvent.VK_C);ButtonGroup group = new ButtonGroup( );JRadioButtonMenuItem rbmi;rbmi = new JRadioButtonMenuItem("Regular", true);group.add(rbmi);cheese.add(rbmi);rbmi = new JRadioButtonMenuItem("Extra");group.add(rbmi);cheese.add(rbmi);rbmi = new JRadioButtonMenuItem("Blue");group.add(rbmi);cheese.add(rbmi);// create a menu bar and use it in this JFrameJMenuBar menuBar = new JMenuBar( );menuBar.add(desi);menuBar.add(conti);menuBar.add(cheese);setJMenuBar(menuBar);

}public static void main(String[] args){

JFrame f = new HotelMenu( );f.addWindowListener(new WindowAdapter( ) {public void windowClosing(WindowEvent we) { System.exit(0);}});f.setVisible(true);

}}

By: Amit Kumar Agrawal 351

The Smartest Way to Learn Java5

This program will demonstrate the use of JMenuBar, JMenuItem, JFrame, JRadioButtonMenuItem, JCheckBoxMenuItem etc.

//PopUp.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class PopUp extends JFrame implements ActionListener{

JPopupMenu colorMenu;Component selectedComponent;public PopUp( ) {

super("PopUpColorMenu v1.0");setSize(100, 200);setLocation(200, 200);addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent e) { System.exit(0);}});

MouseListener mouseListener = new MouseAdapter( ){

public void mousePressed(MouseEvent e) { checkPopup(e); }

By: Amit Kumar Agrawal 352

The Smartest Way to Learn Java5

public void mouseClicked(MouseEvent e) { checkPopup(e); }

public void mouseReleased(MouseEvent e) { checkPopup(e); }

private void checkPopup(MouseEvent e){if (e.isPopupTrigger( ))

selectedComponent = e.getComponent( );colorMenu.show(e.getComponent(),e.getX(),e.getY(

));}}};final Container content = getContentPane( );content.setLayout(new FlowLayout( ));JButton button = new JButton("FIRST");button.addMouseListener(mouseListener);content.add(button);button = new JButton("SECOND");button.addMouseListener(mouseListener);content.add(button);button = new JButton("THIRD");button.addMouseListener(mouseListener);content.add(button);colorMenu = new JPopupMenu("Color");colorMenu.add(makeMenuItem("Red"));colorMenu.add(makeMenuItem("Green"));colorMenu.add(makeMenuItem("Blue"));getContentPane( ).addMouseListener(mouseListener);setVisible(true);

}public void actionPerformed(ActionEvent e){

String color = e.getActionCommand( );if (color.equals("Red"))

selectedComponent.setBackground(Color.red);else if (color.equals("Green"))

selectedComponent.setBackground(Color.green); else if (color.equals("Blue"))

selectedComponent.setBackground(Color.blue);}private JMenuItem makeMenuItem(String label){

By: Amit Kumar Agrawal 353

The Smartest Way to Learn Java5

JMenuItem item = new JMenuItem(label);item.addActionListener( this );return item;

}public static void main(String[] args){

new PopUp( );}

}

This program will demonstrate you JPopupMenu.

//PlaceOrder.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class PlaceOrder{

public static void main(String[] args){

JFrame f = new JFrame("ORDER BOOK");f.setSize(300, 150);

By: Amit Kumar Agrawal 354

The Smartest Way to Learn Java5

f.setLocation(200, 200);f.addWindowListener(new WindowAdapter( ) {public void windowClosing(WindowEvent we) { System.exit(0); }

});JPanel entreePanel = new JPanel( );final ButtonGroup entreeGroup = new ButtonGroup( );JRadioButton radioButton;entreePanel.add(radioButton = new JRadioButton("Special"));radioButton.setActionCommand("CHATNI");entreeGroup.add(radioButton);entreePanel.add(radioButton = new JRadioButton("MASALA"));radioButton.setActionCommand("MASALA");entreeGroup.add(radioButton);entreePanel.add(radioButton = new JRadioButton("Veggie", true));radioButton.setActionCommand("Veggie");entreeGroup.add(radioButton);final JPanel condimentsPanel = new JPanel( );condimentsPanel.add(new JCheckBox("PODINA"));condimentsPanel.add(new JCheckBox("DHANIA"));condimentsPanel.add(new JCheckBox("AAM ACHAR"));JPanel orderPanel = new JPanel( );JButton orderButton = new JButton("O R D E R");orderPanel.add(orderButton);Container content = f.getContentPane( );content.setLayout(new GridLayout(3, 1));content.add(entreePanel);content.add(condimentsPanel);content.add(orderPanel);orderButton.addActionListener(new ActionListener( ){

public void actionPerformed(ActionEvent ae){String entree

=entreeGroup.getSelection().getActionCommand( );System.out.println(entree + " sandwich");Component[] components =

condimentsPanel.getComponents( );for (int i = 0; i < components.length; i++){

JCheckBox cb = (JCheckBox)components[i];if (cb.isSelected( ))

System.out.println("With " + cb.getText( )); }}

By: Amit Kumar Agrawal 355

The Smartest Way to Learn Java5

});f.setVisible(true);

}}

This program will demonstrate you the use of JPanel, JButton, JRadioButton etc.

//SchrollDemo.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;class ImageComponent extends JComponent{

Image image;Dimension size;public ImageComponent(Image image){

this.image = image;MediaTracker mt = new MediaTracker(this);mt.addImage(image, 0);try{

mt.waitForAll( );}catch (InterruptedException e){

// error ...};size = new Dimension (image.getWidth(null),

By: Amit Kumar Agrawal 356

The Smartest Way to Learn Java5

image.getHeight(null));setSize(size);

}public void paint(Graphics g){

g.drawImage(image, 0, 0, this);}public Dimension getPreferredSize( ){

return size;}

}public class SchrollDemo{

public static void main(String[] args){

String filename = "Rhino.gif";if (args.length > 0)

filename = args[0];JFrame f = new JFrame("ScrollPane Demo");f.setSize(300, 300);f.setLocation(200, 200);f.addWindowListener(new WindowAdapter( ){public void windowClosing(WindowEvent e) { System.exit(0); }});Image image = Toolkit.getDefaultToolkit( ).getImage(filename);f.getContentPane( ).add(new JScrollPane(newImageComponent(image)));f.setVisible(true);

}}Output:

By: Amit Kumar Agrawal 357

The Smartest Way to Learn Java5

This program will demonstrate you the use of JComponent, JScrollPane etc.

//QueryProcesssor.java

/*PROGRA FOR THE QUERY PROCESSING WHERE THE QUERY SET INRUNTIME*/

import java.awt.*;import java.awt.event.*;import java.sql.*;import java.util.*;import javax.swing.*;

public class QueryProcesssor extends JFrame{

private JTextArea queryArea;public QueryProcesssor(){

super( "Query Processor" );String driver = "sun.jdbc.odbc.JdbcOdbcDriver";String url = "jdbc:odbc:AKA";

By: Amit Kumar Agrawal 358

The Smartest Way to Learn Java5

String query = "ENTER YOUR QUERY";try{

Class.forName( driver );Connection connection = DriverManager.getConnection(url);Statement statement = connection.createStatement();queryArea = new JTextArea( query, 3, 100 );queryArea.setWrapStyleWord( true );queryArea.setLineWrap( true );JScrollPane scrollPane = new JScrollPane(

queryArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );JButton submitButton = new JButton( "Submit Query" );Box box = Box.createHorizontalBox();box.add( scrollPane );box.add( submitButton );Container c = getContentPane();c.add( box, BorderLayout.NORTH );submitButton.addActionListener(

new ActionListener(){

public void actionPerformed( ActionEvent e ){

try{int l,j;String stq=queryArea.getText();String val=new String();l=stq.length();for(j=0;j<l && stq.charAt(j)!='';val=val+stq.charAt(j),j++);JFrame jf=new JFrame();Connection con =DriverManager.getConnection("jdbc:odbc:AKA");Statement st = con.createStatement();

if(val.equals("SELECT")){ResultSet rs=st.executeQuery(

By: Amit Kumar Agrawal 359

The Smartest Way to Learn Java5

queryArea.getText() );StringBuffer results = new StringBuffer();ResultSetMetaData mData =rs.getMetaData();int ColNum = mData.getColumnCount();for ( int i = 1; i <= ColNum; i++ ){

results.append(mData.getColumnName( i )+ "\t\t" );

}results.append( "\n\n" );while ( rs.next() ){for ( int i = 1; i <= ColNum; i++ )

results.append( rs.getObject( i )+"\t\t" );results.append("\n");

}st.close();con.close();JTextArea textArea = newJTextArea(results.toString() );Container container = getContentPane();

container.add( new JScrollPane( textArea ) );setVisible( true );

}else if(val.equals("UPDATE")){

st.executeUpdate( queryArea.getText() );ResultSet rs=st.executeQuery( "SELECTROLL, COURSE, NAME FROM Amit01");StringBuffer results = new StringBuffer();ResultSetMetaData mData =rs.getMetaData();int ColNum = mData.getColumnCount();results.append("DATA AFTER

UPDATION\n\n");for ( int i = 1; i <= ColNum; i++ ){

results.append(mData.getColumnName( i )+ "\t\t" );

By: Amit Kumar Agrawal 360

The Smartest Way to Learn Java5

}results.append( "\n\n" );while ( rs.next() ){

for ( int i = 1; i <= ColNum; i++ )results.append( rs.getObject( i )+"\t\t" );

results.append("\n");}st.close();con.close();JTextArea textArea = newJTextArea(results.toString() );Container container = getContentPane();container.add( new JScrollPane( textArea ) );setVisible( true );

}else if(val.equals("INSERT")){

st.executeUpdate( queryArea.getText() );ResultSet rs=st.executeQuery( "SELECT *

FROM Amit01");StringBuffer results = new StringBuffer();ResultSetMetaData mData =rs.getMetaData();int ColNum = mData.getColumnCount();results.append("DATA AFTER INSERTION\n\n");for ( int i = 1; i <= ColNum; i++ ){

results.append(mData.getColumnName( i )+ "\t\t" );}results.append( "\n\n" );while ( rs.next() ){

for ( int i = 1; i <= ColNum; i++ )results.append( rs.getObject( i )+"\t\t" );

results.append("\n"); }st.close();con.close();JTextArea textArea = new

JTextArea(results.toString() );Container container = getContentPane();

By: Amit Kumar Agrawal 361

The Smartest Way to Learn Java5

container.add( new JScrollPane( textArea ) );setVisible( true );

}}catch ( SQLException sqlException ) {

JOptionPane.showMessageDialog(

null,sqlException.toString(),"Database

error",JOptionPane.ERROR_MESSAGE

);

}}}); // end call to addActionListenersetSize( 800, 640 );setVisible( true );

}catch ( ClassNotFoundException classNotFound ) {

JOptionPane.showMessageDialog( null,"Cloudscape driver not found", "Driver not found",JOptionPane.ERROR_MESSAGE );

System.exit( 1 ); // terminate application}catch ( SQLException sqlException ) {

JOptionPane.showMessageDialog(

null,sqlException.toString(),"Database error",

JOptionPane.ERROR_MESSAGE );

System.exit( 1 );

}}public static void main( String args[] ){

QueryProcesssor app = new QueryProcesssor();

app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

}}

By: Amit Kumar Agrawal 362

The Smartest Way to Learn Java5

This will demonstrate the use of JDBC with Swing programming.

//QP.java

/*PROGRA FOR THE QUERY PROCESSING WHERE THE QUERY SET INRUNTIME*/

import java.awt.*;import java.awt.event.*;import java.sql.*;import java.util.*;import javax.swing.*;public class QP extends JFrame{

private JTextArea queryArea;public QP(){

super( "Query Processor" );String driver = "sun.jdbc.odbc.JdbcOdbcDriver";String url = "jdbc:odbc:AKA";String query = "ENTER YOUR QUERY";try

By: Amit Kumar Agrawal 363

The Smartest Way to Learn Java5

{Class.forName( driver );Connection connection =

DriverManager.getConnection(url);Statement statement = connection.createStatement();queryArea = new JTextArea( query, 3, 100 );queryArea.setWrapStyleWord( true );queryArea.setLineWrap( true );JScrollPane scrollPane = new JScrollPane(queryArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );JButton submitButton = new JButton( "Submit Query" );Box box = Box.createHorizontalBox();box.add( scrollPane );box.add( submitButton );Container c = getContentPane();c.add( box, BorderLayout.NORTH );submitButton.addActionListener(new ActionListener(){

public void actionPerformed( ActionEvent e ){

try{

String stq=queryArea.getText();String val=new String();Vector c_hd=new Vector();JFrame jf=new JFrame();Connection con =DriverManager.getConnection("jdbc:o

dbc:AKA");Statement st = con.createStatement();ResultSet rs=st.executeQuery(

queryArea.getText() );Vector results = new Vector();ResultSetMetaData mData = rs.getMetaData();

By: Amit Kumar Agrawal 364

The Smartest Way to Learn Java5

int ColNum = mData.getColumnCount();for(int j=0;j<ColNum;j++){

c_hd.add(mData.getColumnName(j));}while ( rs.next() ){

Vector rst=new Vector();for ( int i = 1; i <= ColNum; i+

+ ){

rst.add( rs.getObject( i ));

}results.add(rst);

}st.close();con.close();JTable textArea = new JTable(results,c_hd);Container container = getContentPane();container.add( new JScrollPane( textArea ) );setVisible( true );

}catch ( SQLException sqlException ){

JOptionPane.showMessageDialog(null,sqlException.toString(),"Database

error",JOptionPane.ERROR_MESSAGE);

}}

}); // end call to addActionListenersetSize( 800, 640 );setVisible( true );//}}catch ( ClassNotFoundException classNotFound ) {

JOptionPane.showMessageDialog( null,"Cloudscape

By: Amit Kumar Agrawal 365

The Smartest Way to Learn Java5

driver not found", "Driver not found",JOptionPane.ERROR_MESSAGE );System.exit( 1 ); }

catch ( SQLException sqlException ) {JOptionPane.showMessageDialog(null,sqlException.toString(),"Database error",

JOptionPane.ERROR_MESSAGE );System.exit( 1 );}}

public static void main( String args[] ){QP app = new QP();app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

}}

Output:

When designing applications that use the JTable it is worth paying close attention to the data structures that will represent the table's data. The DefaultTableModel is a model implementation that uses a Vector of Vectors of Objects to store the cell values. As well as copying the data from an application into the DefaultTableModel, it is also possible to wrap the data in the methods of the TableModel interface so that the data can be passed to the JTable directly.

This is the output of the JTable program

By: Amit Kumar Agrawal 366

The Smartest Way to Learn Java5

//TDemo.java

/*PROGRAM TO DEMONSTARTE THE JTREE*/

import java.awt.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.tree.*;public class TDemo extends Jframe{

public TDemo(){JTree t;DefaultMutableTreeNode st=new

DefaultMutableTreeNode("RCM");DefaultMutableTreeNode st1=newDefaultMutableTreeNode("MBA");st.add(st1);DefaultMutableTreeNode st1_1=newDefaultMutableTreeNode("MBA 1st Yr");st1.add(st1_1);DefaultMutableTreeNode st1_2=new

By: Amit Kumar Agrawal 367

The Smartest Way to Learn Java5

DefaultMutableTreeNode("MBA 2nd Yr");st1.add(st1_2);DefaultMutableTreeNode st2=newDefaultMutableTreeNode("MCA");st.add(st2);DefaultMutableTreeNode st2_1=newDefaultMutableTreeNode("MCA 1st Yr");st2.add(st2_1);DefaultMutableTreeNode st2_2=newDefaultMutableTreeNode("MCA 2nd Yr");st2.add(st2_2);DefaultMutableTreeNode st2_3=newDefaultMutableTreeNode("MBA 3rd Yr");st2.add(st2_3);t=new JTree(st);JScrollPane j=new JScrollPane(t);add(j);t.addTreeSelectionListener(new TreeSelectionListener(){public void valueChanged(TreeSelectionEvent e){}});setSize(640,480);setVisible(true);

}public static void main(String args[]){

TDemo td=new TDemo();}

}

By: Amit Kumar Agrawal 368

The Smartest Way to Learn Java5

This is the output of the TDemo program it is to demonstrate how to use the JTree class.

//TabDemo.java

/*PROGRAM TO DEMONSTARTE THE JTREE*/

import java.awt.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.tree.*;public class TabDemo extends JFrame{

public TabDemo(){

JTabbedPane t=new JTabbedPane();t.addTab("INTERFACE",new IntSoft());t.addTab("LAKSHYA",new Lakshya());t.addTab("JAVA POINT",new JPoint());add(t);setSize(640,480);setVisible(true);

}

By: Amit Kumar Agrawal 369

The Smartest Way to Learn Java5

public class IntSoft extends Jpanel{

public IntSoft(){JButton b=new JButton("RASHMI");JButton b1=new JButton("P.K.DIKHIT");JButton b2=new JButton("AMIT");add(b);add(b1);add(b2);

}}

public class Lakshya extends JPanel{

public Lakshya(){

JButton b=new JButton("SUSHANT");JButton b1=new JButton("SIDDHARTHA");JButton b2=new JButton("NILAB GHOSH");add(b);add(b1);add(b2);

}}public class JPoint extends JPanel{

public JPoint(){

JButton b=new JButton("DEBASHIS");add(b);

}}

public static void main(String args[]){

TabDemo td=new TabDemo();}

}

By: Amit Kumar Agrawal 370

The Smartest Way to Learn Java5

This is the program to demonstrate the JTabbedPane

//JFileChooser Demonstration

/*PROGRAM FILE TO DEMONSTRATE THE JFileChooser*/

import javax.swing.*;import java.awt.*;import java.awt.event.*;class JFC extends JFrame{

JTextField filename = new JTextField(),dir = new JTextField();JButton open = new JButton("Open Dialogbox");JButton save = new JButton("Save The File");public JFC(){

JPanel p = new JPanel();open.addActionListener(new OpenL());p.add(open);save.addActionListener(new SaveL());p.add(save);Container cp = getContentPane();cp.add(p, BorderLayout.SOUTH);dir.setEditable(false);filename.setEditable(false);

By: Amit Kumar Agrawal 371

The Smartest Way to Learn Java5

p = new JPanel();p.setLayout(new GridLayout(2,1));p.add(filename);p.add(dir);cp.add(p, BorderLayout.NORTH);setSize(300,300);setVisible(true);

}class OpenL implements ActionListener{

public void actionPerformed(ActionEvent e){

JFileChooser c = new JFileChooser();// Demonstrate "Open" dialog:int rVal = c.showOpenDialog(JFC.this);if(rVal == JFileChooser.APPROVE_OPTION){

filename.setText(c.getSelectedFile().getName());dir.setText(c.getCurrentDirectory().toString());

}if(rVal == JFileChooser.CANCEL_OPTION){

filename.setText("You pressed cancel");dir.setText("");

}}

}class SaveL implements ActionListener {

public void actionPerformed(ActionEvent e){

JFileChooser c = new JFileChooser();// Demonstrate "Save" dialog:int rVal =c.showSaveDialog(JFC.this);if(rVal == JFileChooser.APPROVE_OPTION){

filename.setText(c.getSelectedFile().getName());dir.setText(c.getCurrentDirectory().toString());

}if(rVal == JFileChooser.CANCEL_OPTION){

filename.setText("You pressed cancel");

By: Amit Kumar Agrawal 372

The Smartest Way to Learn Java5

dir.setText("");}

}}

}public class JFCDemo{

public static void main(String[] args){

JFC j=new JFC();}

}

//JColorChooser demonstration program

/*Demonstrate the JColorChooser*/

import javax.swing.*;import java.awt.*;

By: Amit Kumar Agrawal 373

The Smartest Way to Learn Java5

import java.awt.event.*;class JCC extends JFrame{

JLabel demo;Color lastChosen;public JCC( ){

super("Swing Color Demo");Container cp = getContentPane();JButton jButton;cp.add(BorderLayout.NORTH, jButton = new JButton("Change

Color..."));jButton.setToolTipText("Click here to see the Color Chooser");jButton.addActionListener(new ActionListener( ){

public void actionPerformed(ActionEvent actionEvent){

Color ch = JColorChooser.showDialog(JCC.this,"Swing

Demo Color Popup",getBackground());if (ch != null)demo.setBackground(ch);}});cp.add(BorderLayout.CENTER, demo = new

JLabel("Your One TrueColor"));demo.setToolTipText("This is the last color you

chose");setSize(300,300);setVisible(true);

}}

public class JCCDemo{

public static void main(String[] argv) {

JCC j=new JCC( );

By: Amit Kumar Agrawal 374

The Smartest Way to Learn Java5

}}

if we run this code then the output will be :

After pressing CTRL+c the program will be terminated

An Overview on REMOTE METHOD INVOCATION (RMI)

RMI supports Client-Server architecture or in other words distributed Application.

In RMI the complete application is sub-divided into smaller parts.

By: Amit Kumar Agrawal 375

The Smartest Way to Learn Java5

Each parts are termed as Object or Components In RMI the user create the object of the Server side application. This object is called as local object, after this he/she registered the object in

RMI. This registration can be done by using two static methods:

Naming.rebind();Naming.bind();

Naming is a class available in java.rmi package. This class is used for connecting the RMI package)

Difference between rebind() and bind() of Naming class:

In case of rebind () method: If the same name object is already registered in RMI registry then this method overrides the previous object.

In case of bind() method: If the same name object is already registered in RMI registry then it throws an Exception called as

AlreadyBoundsException:

The client side application of the otherhand searches the reference of the remote

object from RMI registry with the help of a static method called as

Naming.lookup();

STEPS: (For the execution of RMI program)

o Define an interface, that extends the java.rmi.Remote interface. When a user deifine interface extends the Remote interface then all the methods available in the interface are treated as Remote method, and then it must throws RemoteException.

o Implement this interface on the server side application: This can be done by extending the UnicastRemoteObject. This class explicitly export the Remote object.

o Compile the interface and its implementation.o Compile the server class file with the rmic (RMI compiler). It generates

two class file. 1) server.class_stub : proxy for the Client. 2) server.class_skel : proxy for the Server.

By: Amit Kumar Agrawal 376

The Smartest Way to Learn Java5

o Run the RMI registery.o Compile the client side application for the other machine.o Run the Cient side application.

PROGRAM TO DEMONSTRATE THE RMI

//RMIAdd.java

import java.rmi.*;public interface RMIAdd extends Remote{

public int add(int a, int b) throws RemoteException;}

//RMIServer.java

import java.rmi.*;import java.rmi.server.*;public class RMIServer extends UnicastRemoteObject implements RMIAdd{

public RMIServer() throws RemoteException{System.out.println(“SERVER GET CONNECTED”);}int i,j;public int add(int a,int b)throws RemoteException{

i=a;j=b;return i+j;

}public static void main(String args[]){

try{

RMIServer rs=new RMIServer();Naming.rebind(“RMIServer”,as);

}catch(Exception e){}}}

javac RMIAdd.javajavac RMIServer.javarmic RMIServerstart rmiregistryjava RMIServer

By: Amit Kumar Agrawal 377

The Smartest Way to Learn Java5

//RMIClient.java

import java.rmi.*;import java.io.*;public class RMIClient{

Public static void main(String args[])throws Exception{

DataInputStream in=new DataInputStream(System.in);try{

System.out.println(“ENTER TWO VALUES:”);;int i=Integer.parseInt(in.readLine());int j=Integer.parseInt(in.readLine());RMIAdd ad=(RMIAdd) Naming.lookup (“rmi: //

localhost : 1099 / RMIServer”);System.out.println(“ADDITION IS:+ad.add(i,j));

}catch(Exception e){}

}}

javac RMIClient.javajava RMIClient

Layers of RMI

RMI works with the help of four different layers

A – ApplicationP – proxyR – Remote Reference LayerT – Transport layer

By: Amit Kumar Agrawal 378

The Smartest Way to Learn Java5

Application Layer

Application layer understand only the high level task.

It is the actual implementation of the Cilent-Server application.

In this layer the data dataflow from Server side application to the

Cilent side application and vice versa.

In RMI every interface extends Remote Interface that makes the

inheritance remote and methods as remote methods.

The server side application must extends UnicastRemoteObject

class.

It is used to implicitly exports the remote object.

The server create the object and registered the object and registered the object in rmiregistry with the help of two methods : rebind() and bind() of Naming class.

rmiregistry is a server who keeps track of all the objects. On the Client side the programmer or the user check the object is a

registered in the rmiregistry or not, with the help of a method called lookup of Naming class.

proxy Layer

By: Amit Kumar Agrawal 379

The Smartest Way to Learn Java5

The proxy layer can work with the help of stub and skeleton class file.

Work of stub class file:o stub is the proxy for the client side application.

o By using this class file the Client application sends the

parameters on the net.

o stub serializes the arguments. Serialization means coneverting

the the java bytecode into String format for transmitting the

parameter to the destination machine.

o When the destination PC process the data and send it to Client

PC. It deserialize the return type.

Work of skel class file:

o Skeleton is the proxy for the server.

o It deserialize the argumemts, that is sends by the stub (Client

proxy) and process the same.

o Then skeleton serialize the return type and sends the result to the

client (stub).

Remote Reference Layer

It is the middleware between the proxy layer and the transport layer. The actual serialization and de-serialization task is done by this

layer.

Transport Layer Transport layer manages the network connection. It checks the connectivity. It monitors the network.

By: Amit Kumar Agrawal 380

The Smartest Way to Learn Java5

FLOWS OF RMI:

Steps:

1. Server creates the object and that object is called as local object.

2. Server register the object in RMI registry then the object is Remote

Object.

3. Client makes the request for accessing the reference of remote object.

4. RMI registry returns reference of remote object to stub.

5. stub processes the remote object reference to the client.

6. stub serializes the argument of the remote method and send it to skel.

7. skel processes the oaraameter through the object.

8. skel serialize the return type and sends it to the stub.

By: Amit Kumar Agrawal 381

The Smartest Way to Learn Java5

An overview on JavaBean

Motto of JavaBeans is:

“ Write once,Run any where,

And reuse it every where”

The tools such as Visual Basic allow the programmer or the end users to combine applicatuions from pre-exhist components. In general, the technique that allows the vendors to build visual programming environments is called component-bassed software engineering. Java development team decide to provide the similar facility in Java technology that allows you to build components is called JavaBeans. It is a componentsoftware developed by sun microsystem.

JavaBeans enable the software developers to design and create re-usable software components written in java language.

The basic advantage of these kind of component is created once but use for multiple times.

Advantage of JavaBean over VB is, It is platformindependent (As it is written in Java), but the application develop in VB is platformdependent.

Component model defines the architecture of the componets which is responcible for determining how the components are able to interactin a dynamic environment and how they can be manipulated.

JavaBeans define the component model with the help of following advantages:

o Introspection.

o Event Handling.

o Persistence.

o Layout.

o Application Builder Support.

o Distributed computing support.

Introspection:

By: Amit Kumar Agrawal 382

The Smartest Way to Learn Java5

It is the mechanism that exposes the functionality of a component to the outside world.Event Handling:

It is the mechanism through which the internal state of the component is changed.

Persistence:

It is feature through which we can store the component permananently.

Layout:

It is use to placing the userdefined components in the complex applications.

Application Builder Support:

It gives the facility to the user graphically build the complex application.

Distributed computing support:

with the help of RMI (Remote Method Invocation) and CORBA (Common Object Request Brokers Architecture). The objects are communicates with one machine to other machines.

Reflection:

It is the ability to obtained the information about the fields, constructors, and methods of any class at the runtime.

Intrispection uses the reflection to obtain the information about the beans.

Accessor Methods:

Accessor methods are the public methods that use by JavaBeans. Property access is one of the biggest responsibility of JavaBean

API(Application Programming Interface). These are the public methods comes in pair. One part of the pair is usee to write the property and the other one is to read

the property.

By: Amit Kumar Agrawal 383

The Smartest Way to Learn Java5

public void setName(String Name){……….. }public String getName(){……….. }

JAR Files

JAR stands for Java Archive File. JAR files provides standard mechanism to compress and packages a set of

files. For the users. JAR is a platform independent file format that aggregates many files in to

one file. JAR is simply a class file. JAR supports the file compression which reduces the file size. JAR used for improving the downloading time. JAR must require a manifest file or .mft file.

Advantage of using JAR Files

Improved download efficiency. Improved file storage. Improveed security (By using keys). Platform independence. Backwards compatibility. Extensibility.

Creating a JAR file of Listing.java

//Listing.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Listing{public static void main(String[] args){

JFrame f = new JFrame("Lister v1.0");f.setSize(200, 200);f.setLocation(200, 200);

By: Amit Kumar Agrawal 384

The Smartest Way to Learn Java5

f.addWindowListener(new WindowAdapter( ) {public void windowClosing(WindowEvent we) { System.exit(0);}

});// create a combo box

String [] items = { "Amit", "Rashmi", "DIKHIT", "SUSHREE","MANASH","MONALISHA", "DEBASHIS", "BABU", "ARUNA", “DILLIP","SIBASHIS", "PAPUN" };

JComboBox comboBox = new JComboBox(items);comboBox.setEditable(true);

// create a list with the same data modelfinal JList list = new JList(comboBox.getModel( ));// create a button; when it's pressed, print out// the selection in the listJButton button = new JButton("Per favore");button.addActionListener(new ActionListener( ) {public void actionPerformed(ActionEvent ae) {Object[] selection = list.getSelectedValues( );System.out.println("-----");for (int i = 0; i < selection.length; i++)System.out.println(selection[i]);}});// put the controls the content paneContainer c = f.getContentPane( );JPanel comboPanel = new JPanel( );comboPanel.add(comboBox);c.add(comboPanel, BorderLayout.NORTH);c.add(new JScrollPane(list), BorderLayout.CENTER);c.add(button, BorderLayout.SOUTH);f.setVisible(true);}

}

javac Listing.java

edit Listing.mft

Name: Listing.classJava-Bean: True

By: Amit Kumar Agrawal 385

The Smartest Way to Learn Java5

Alt+F+Xjar –cfm Listing.jar Listing.mft Listing.class---------JAR file created

c: Create an archive (Name of the archive file)

f: First element name of the archive

m: Second element name of the archive (Name of the Manifest file)

JAR file Option for JAR utility

c – Make a new Archive.

f – First element is the name of the acrchive file.

m – Second element is the name of the manifest file.

T – Tabulate the contents of the archive

x – Extract file from the archive.

O – Don’t use for compression.

M – Not create the manifest file.

SERVLET

1. A servlet is nothing but the server side software program that dynamically extends functionality of a web page in web server to its client.

2. It creates dynamic and interactive web pages that can be stored in a server (web server) and can be accessed securely.

3. This is the technology that that creates content of basically HTML web page dynamically as when required as per users request.

4. These are java class files associated with specific interface creates dynamic HTML codes for the user and can be invoked via a web server.

5. The servlets reside within the web server in which a servlet container contains the servlets.

6. Web servers are able to execute servlets and produces dynamic HTML after getting request from the users.

By: Amit Kumar Agrawal 386

The Smartest Way to Learn Java5

7. For each user the servlet is instantiated by using concept of threading without creating copy of that page.

8. Some other technologies that create dynamic pages are: JSP, ASP, PhP, Cold Fusion etc.

Features

1. EfficiencyIn case of java Servlets, for each request from client a thread of the servlet is created. The JVM continues to run in the server to accept the request and making threads. Does not use the heavy weight processes.

2. PortableJava servlets are portable across the OS and server implantations. We can write servlets for Tomcat server in Windows platform and can deploy the same in UNIX platform with another web server with no effort or little effort.

3. PowerServlets exploit the power and efficiency of core java, networking, multithreading, database connectivity, serialization, RMI. It also takes the advantages of EJB, JNDI, and Messaging Services of the J2EE platform.

4. SafetySafeties comes from the Java’s features of strongly typed, no use of pointer.Java’s exception handling handles the errors.Server also protects itself from servlets through Java Security Manager that access the control by defining policy.

5. ExtensibilityServlets APIs are designed to be easily extensible for further enhancement.

6. ConvenientOne, who knows Java, need not know other language for server side programming.

Most of the things are automatic: passing parameter, reading HTML form, handling cookies etc.

By: Amit Kumar Agrawal 387Client

JDBC

Web Server(Servlet)

Web service

RMI

JNDI

The Smartest Way to Learn Java5

HTTP Request

When a client makes a request for a web page from the server and if the server

responds it then it is called that the transaction is complete.

The request contains the type of the action, the address of the document and

version of the HTTP protocol.

Besides this information the request also sends extra information regarding

what software is being used (User-Agent ), what content type (Accept) are

understood by the client. This information is called a request header.

HTTP Response

After accepting the request the server processes it and sends information that

are represented by the client called response.

The response contains the status line that contains HTTP protocol used by

server, status code and status description.

Response also followed by a response header which contains the information

regarding server software running in server, content type sent, length of the

content etc.

By: Amit Kumar Agrawal 388Client

Server

HTML contentServlet

Invoke

Response

Request

The Smartest Way to Learn Java5

Requirement

1. JDK

To compile the servlet and to get predefined packges

2. Web server

To accept request from user and provide response To create threads for the users those who seek response from the server. To create the instance of servlets for the users. To contain the servlets (web container) and implement the interfaces into

classes at runtime. Some web servers : Web Sphere, Apache Tomcat, Web logic, JWS.

3. DBMS

4. IDE

Installing Server (Apache Tomcat)

1. Install JDK 1.4 or higher for Tomcat 5 or higher2. Install Apache Tomcat.3. Provide port number (8080 default you may change to any unused port),

administrator id and password.4. Start Tomcat in window as Start->Program -> Apache -> Start Tomcat.5. Test the server IE by entering http://localhost:8080/index.jsp . Examine for the

index page of Tomcat.

Example (GenericServlet class)

By: Amit Kumar Agrawal 389

The Smartest Way to Learn Java5

import javax.servlet.*;import java.io.*;public class Frst_Servlet extends GenericServlet{

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{

PrintWriter pout=response.getWriter();pout.println(“<HTML>”);pout.println(“<BODY BGCOLOR=’YELLOW’>”);pout.println(“<H1> HELLO, SERVLET</H1>”);pout.println(“</BODY>”);pout.println(“</HTML>”);

}}

Example (using HttpServlet)

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class First_Servlet1 extends HttpServlet{

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

PrintWriter pout=response.getWriter();pout.println(“<HTML>”);pout.println(“<BODY BGCOLOR=’YELLOW’>”);pout.println(“<H1> HELLO, MY SERVLET</H1>”);pout.println(“</BODY>”);pout.println(“</HTML>”);

}}Saving the servlet

Create a directory which will be the context directory say ‘mohanty’.

By: Amit Kumar Agrawal 390

The Smartest Way to Learn Java5

Create a sub-directory as ‘WEB-INF’ under mohanty and ‘classes’ under WEB-

INF.

Save your java source code under the ‘classes’ directory such that .class file

will be saved here.

So the directory structure may be D:\mohanty\WEB-INF\classes\*.class

Copy servlet.jar file from C:\program files\apache group\tomcat 4.1\common\

lib directory and paste it in D:\mohanty\WEB-INF\classes directory.

Compile the source code

Compile the servlets using classpath option of javac as

C:\JDK1.5.0\Bin> javac –classpath servlet.jar First_Servlet.java.

Creating context

Context is a reference name given to a group of objects (such as html, JSP, Servlet) to access them from the web derver using web browser.

For example : In http://localhost:80/aka/index.html , ddm is the context name where ddm reference to ‘mohanty’ is context directory.

Create a file known as web.xml in WEB-INF directory of the context directory

or

Copy the web.xml file from tomcat home\webapps\examples\ WEB-INF and paste it in your context directory’s WEB-INF directory.

Edit server.xml file available in tomcat home\conf and create a <Context> tag before ending of </Host > tag as<Context path=”/aka” docBase=”c:\singhal” reloadable=”true” debug=”0”/>

To test the context create an HTML file and place it in the context directory and try to access by the browser.

By: Amit Kumar Agrawal 391

The Smartest Way to Learn Java5

Execution of servlet

Edit the web.xml file available in WEB-INF directory of the context directory and write following information about your servlet within the tag :

<web-app>………

</web-app>

<servlet><servlet-name>fs1</servlet-name><servlet-class>FirstServlet</servlet-class>

</servlet><servlet-mapping>

<servlet-name>fs1</servlet-name><url-pattern>/greet</url-pattern>

</servlet-mapping>

Servlet Life Cycle

Life cycle of servlet involves following stages and they are:

1. The init Method

The method is called when the servlet is first loaded before the thread is created.

The method is applied for performing some complex functions such as initializations, calculations which common to the all the requests.

The init() is called once for the a servlet. public void init() {……..}

2. The service Method

When a server gets a request from the client requesting for a servlet, the server forks a thread and calls the service method for the request.

The service method checks HTTP request type (GET, POST, PUT etc) and calls doGet(), doPost(), doPut() respectively.

Instead of overriding the service(), it advantageous to override the doGet() or doPost().

By: Amit Kumar Agrawal 392

The Smartest Way to Learn Java5

3. The doGet(), doPost() ….

These methods contain vital part of the servlet that is sent to user as response after implementation of logic of the servlet.

Most of the time these methods are used in the servlets.

4. The destroy Method

The method removes the loaded servlet, closes the connectivity of database.

Halts the background threads and cleans up the servlet activities and saves the status in the disk.

User Tracking

This is a mechanism to keep the textual information of the particular client for more than one page available to the same domain. By using this mechanism we can create variables which value remains alive for scheduled time within different pages of same domain. The mechanism let the clients to pass information over other pages of same domain and make the servlet to track the user also. There are two mechanisms:

Cookies Session

Cookies:

Cookie is a small textual information that web-server sends to a browser (browser may save it) and that browser later returns the same information when visiting the same domain.

This is a mechanism to create variable and value pair to store information for the user in the user end by using user’s web browser.

The cookies created by a web server will be available to that site only each time the particular client (browser) sends request to that server and will travel from user end (client) to the server as the part of the request.

Once the cookie is created it can be available for the server through request for a particular period of duration (by default till the browsing session) and can be extended or shortened.

By: Amit Kumar Agrawal 393

The Smartest Way to Learn Java5

The cookies methods are

1. void setDomain( String domain)The method set the domain pattern to which a cookie

applies.2. String getDomain()

The method returns the name of the domain to which it applies.

3. void setMaxAge(int sec)It sets the lifetime of the cookie ie how much time should elapse before the cookie expires.

4. int getMaxAge()It gets the life time of the cookie.

5. String getName()It returns the name of the cookie that has been assigned at the time of creation of the cookie.

6. void setPath(String path)The method sets the path to which the cookie is applied. Default is the directory in or below the directory containing the page that sent the cookie.

7. String getPath()It returns the path to which the cookie applied.

8. String getValue()It returns the value associated with a cookie name.

Creating Cookie

Instantiate the Cookies class of javax.servlet.http package by providing variable and value pair asCookie ck= new Cookie(“variablename”, value)

E.g.:String prod=request.getParameter(“txtprod”);Cookie ckprod=new Cookie(“ckprod”, prod);

Set the maximum age of the cookie if the browser will store the information of the cookie in disk instead of keeping it in memory. If age is not set then it will last for the browsing session only by default.

ckprod.setMaxAge(int sec)

By: Amit Kumar Agrawal 394

The Smartest Way to Learn Java5

Add the cookies instance into the response by invoking addCookie() method of HttpServletResponse as

response.addCookie(ckprod);

Reading Cookie

Create an array of object of Cookie class which will contain all the cookies by using getCookies() method of HttpServletRequest asCookie ret_ck[]= request.getCookies();

Find the name of the cookie from the array of the cookies by invoking getName() method of Cookie class and use getValue() method of Cookie class to find value associated with the cookie as:

for( int cnt=0;cnt<ret_ck.length, cnt++){

if (ret_ck[cnt].getName().equals(“ckprod”)){

ck_val=ret_ck[cnt].getValue();//process ck_val

} }

Complete example (Cookie)

Shop.html<html>

<body><form action=”/aka/thnk” method=”post”>

</h3> Enter Goods name <input type=”text” name=”txtprd”> </h3><input type=”submit” value=”submit”>

</form></body>

</html>

Session

By: Amit Kumar Agrawal 395

The Smartest Way to Learn Java5

Whenever a user enters into a web server a session is created with a unique session

id, which continues till the user stays in the server. A servlet can utilize this session

to create variables with values which will be available for all the servlets of the site

within the session.

Creating a session

1. Instantiate javax.servlet.http.HttpSession class by using getSession() method of HttpSetrvletRequest class.

HttpSeesion myses = request.getSession(true);

This statement allows creating session and adding session variable into servlet and avails the variable in other servlet within the session.

2. Provide variable and value pair to method setAtrribute() of HttpSession class.

myses.stAttribute(“var”,value);

Reading Session

1. Instantiate javax.servlet.http.HttpSession class by using getSession()

method of HttpSetrvletRequest class.

HttpSeesion myses = request.getSession(true);

2. Read the value of the session variable by providing variable name in the

gtAttribute() of HttpSession class.

String str=(String) myses.getAttribute(“var”);

Session tracking API

By: Amit Kumar Agrawal 396

The Smartest Way to Learn Java5

Object getAttribute(String) Enumeration getAttributeNames() void setAttribute(String var, Object val) void removeAttribute(String var) void invalidate()

Unbind all the object associated with the current session void logout()

Logs the client out of the server and invalidate the entire object associated with the session.

String getId()Returns the id of the session.

void setMaxInactiveInterval(Sec)The session invalidated automatically after this long time without access.

Example (using session)

cookie.java

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class save_session extends HttpServlet{

public void doPost ( HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOexception {

String prod=request.getParameter();HttpSession myses =request.getSession(true);myses.setAttribute(“prd_nm”,prod);PrintWriter pout=response.getWriter();pout.println(“<html>”);pout.println(“<body bgcolor=’blue’>”);pout.println(“<h2>thanks for purchasing “ + prod + “</h2>”);pout.println(“<h3> <a href =’aka/ckread’> to pay </a> </h3>”);pout.println(“</body>”);pout.println(“</html>”);}}

read_session.java

import javax.servlet.*;

By: Amit Kumar Agrawal 397

The Smartest Way to Learn Java5

import javax.servlet.http.*;import java.io.*;public class read_session extends HttpServlet{

public void doPost ( HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOexception {

HttpSession myses =request.getSession();String prod=null;Prod = (String) myses.getAttribute(“prod_nm”);PrntWriter pout=response.getWriter();pout.println(“<html>”);pout.println(“<body bgcolor=’gray’>”);pout.println(“<h2>You purchased :“ + prod + “</h2>”);pout.println(“<h3> <a href =’aka/myprod’> Purchase more </a> </h3>”);pout.println(“</body>”);pout.println(“</html>”); }}

JSP (Java Server Pages)

JSP (Java Server Pages) is a technology that enables us to mix regular, static HTML with dynamically generated content.

The technology that creates your interface of an enterprise application allows writing dynamically generated web content within HTML tag.

JSP can be thought of java code inside HTML (servlets are HTML within java). JSP is another way of writing servlet.

JSP is translated to a .java file which is servlet. The servlet is then compiled to .class file implicitly. JSP uses the power of servlet and flexibility of HTML. It makes separation between presentation and content of web page. JSP is easy to write and maintain as it is written within HTML. All the standard HTML tools can be used in JSP. Presents better than servlet but less dynamic than it.

Technology

By: Amit Kumar Agrawal 398

JSP .java .class

JSP Container .java for servlet Servlet Contain

The Smartest Way to Learn Java5

Each time a JSP gets request from the client will provide response using a .class

file of its servlet. When first user comes forward and issue request to JSP, it will be

translated to a servlet which in turn implicitly compiled to a .class file after

removal of error. The servlet must be available in the servlet to provide service to

the user.

Contents of JSP

By: Amit Kumar Agrawal 399

The Smartest Way to Learn Java5

A JSP page is a combination of HTML or XML type tags and java codes (servlet codes) where the java codes are fused within HTML or XML like tags enclosed by tags like <% …%> .

In a JSP page there are three different categories of contents or three different types of tags.

They are :

1. Directive

A JSP directive affects aver all structure of the servlet that is translated

from the JSP page. Directives are used import classes from package,

includes HTML or JSP file in the JSP page at the time of translation of JSP

page into servlet, define custom markup tags etc.

2. Scripting elements

JSP scripting elements allow java code -: variable declaration, method declaration, scriptlets and expression to be inserted in the JSP page.

3. Actions

Actions are the predefined tags which are if used in the JSP page affects the runtime behaviors of JSP and of the response sent to client. Actions are available to JSP by default.

Scripting elements

The followings are the scripting element.

1. DeclarationThe element declares a class level variable or method for the servlet

generating from the JSP page. The variables declared here available to

other declaration, expression and code of the JSP page.

By: Amit Kumar Agrawal 400

The Smartest Way to Learn Java5

The declaration section is introduced not in the _jspService() but within

the class as class variable or method of the class. A declaration is done

by the tag :

<%! int a=3; %>2. Scriptlet

A block of java code processed in order they appear at the time of

request processing. Scriptlets are inserted into _jspService() method of

the servlet which actually produces the output and output depends on

the code purely. A scriptlet is enclosed within :

<% java code %>

3. ExpressionThe element sends a java expression to response to client. The

expression is evaluated at time of request processing and sent as string.

An expression is enclosed as:

<%= java expression %>4. JSP Comments

The contents which are not sent to the client are commented in JSP as : <%-- comment --%>

Example 1. Create a jsp that will print ‘hello’ for finite number of time.

(hello.jsp)

<HTML><BODY BGCOLOR=”GRAY”>

<H2> This is our first JSP page</H2><%

for(int cnt=0;cnt<10;cnt++)out.println( “<H2> Hello </H2>”);

%></BODY>

</HTML>

By: Amit Kumar Agrawal 401

The Smartest Way to Learn Java5

2. Create a jsp that add 10 elements to a combo box where elements are 0 to 9.

( mycomb.jsp)

<html><body bgcolor=’cyan’>

<%! int m=20;%><h1> My Second JSP <h1><select name=”numbers”><%

for(int n=0;n<m;n++){

%><option ><%=n%></option><%

}%></select>

</body></html>

JSP Directives

JSP directives controls and set the code generation that the JSP container performs in translating JSP to Servlet.

They are used to set global values such the class from which the servlet is going to be extended, output content type, session creation ability, error handling mechanism, inclusion of another page in current page, using user defined tags in JSP page.

They are not used to produce output but control the output. There are three directives:

1. The page directive2. The include directive3. The taglib directive

By: Amit Kumar Agrawal 402

The Smartest Way to Learn Java5

page Directive

The page directive is used to manipulate different attributes of a JSP page that affects it.

A page can have multiple page directives in any order and can be placed any where in the page because they are assembled together at the time of translation of JSP to servlet.

Conventionally page directives appear at start of the JSP page. A page directive is applied as

<%@ page attr1=value1 attr2=value2 …. %> Attributes of the page includes:

Import, session, isThreadSafe, errorPage etc.

Example

Displaying system date from Gregorian Calendar to a text box.

cdate.jsp

<%@ page import="java.util.*" language=”Java” session=”true” isErrrorPage=”false” %>

<html> <body bgcolor='BLUE'>

<h1> Second JSP <h1><%

GregorianCalendar gc=new GregorianCalendar(); int dy, mn, yr; dy=gc.get(Calendar.DATE); mn=gc.get(Calendar.MONTH); yr=gc.get(Calendar.YEAR);%><input type="text" value=<%=dy”:”+mn+”:”+yr%> name="t1"></body>

</html>

The include Directive

By: Amit Kumar Agrawal 403

The Smartest Way to Learn Java5

The directive instructs the JSP container to include content of another page in the current page as inline at the point of directive information.

The resource being included must be available to JSP container. The resource may be JSP, HTML or text content which

supports the content type. Content of the included file is parsed at the time of translation. It is better to keep the file being included in a context such that it is easy

access it without publishing much more about the directories under the context directory.

It is performed by<%@ include file=”filename” %>

Example (hello.jsp)<HTML><BODY BGCOLOR="CYAN"><H2> This is our first JSP page</H2><%for(int cnt=0;cnt<10;cnt++){%>

<H2> Hello Mr. Agrawal </H2><%}%><%@ include file="/mycomb.jsp" %></BODY> </HTML>The taglib Directive

The directive allows the JSP page to use custom tag defined in a tag library file

which contains compiled java code against defined tags.

The directive says where to find the definition of used custom tag and what to

do when a particular tag name is encountered.

The directive is used as :

<%@ taglib uri=”tagliburi” prefix=”any” %>

By: Amit Kumar Agrawal 404

The Smartest Way to Learn Java5

Predefined (Implicit)Objects in JSP

There are eight predefined (implicit) objects available for JSP and they are:

requestThe object is of type HttpServletRequest which enables you to access request

parameter, request type and headers etc in JSP page.

responseThis is the variable of type HttpServletResponse which represents server

response for sending response to the client.

outThis is the variable of PrintWriter type and used to make output. This is an

object of javax.servlet.jsp.JspWriter and used widely to write output into

output stream.

sessionThis variable is of HttpSession type associated with the request. Session in JSP is created automatically (if allowed) and the variable is session.

applicationThe object represents the servlet context.

pageThe page object is an instance of the JSP page’s implementation servlet class and like this variable.

Request and Response in JSP

JSP contains implicit objects within it for request and response and the objects for request and response are ‘request’ and ‘response’.

All the methods of HttpServletRequest are available by ‘request’ object. Similarly all the methods of HttpServletResponse can be used by ‘response’ object.

Example (login.html)

<html><body>

By: Amit Kumar Agrawal 405

The Smartest Way to Learn Java5

<form action=”/ddm/valid.jsp” method=”post”><h2> User Token: <input type=”text” name=”txtnm”> </h2><h2> Password <input type=”text” name=”txtpwd”> </h2><input type=”submit” value=”Submit”>

</form></body>

</html>

valid.jsp

<html><body><%

String strnm = request.getParameter(“txtnm”);String strpwd =request.getParameter(“txtpwd”);

%><h2> Your name :<%= strnm %> <h2><h2> Ur password : <%= strpwd %> </h2>

</body></html>

Creating cookies

Create an instance of Cookie class available in javax.servlet.http package. Provide pair of variable and value of cookies. Add the instance of cookies through the response object using addCookie().

Cookie ck = new Cookie(“var”, val);response.addCookie(ck);

Reading cookie

Create an array of Cookie by using getCookies() method of ‘request’ object. Search the name of desired variable of in the cookies array by using

getName(). Read the values of the cookie if searching of the cookie name is successful.

Cookie rc[] =request.getCookies();for ( int cnt=0;cnt<rc.length; cnt++){

if(rc[cnt].getName().equals(“ck”))v=rc[cnt].getValue();

By: Amit Kumar Agrawal 406

The Smartest Way to Learn Java5

}

JSP Actions

Actions are the predefined tags which are if used in the JSP page affects the

runtime behaviors of JSP and of the response sent to client.

Standard actions are available to JSP by default (no need of declaring the

taglib).

During translation of JSP into servlet, the action tag generates java code

that corresponds to the predefined task.

JSP actions are written within <……/>.

The actions are :1. <jsp:useBean/>

This is used to use a bean in a JSP such that lengthy java code for business logic can be stored separately in a class and can be instantiated in JSP and used.<jsp:useBean id=”bean_id” class=”class_name” scope=”page /session /application”/>

2. <jsp:setProperty />The tag is used to set / change property of a bean (object) which is supposed to be used in the JSP. It is always used in association with <jsp:useBean /> action.<jsp:setProperty name=”bean_id” property=”prop_name” value=”val” />

3. <jsp:getProperty />The tag is used to get /retrieve property of a bean (object) which is supposed to be used in the JSP. It is always used in association with <jsp:useBean /> action.<jsp:getProperty name=”bean_id” property=”prop_name” />

4. <jsp:forward>5. <jsp:include>6. <jsp:plugin>7. <jsp:param>

By: Amit Kumar Agrawal 407

The Smartest Way to Learn Java5

Introduction to JMS (Java Message Services)

This section will give you a brief description on the objectives and functionality of the Java Message Service (JMS). JMS provides a common way for Java programs to create, send, receive and read an enterprise messaging system’s messages.

Is This a Mail API?

The term messaging is quite broadly defined in computing. It is used for describing various operating system concepts; it is used to describe email and fax systems; and here, it is used to describe asynchronous communication between enterprise applications. Messages, as described here, are asynchronous requests, reports or events that are consumed by enterprise applications, not humans. They contain vitalinformation needed to coordinate these systems. They contain precisely formatted data that describe specific business actions. Through the exchange of these messages each application tracks the progress of the enterprise.

JMS Objectives

If JMS provided a union of all the existing features of messaging systems it would be much too complicated for its intended users. On the other hand, JMS is more than an intersection of the messaging features common to all products. It is crucial that JMS include the functionality needed to implement sophisticated enterprise applications. JMS defines a common set of enterprise messaging concepts and facilities. It attempts to minimize the set of concepts a Java language programmer must learn to use enterprise messaging products. It strives to maximize the portability of messaging applications.

JMS Provider

As noted earlier, a JMS provider is the entity that implements JMS for a messaging product. Ideally, JMS providers will be written in 100% Pure Java so they can run in applets; simplify installation; and, work across architectures and OS’s. An important goal of JMS is to minimize the work needed to implement a provider.

JMS Messages

By: Amit Kumar Agrawal 408

The Smartest Way to Learn Java5

JMS defines a set of message interfaces. Clients use the message implementations supplied by their JMS provider. A major goal of JMS is that clients have a consistent API for creating and working with messages that is independent of the JMS provider.

Java Transaction API (JTA)

The javax.transaction package provides a client API for delimiting distributed transactions and an API for accessing a resource’s ability to participate in a distributed transaction. A JMS client may use JTA to delimit distributed transactions; however, this is a function of the transaction environment the client is running in. It is not a feature of JMS. A JMS provider can optionally support distributed transactions via JTA.

Java Transaction Service (JTS)

JMS can be used in conjunction with JTS to form distributed transactions that

combine message sends and receives with database updates and other JTS aware

services. Distributed transactions should be handled automatically when a JMS

client is run from within an application server such as an Enterprise JavaBeans

server; however, it is also possible for JMS clients to program them explicitly.

What is a JMS Application?

A JMS application is composed of the following parts:

JMS Clients - These are the Java language programs that send and receive

messages.

By: Amit Kumar Agrawal 409

The Smartest Way to Learn Java5

Non-JMS Clients - These are clients that use a message system’s native

client API instead of JMS. If the application predated the availability of

JMS it is likely that it will include both JMS and non-JMS clients.

Messages - Each application defines a set of messages that are used to

communicate information between its clients.

JMS Provider - This is a messaging system that implements JMS in addition

to the other administrative and control functionality required of a

fullfeatured messaging product.

Administered Objects - Administered objects are preconfigured JMS

objects created by an administrator for the use of clients.

There are two types of JMS administered objects:

ConnectionFactory - This is the object a client uses to create a connection

with a provider.

Destination - This is the object a client uses to specify the destination of

messages it is sending and the source of messages it receives.

Administered objects are placed in a JNDI namespace by an administrator. A JMS

client typically notes in its documentation the JMS administered objects it requires

and how the JNDI names of these objects should be provided to it.

JMS Administration:

By: Amit Kumar Agrawal 410

The Smartest Way to Learn Java5

Overview of JMS Object Relationship:

By: Amit Kumar Agrawal 411

The Smartest Way to Learn Java5

Here are the basic steps to establish a connection and prepare to send and receive messages:

Get a ConnectionFactory and Destination Create a Connection and Session Create a MessageConsumer Create a MessageProducer

Getting a ConnectionFactory

Both the message producer and message consumer (the sender and receiver) need to get a ConnectionFactory and use it to set up both a Connection and a Session.

An administrator typically has created and configured a ConnectionFactory for the JMS client’s use. The client program typically uses the JNDI API to look up the ConnectionFactory.

import javax.naming.*;import javax.jms.*;ConnectionFactory connectionFactory;Context messaging = new InitialContext();connectionFactory = (ConnectionFactory)messaging.lookup("ConnectionFactory");

Getting a Destination

An administrator has created and configured a Queue named “StockSource” which is where stock quote messages are sent and received. Again, the destination can be looked up using the JNDI API.

Queue stockQueue;stockQueue = (Queue)messaging.lookup("StockSource");

Creating a Connection

Having obtained the ConnectionFactory, the client program uses it to create a Connection.

Connection connection;

By: Amit Kumar Agrawal 412

The Smartest Way to Learn Java5

connection = ConnectionFactory.createConnection();Creating a Session

Having obtained the Connection, the client program uses it to create a Session. The Session is used to create a MessageProducer (to send messages) or a MessageConsumer (to receive messages). The Connection.createSession method takes two parameters:

A boolean indicating whether this session is transacted or not The mode of acknowledging message receipt

Session session;/* Session is not transacted,* uses AUTO_ACKNOWLEDGE for message* acknowledgement*/session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

Creating a MessageProducer

Having obtained the Session, the client program uses the Session to create a MessageProducer. The MessageProducer object is used to send messages to the destination. The MessageProducer is created by using the Session.createProducer method, supplying as a parameter the destination to which the messages are sent.

MessageProducer sender;/* Value in stockQueue previously looked up in the JNDI* createProducer takes a Destination*/sender = session.createProducer(stockQueue);

Creating a MessageConsumer

Messages can be consumed either synchronously or asynchronously. This example shows how to create a message consumer that consumes messages synchronously. See Section 9.3.1, “Receiving Messages Asynchronously,” to learn more about consuming messages asynchronously.

By: Amit Kumar Agrawal 413

The Smartest Way to Learn Java5

A MessageConsumer is used to receive messages from the destination, which in this example is the Queue “StockQuote.” A MessageConsumer is created using the Session.createConsumer method, supplying one parameter, the destination from which messages are received.

MessageConsumer receiver;

/* Value in stockQueue previously looked up in the JNDI* createConsumer takes a Destination*/

receiver = session.createConsumer(stockQueue);

Should JMS Specify a Set of JMS JavaBeans?

JMS is a low-level API, and like other Java low-level APIs, it doesn't lend itself to direct representation as JavaBeans.

Should JMS Provide Subscription Notification?

If it were possible for a publisher to detect when subscribers for a topic existed, it could inhibit publication on unsubscribed topics. Although there may be some benefit in providing publishers with a mechanism for inhibiting publication to unsubscribed topics, the complexity this would add to JMS and the additional provider overhead it would require are not justified by its potential benefits. Instead, JMS providers should insure that they minimize the overhead for handling messages published to an unsubscribed topic.

Alignment with the CORBA Notification Service

The Notification service adds filtering, delivery guarantee semantics, durable connections, and the assembly of event networks to the CORBA Event Service. It gets its delivery guarantee semantics from the CORBA Messaging Service (which defines asynchronous CORBA method invocation). Java technology is well integrated with CORBA. It provides Java IDL and COS Naming. In addition, OMG has recently defined RMI over IIOP. It is expected that most use of IIOP from Java will be via RMI. It is expected that most use of COS Naming from Java will be via JNDI (Java Naming and Directory Service). JMS is a Java API designed to be

By: Amit Kumar Agrawal 414

The Smartest Way to Learn Java5

layered over a wide range of existing and future MOM systems (just as JNDI is layered over existing name and directory services).

Struts

What is Struts?

An open source development frameworkfor building web applications

Based on Model-View-Controller (MVC) design paradigm Implementation of JSP Model 2 Architecture Created by Craig McClanahan and donated to Apache Software

foundation (ASF) in 2000

NB: Stuts consists of approximately 250 classes and interfaces

Why use Struts?

The webpage need changes time to time and effect must be shown through out the web site, let if we change the name of the Manager of a company that need to be changed at all the pages that contain the name of the manager. The website that is designed through struts can solve this problem easily.

It is developed by industry experts. Stable and mature. Easily Manageable. Open Source. It is rich in features. Free to develop and deploy. Many supported third party tools. Flexible and extendeable. J2EE technology. High in performance.

Configuring Struts

By: Amit Kumar Agrawal 415

The Smartest Way to Learn Java5

For every Struts application, there are at least two configuration files that must be

present: the web application deployment descriptor and a Struts configuration file.

This part discusses each one in turn.

Configuring web.xml

Each Struts application must include a web application deployment descriptor named web.xml, which must be placed in the WEB-INF directory. The web container reads and parses the descriptor file at startup and uses the settings to configure the runtime environment for the installed web application.

Although there are many available configuration settings that can affect the container’s runtime environment, it’s not necessary to configure all of the settings for a Struts application. In many cases, the absence of a setting or the container’sdefault values will be sufficient. Only those settings that pertain to Struts applications will be examined here. For Struts applications, the following configuration settings are typically configured within the web.xml file:

Struts ActionServlet settings Initialization parameters load-on-startup settings Welcome file list Tag libraries mappings

Configuring the Struts ActionServlet

The Struts ActionServlet is designed to receive all incoming requests for the web application. Two steps are necessary when configuring the ActionServlet in the web.xml file. The first step is to use the servlet element to configure the fully qualified Java class name of the ActionServlet:

<web-app><servlet>

<servlet-name>storefront</servlet-name><servlet-class>

org.apache.struts.action.ActionServlet

By: Amit Kumar Agrawal 416

The Smartest Way to Learn Java5

</servlet-class></servlet>

</web-app>

In this web.xml example, the servlet element declares two child elements, servlet-name and servlet-class. The servlet-class element specifies the fully qualified class that will function as the front controller for the Struts application. The Java class specified must be a descendant of the org.apache.struts.action.ActionServlet. If you don’t have a need for specialized behavior, you can safely use the default controller as shown in the previous web.xml fragment. The servlet-name element acts as a logical name for the ActionServlet. It is used in other elements within the deployment descriptor. You can specify whatever value you like here, as long as it adheres to the Servlet Specification naming guidelines. The second step required to configure the ActionServlet is to inform the web container which URL requests should be directed to the ActionServlet controller. This is done using the servlet-mapping element:

<web-app><servlet>

<servlet-name>storefront</servlet-name><servlet-class>

org.apache.struts.action.ActionServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>storefront</servlet-name><url-pattern>*.do</url-pattern>

</servlet-mapping></web-app>

In the example servlet and servlet-mapping elements shown, any request containing a URL that matches *.do would be processed by the servlet named storefront.

The Jakarta Project's Struts framework, version 1.1b2, from Apache Software Organization is an open source framework for building web applications that integrate with standard technologies, such as Java Servlets, JavaBeans, and JavaServer Pages. Struts offers many benefits to the web application developer, including Model 2 implementation of Model-View-Controller (MVC) design patterns in JSP web applications. The MVC Model 2 paradigm applied to web

By: Amit Kumar Agrawal 417

The Smartest Way to Learn Java5

applications lets you separate display code (for example, HTML and tag libraries) from flow control logic (action classes).

Following is a brief overview of the MVC Model 2 design pattern. For complete information about how Struts implements the MVC design patterns, see the Introduction to the Struts User's Guide on the Jakarta Project's Web site:

http://jakarta.apache.org/struts/userGuide/index.html

The Model portion of an MVC-based system typically comprises JavaBean

classes that define the internal state of the system; they also specify the

actions that can be taken to change that state. If you use the BC4J data

access framework, this layer implements the model entirely for you.

Otherwise, you will need to create the classes that implement your model.

The View portion of a Struts-based application is generally constructed

using JSP technology. JSP pages can contain static HTML (or XML) text

called "template text", plus the ability to insert dynamic content based on

the interpretation (at page request time) of special action tags. The JSP

environment includes a set of custom JSP tag libraries (such as the Struts

tag libraries), standard JSP action tags (such as those described in the

JavaServer Pages Specification), and a facility to install your own JSP

custom tag libraries. If you use the BC4J data access framework, you can

take advantage of JDeveloper's JSP generation wizards and the custom tag

libraries that allow your JSP pages to display databound dynamic content.

The Controller portion of the application is focused on receiving requests from the client (typically a user running a web browser), deciding what business logic function is to be performed, and then delegating responsibility for producing the next phase of the user interface to an appropriate View component. In Struts, the primary components of the Controller is a servlet of class ActionServlet and the class RequestProcessor. If you use the BC4J data access framework, the RequestProcessor is extended for you and is known as the

By: Amit Kumar Agrawal 418

The Smartest Way to Learn Java5

BC4JRequestProcessor. JDeveloper helps you implement the MVC Model 2 design patterns using core technology familiar to all web developers:

You can create JSP pages with HTML and custom tag libraries to implement the View of the data. You use links to let the user trigger actions on the HTTP Request.

You can enhance your JSP pages using a large set of custom JSP tag

libraries that work with the Struts framework. All of the Struts tag libraries

are accessible from the JDeveloper Component Palette, when you open a

JSP in the Code Editor. For example, the Struts Form tag works closely

with the Struts actions and form bean to retain the state of a data-entry form

and validate entered data.

Unlike non-Struts JSPs, when you run your application, action requests do

not invoke another JSP or Servlet directly. Instead, the request URI

specifies a logical page request, which the request processor

(RequestProcessor class) provided by the Struts controller handles. The

Struts servlet may direct the responsibility for displaying the action results

to the appropriate JSP page of your application, where the page may vary

according to the exit code.

Working model of struts:

By: Amit Kumar Agrawal 419

The Smartest Way to Learn Java5

SOFTWARE DEVELOPMENT LIFE CYCLE

Systems development is often managed by the systems development life cycle (SDLC), a methodology to plan and manage systems develop via structured analysis. The SDLC model includes the following steps:

1. Systems planning

2. Systems analysis

3. Systems design

4. Systems implementation

5. Systems operation and support

The Developers spends millions of seconds each year on the acquisition, design, development, implementation, and maintenance of information systems vital to mission programs and administrative functions. The need for safe, secure, and reliable system solutions is heightened by the increasing dependence on computer

By: Amit Kumar Agrawal 420

The Smartest Way to Learn Java5

systems and technology to provide services and develop products, administer daily activities, and perform short- and long-term management functions. There is also a need to ensure privacy and security when developing information systems, to establish uniform privacy and protection practices, and to develop acceptable implementation strategies for these practices.

The Developers needs a systematic and uniform methodology for information

systems development. Using this SDLC will ensure that systems developed by the

Department meet IT mission objectives; are compliant with the current and planned

Information Technology Architecture (ITA); and are easy to maintain and cost-

effective to enhance. Sound life cycle management practices include planning and

evaluation in each phase of the information system life cycle. The appropriate level

of planning and evaluation is commensurate with the cost of the system, the

stability and maturity of the technology under consideration, how well defined the

user requirements are, the level of stability of program and user requirements and

security considerations.

CLASSICAL WATER FALL MODEL

By: Amit Kumar Agrawal 421

The Smartest Way to Learn Java5

ITERATIVE WATER FALL MODEL

SPIRAL MODEL

By: Amit Kumar Agrawal 422

The Smartest Way to Learn Java5

The software programmer need to follow any of the Software Development Life

Cycle model to proceed in the field of development. Every industry in the field of

IT have its own set of rules and regulation for the SDLC, but all based on the

Classical Water Fall Model as it is the base of all models.

Why we need SDLC?

As mentioned earlier every development job need a special atteintion in a proper

scheduled manner to develop a high quality, high integrity, fault tullerence, bug

free software as per industry standard. SDLC help the programmer to achieve the

mentioned goal.

By: Amit Kumar Agrawal 423

The Smartest Way to Learn Java5

HIGH INTEGRITY SOFTWARE QUALITY SYSTEM

Here is some project done in Core Java for the development of your programming skill and make you aware of the real world problem and there solutions. Here Iattached 3-4 projects :

1. Tic-Tac-Toe Game project.

2. Sample On-Line-Voting System.

3. Tower of Hanoi

4. Number Puzzle etc..

By: Amit Kumar Agrawal 424

The Smartest Way to Learn Java5

A Small Project Tic-Tac-Toe Program

Tic-Tac-Toe is a classic pen/pencil-and paper game, which is played between two player to get three marks, usually represented by and

in a row or in any diagonal it may be from left to right or right to left. This is a game played by the every age people in almost all part of the world. A small demonstration of the game is given below where is wins due to an unfortunate lapse in concentration by

The demonstration of the program is:

By: Amit Kumar Agrawal 425

The Smartest Way to Learn Java5

In the above demonstration of the program the is played by the program and is played by the user and this is fixed for all time.

The Algorithm of the different move of the Tic-Tac-Toe program:

1. View the vector board as a ternary number. Convert it to a decimal number.2. Use the number computed in step 1 as an index into move table and access

the vector stored there.3. the vector selected in step 2 represents the way the board will look after the

move that should be made. So set equal to that vector.

The program body is given below:The program body of the Tic-Tac-Toe game program:

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

/******* ******* * TicTacToe program as small game project * By Amit Kumar Agrawal. ******* ******* * Inspired By Book of Robert Lafore * Book By Waite Group's * Book Title: Object-Oriented Programming In Turboc C++ *******

By: Amit Kumar Agrawal 426

The Smartest Way to Learn Java5

******* * The Program Has Artificial Intelligence * Tree Move Program is Used *<applet code="MGM.class" height=350 width =750> <param name="amitg" value="star7.gif"> </applet> ********/

import java.awt.*;import java.awt.event.*;import java.awt.image.*;import java.net.*;import java.applet.*;

public class MGM extends Applet implements MouseListener { int white; int black; final static int moves[] = {4, 0, 2, 6, 8, 1, 3, 5, 7}; //Variable for score board calculation public static int I=0; public static int U=0;

static boolean won[] = new boolean[1 << 9]; static final int DONE = (1 << 9) - 1; static final int OK = 0; static final int WIN = 1; static final int LOSE = 2; static final int STALEMATE = 3;

//Fonts for displaying the required data form Font MyFont=new Font("Comic sans MS",Font.BOLD,18); Font NowFont=new Font("Comic sans MS",Font.BOLD,20); Image amitg; static void isWon(int pos) { for (int i = 0 ; i < DONE ; i++)

By: Amit Kumar Agrawal 427

The Smartest Way to Learn Java5

{ if ((i & pos) == pos) { won[i] = true; } } } static { isWon((1 << 0) | (1 << 1) | (1 << 2)); isWon((1 << 3) | (1 << 4) | (1 << 5)); isWon((1 << 6) | (1 << 7) | (1 << 8)); isWon((1 << 0) | (1 << 3) | (1 << 6)); isWon((1 << 1) | (1 << 4) | (1 << 7)); isWon((1 << 2) | (1 << 5) | (1 << 8)); isWon((1 << 0) | (1 << 4) | (1 << 8)); isWon((1 << 2) | (1 << 4) | (1 << 6)); } int bestMove(int white, int black) { int bestmove = -1; loop: for (int i = 0 ; i < 9 ; i++) { int mw = moves[i]; if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) { int pw = white | (1 << mw); if (won[pw]) { return mw; } for (int mb = 0 ; mb < 9 ; mb++) { if (((pw & (1 << mb)) == 0) && ((black & (1 << mb)) == 0)) { int pb = black | (1 << mb); if (won[pb]) { continue loop; }

By: Amit Kumar Agrawal 428

The Smartest Way to Learn Java5

} } if (bestmove == -1) { bestmove = mw; } } } if (bestmove != -1) { return bestmove; }

for (int i = 0 ; i < 9 ; i++) { int mw = moves[i]; if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) { return mw; } } return -1; } boolean yourMove(int m) { if ((m < 0) || (m > 8)) { return false; } if (((black | white) & (1 << m)) != 0) { return false; } black |= 1 << m; return true; } boolean myMove() { if ((black | white) == DONE)

By: Amit Kumar Agrawal 429

The Smartest Way to Learn Java5

{ return false; } int best = bestMove(white, black); white |= 1 << best; return true; } int status() { if (won[white]) { return WIN; } if (won[black]) { return LOSE; } if ((black | white) == DONE) { return STALEMATE; } return OK; } boolean first = true; Image notImage; Image crossImage; public void init() { setBackground(Color.white); notImage = getImage(getCodeBase(), "right.gif"); amitg=getImage(getDocumentBase(),getParameter("amitg")); crossImage = getImage(getCodeBase(), "cross.gif"); addMouseListener(this); } public void destroy() { removeMouseListener(this); } public void paint(Graphics g) { g.setFont(MyFont);

By: Amit Kumar Agrawal 430

The Smartest Way to Learn Java5

g.setColor(Color.black);

int xoff = 240 / 3; int yoff = 240 / 3; //For the internal structure of the Game Plate g.drawLine(xoff, 2, xoff, 249); g.drawLine(2*xoff, 2, 2*xoff, 249); g.drawLine(2, yoff, 249, yoff); g.drawLine(2, 2*yoff, 249, 2*yoff); //For the image at the required place g.drawImage(amitg,550,50,this); //For the game plate formation g.setColor(Color.red); g.drawLine(250,2,250,250); g.drawLine(252,0,252,252); g.drawLine(2,252,252,252); g.drawLine(2,250,250,250); g.drawLine(0,0,0,252); g.drawLine(2,2,2,250); g.drawLine(0,0,252,0); g.drawLine(2,2,250,2); //For the Score Board Formation g.setColor(Color.red); g.drawRect(279,74,225,80); g.setColor(Color.green); g.drawRect(280,75,225,80); g.drawRect(280,75,224,79); //For entitled the Score board g.setColor(Color.red); g.drawString("Score Board",280,65);

//For the Internal data of the Score Board g.setColor(Color.blue); g.drawString("COMPUTER : "+U,285,100); g.drawString(" PLAYER : "+I,285,145);

By: Amit Kumar Agrawal 431

The Smartest Way to Learn Java5

//For the entitled the Game plate g.setColor(Color.red); g.drawString("GAME PLATE",58,285);

g.setFont(NowFont); g.setColor(Color.gray); g.drawString("Amit Kumar Agrawal's TicTacToe Game",270,25);

int i = 0; for (int r = 0 ; r < 3 ; r++) { for (int c = 0 ; c < 3 ; c++, i++) { if ((white & (1 << i)) != 0) { g.drawImage(notImage, c*xoff + 3, r*yoff + 3, this); } else if ((black & (1 << i)) != 0) { g.drawImage(crossImage, c*xoff + 3, r*yoff + 3, this); } } } } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); switch (status()) { case WIN: case LOSE: case STALEMATE: play(getCodeBase(), "audio/return.au"); white = black = 0; if (first) { white |= 1 << (int)(Math.random() * 9); } first = !first; repaint(); return; } int c = (x * 3) / 240; int r = (y * 3) / 240; if (yourMove(c + r * 3))

By: Amit Kumar Agrawal 432

The Smartest Way to Learn Java5

{ repaint(); switch (status()) { case WIN: play(getCodeBase(), "audio/yahoo1.au"); U++; break; case LOSE: play(getCodeBase(), "audio/yahoo2.au"); I++; break; case STALEMATE: break; default: if (myMove()) { repaint(); switch (status()) { case WIN: play(getCodeBase(), "audio/yahoo1.au"); U++; break; case LOSE: play(getCodeBase(), "audio/yahoo2.au"); I++; break; case STALEMATE: break; default: play(getCodeBase(), "audio/ding.au"); } } else { play(getCodeBase(), "audio/beep.au"); } } }

By: Amit Kumar Agrawal 433

The Smartest Way to Learn Java5

else { play(getCodeBase(), "audio/beep.au"); } }

public void mousePressed(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public String getAppletInfo() { return "TicTacToe By Amit Kumar Agrawal."; }}

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

The different all other files are:

star7.GIF cross.GIF Right.GIF MGM.html

beep.au ding.au return.au yahoo1.au

yahoo2.au

all the audio files which have extension .au are stored in side a directory named audio then the whole program code is compiled by the javac compiler.

C:\jdk1.5.0\bin>javac MGM.javaC:\jdk1.5.0\bin>edit MGM.html

</HTML>

<HEAD>

By: Amit Kumar Agrawal 434

The Smartest Way to Learn Java5

<title>Amit Kumar Agrawal TicTacToe Game program</title>

</HEAD>

<BODY>

<hr>

<applet code="MGM.class" width=750 height=350>

<param name="amitg" value="star7.gif">

</applet>

<hr>

</BODY>

</HTML>

The output of the MGM.html is:

The different quadrant of the Tic-Tac-Toe Game Plate:

By: Amit Kumar Agrawal 435

Quadrant 1 Quadrant 2 Quadrant 3

The Smartest Way to Learn Java5

In this section, we present a series of three programs to play tic-tac-toe. The programs in this series increase in:

Their complexity.Their use of generalizations.The clarity of their knowledge.The extensibility of their approach.

Data Structures:

Board: A nine-element vector representing the board, where the elements of the vector correspond to the board positions as follows:

By: Amit Kumar Agrawal 436

Quadrant 4 Quadrant 5 Quadrant 6

Quadrant 7 Quadrant 8 Quadrant 9

1 2 3

4 5 6

The Smartest Way to Learn Java5

An element contains the value 0 if the corresponding square is blank, 1 if it is filled

with as , or 2 if it is filled with an .

Move table: A large vector of 19,683 elements (39), each element of which is a nine-element vector. The contents of this vector. The content of this vector are chosen specially to allow the algorithm to work.

If we make a hierarchy of the move in the Tic-Tac-Toe game then we get a Tree like structure for each move. That is why the above program is contain tree move programming or in programming word Tree Programming (Containing artificial intelligence) by using which the program can able to move its moves it self.

Artificial Intelligence

Artificial intelligence or AI is the view that human cognitive mental states can be

duplicated in computing machinery. Accordingly, an intelligent system (Program)

is nothing but an information processing system.

AI is a branch of science of IT (Information Technology). This helps the machines

to find solutions to complex problems in a more human like fashion. As the above

program, can able to do the same.

Application of AI

Game playing: We can buy machines (Computer System) that can play master level

chess for few thousand rupees, there is some AI in them, but they play well against

people mainly through brute force computation-looking at hundreds of thousands

of moves. To beat a champion by brute force and known reliable heuristics requires

being able to look at 200 million positions per seconds.

By: Amit Kumar Agrawal 437

7 8 9

The Smartest Way to Learn Java5

Similarly, the above Tic-Tac-Toe game is designed to look at near about 362900

moves.

Picture to give you a overall idea about Tree programming:

Another small project:

This is a program that is prepared for the election purpose, just go through it and try to prepare a small implementable project for the president election of your own college.

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

/* Sample skeleton of a voting program in java*/

import java.*;import java.io.DataInputStream;

class project{ public static void main(String args[]) { double a[]={0,0,0,0,0,0}; double total=20;

By: Amit Kumar Agrawal 438

The Smartest Way to Learn Java5

double per[]={0,0,0,0,0,0} ; int ch; DataInputStream in=new DataInputStream(System.in); try { do { System.out.print("\n\n"); System.out.println("1. Atal Bihari Bajpayee"); System.out.println("2. Sonia Gandhi"); System.out.println("3. Bal Thakre"); System.out.println("4. Laloo Prashad Yadav"); System.out.println("5. Lalkrishna Advani"); System.out.println("\n\nPress 0 to Escape from the program:"); System.out.print("\nEnter your choice Candidate no. for your vote to him/her : "); ch=Integer.parseInt(in.readLine()); switch(ch) { case 1: a[ch-1]++; break; case 2: a[ch-1]++; break; case 3: a[ch-1]++; break; case 4: a[ch-1]++; break; case 5: a[ch-1]++; break; default: a[5]++; break; } total--; }while(ch!=0&&total>0); total=20; for(int i=0;i<6;i++) {

By: Amit Kumar Agrawal 439

The Smartest Way to Learn Java5

per[i]=(a[i]/total)*100; } System.out.print("\n\n\n"); System.out.println("GOVERNMENT OF INDIA"); System.out.println("-------------------\n"); System.out.println("TOTAL NO. OF VOTER PRESENT : "+total); System.out.println("Total no. of polling in the election: "+(a[0]+a[1]+a[2]+a[3]+a[4]+a[5])); System.out.println("\n\n"); System.out.println("The Percentage of vote to the Defferent candidate"); System.out.print("\n\n"); System.out.println(" NAME PERCENTAGE"); System.out.println("1. Atal Bihari Bajpayee : "+per[0]+"%"); System.out.println("2. Sonia Gandhi : "+per[1]+"%"); System.out.println("3. Bal Thakre : "+per[2]+"%"); System.out.println("4. Laloo Prashad Yadav : "+per[3]+"%"); System.out.println("5. Lalkrishna Advani : "+per[4]+"%"); System.out.println("6. The DISPOSED vote percentage is : "+per[5]+"%"); System.out.println("\n\n"); System.out.println("The total percentage of voting polled in election is : "+(((a[0]+a[1]+a[2]+a[3]+a[4]+a[5])/total)*100)+"%"); } catch(Exception e) {} }}

This program is a sample of the Voting in Polling booth the output of the program is given below:

By: Amit Kumar Agrawal 440

The Smartest Way to Learn Java5

This is the first screen of the program then we are allow to poll our vote to the require candidate then at last the output of the program is:

The given program can be extended to make a project for a On-Line Voting System and can be submitted in the exam this is a task for you to prepare a project on the same and try to extend the above program.

PROJECT ON TOWER OF HANOI

/********************************************************************//* AMIT KUMAR AGRAWAL PRESENTING THE TOWER OF HANOI PROGRAM FOR YOU */

By: Amit Kumar Agrawal 441

The Smartest Way to Learn Java5

/********************************************************************//* Program for Tower of Hanoi Applet Application * Project_4_u program *@ Amit Kumar Agrawal *@ Dt. 22-08-2007 *@ Time 7:23 P.M. *<applet code="Tower.class" height=700 width =750> </applet>*//********************************************************************/

import java.awt.*;import java.awt.event.*;import java.awt.image.*;import java.net.*;import java.applet.*;import java.util.*;

public class Tower extends Applet{

TowerPanel pnl;TowerControl cntrl;

public void init(){

resize(850,450);setLayout(new BorderLayout());

pnl=new TowerPanel();add("Center",pnl);add("South",cntrl=new TowerControl(pnl));

}

public void start(){

By: Amit Kumar Agrawal 442

The Smartest Way to Learn Java5

pnl.start();}

public void stop(){

pnl.stop();}

public boolean action(Event ev,Object arg){

if(arg instanceof Boolean){

if(((Checkbox)ev.target).getLabel().equals("Reset")){

pnl.reset=((Boolean)arg).booleanValue();}else{

pnl.reset=((Boolean)arg).booleanValue();}return true;

}return false;

}}

class Towering{

int nm_rings[]=new int[3];int tp_size[]=new int[3];

public Towering(int a){nm_rings[0]=a;nm_rings[1]=0;nm_rings[2]=0;tp_size[0]=40;tp_size[1]=1000;tp_size[2]=1000;

}public void reset(int b)

By: Amit Kumar Agrawal 443

The Smartest Way to Learn Java5

{nm_rings[0]=b;nm_rings[1]=0;nm_rings[2]=0;tp_size[0]=40;tp_size[1]=1000;tp_size[2]=1000;

}}

class Ring{ int rn_size[]=new int[10];

int ol_x[]=new int[10];int wh_x[]=new int[10];int wh_y[]=new int[10];int ordr[]=new int[10];int wh_twr[]=new int[10];

public Ring(int a){

for(int i=0;i<a;i++){

rn_size[i]=40+20*i;wh_x[i]=100;ol_x[i]=wh_x[i];wh_y[i]=400-30*(a-i);ordr[i]=a-i;wh_twr[i]=0;

}}

public void reset(int b){

for(int i=0;i<b;i++){

rn_size[i]=40+20*i;wh_x[i]=100;ol_x[i]=wh_x[i];wh_y[i]=400-30*(b-i);

By: Amit Kumar Agrawal 444

The Smartest Way to Learn Java5

ordr[i]=b-i;wh_twr[i]=0;

}}

}

class TowerPanel extends Panel implements Runnable{ Applet ap; Thread go=null; int wd=500; int ht=400;

int tw_ht=350;int tw_wd=20;int nm_rings=8;int pick_ring=1000;int tmp_x;int tmp_y;boolean win=false;boolean reset;

int pts=0;

//Specially effected words String s=new String("Tower of Hanoi 4 U");

char separated[]; int x_cord=0;int y_cord=0;

Towering twr1=new Towering(nm_rings);Ring rngs=new Ring(nm_rings);

TowerPanel(){ setFont(new Font("TimesRoman",Font.BOLD,50));

setBackground(new Color(170,170,170));separated=new char[s.length()];

s.getChars(0,s.length(),separated,0);}

public void paint(Graphics g){

//special words

By: Amit Kumar Agrawal 445

The Smartest Way to Learn Java5

for(int i=0;i<s.length();i++){

x_cord=(int)(Math.random()*10+15*i+100);y_cord=(int)(Math.random()*10+36);g.setColor(new Color(200-10*i,10*i,10*i));g.drawChars(separated,i,1,x_cord,y_cord);

}

//drawing those three tower nowg.setColor(Color.red);

g.fill3DRect(90,ht-tw_ht,tw_wd,tw_ht,true);g.setColor(Color.blue);

g.fill3DRect(240,ht-tw_ht,tw_wd,tw_ht,true); g.setColor(Color.yellow); g.fill3DRect(390,ht-tw_ht,tw_wd,tw_ht,true); g.drawString("Amit's T.O.H.",490,100);

//drawing all the ringsg.setColor(Color.gray);

for(int j=0;j<nm_rings;++j){

g.setColor(new Color(20*j+55,200-20*j,20*j+55)); g.fill3DRect(rngs.wh_x[j]-rngs.rn_size[j]/2,rngs.wh_y[j],rngs.rn_size[j],30,true);

}

//Score Area g.setColor(Color.green); g.drawRect(485,55,310,130);

//Printing of Score g.setColor(Color.red); g.drawString("Score : "+Integer.toString(pts),490,150);

//Congratulationif(win){

g.setColor(Color.cyan); g.drawString("Congratulation !!!",60,150);

By: Amit Kumar Agrawal 446

The Smartest Way to Learn Java5

}}

public synchronized boolean mouseDown(Event ev, int x, int y){

for(int k=0;k<nm_rings;++k) { if(rngs.ordr[k]==twr1.nm_rings[rngs.wh_twr[k]]) { if((x>=(rngs.wh_x[k]-rngs.rn_size[k]/2))&&(x<=((rngs.wh_x[k]-rngs.rn_size[k]/2)+rngs.rn_size[k]))) { if((y>=rngs.wh_y[k])&&(y<=(rngs.wh_y[k]+30))) { pick_ring=k; } } } } return true; }

public synchronized boolean mouseDrag(Event ev, int x, int y){

if(pick_ring!=1000){

rngs.wh_x[pick_ring]=x; rngs.wh_y[pick_ring]=y;

repaint();}return true;}

public synchronized boolean mouseUp(Event ev, int x,int y){

if(pick_ring!=1000){

if((140>=rngs.wh_x[pick_ring])&&(100<=(rngs.wh_x[pick_ring]+rngs.rn_size[pick_ring]))&&(rngs.rn_size[pick_ring]<twr1.tp_size[0]))

{

By: Amit Kumar Agrawal 447

The Smartest Way to Learn Java5

++twr1.nm_rings[0]; --twr1.nm_rings[rngs.wh_twr[pick_ring]]; rngs.wh_twr[pick_ring]=0;

rngs.wh_x[pick_ring]=100;rngs.ordr[pick_ring]=twr1.nm_rings[0];rngs.wh_y[pick_ring]=400-30*twr1.nm_rings[0];

}else

if((280>=rngs.wh_x[pick_ring])&&(240<=(rngs.wh_x[pick_ring]+rngs.rn_size[pick_ring]))&&(rngs.rn_size[pick_ring]<twr1.tp_size[1]))

{++twr1.nm_rings[1];

--twr1.nm_rings[rngs.wh_twr[pick_ring]]; rngs.wh_twr[pick_ring]=1;

rngs.wh_x[pick_ring]=250;rngs.ordr[pick_ring]=twr1.nm_rings[1];rngs.wh_y[pick_ring]=400-30*twr1.nm_rings[1];

}else

if((430>=rngs.wh_x[pick_ring])&&(390<=(rngs.wh_x[pick_ring]+rngs.rn_size[pick_ring]))&&(rngs.rn_size[pick_ring]<twr1.tp_size[2]))

{++twr1.nm_rings[2];

--twr1.nm_rings[rngs.wh_twr[pick_ring]];

rngs.wh_twr[pick_ring]=2;rngs.wh_x[pick_ring]=400;rngs.ordr[pick_ring]=twr1.nm_rings[2];rngs.wh_y[pick_ring]=400-30*twr1.nm_rings[2];

}else{

rngs.wh_x[pick_ring]=rngs.ol_x[pick_ring];rngs.wh_y[pick_ring]=400-

30*twr1.nm_rings[rngs.wh_twr[pick_ring]];}

}rngs.ol_x[pick_ring]=rngs.wh_x[pick_ring];pick_ring=1000;

By: Amit Kumar Agrawal 448

The Smartest Way to Learn Java5

//recompute the to_size for all towersfor(int z=0;z<nm_rings;++z){

if(rngs.ordr[z]==twr1.nm_rings[rngs.wh_twr[z]]){

twr1.tp_size[rngs.wh_twr[z]]=rngs.rn_size[z];}

}

//for if the user wins the matchfor(int t=0;t<3;++t){

if((t!=0)&&(twr1.nm_rings[t]==nm_rings)){

win=true; pts++;

}if(twr1.nm_rings[t]==0){

twr1.tp_size[t]=1000;}

}repaint();return true;

}

public void start(){

if(go==null){

go=new Thread(this);go.start();

}}

public void stop(){

go=null;}

By: Amit Kumar Agrawal 449

The Smartest Way to Learn Java5

public void run(){

while(go!=null){

try{

Thread.sleep(100);}catch(InterruptedException e){}repaint(1,0,0,500,45);

}go=null;

}

public void reset(boolean fill, int nm_blk){

win=false;nm_rings=nm_blk;twr1.reset(nm_rings);rngs.reset(nm_rings);repaint();

}}

class TowerControl extends Panel{

TextField s; TextField e;

TowerPanel pa;

public TowerControl(TowerPanel pa){

this.pa=pa;add(s=new TextField("8",4));add(new Button("Reset Blocks Number"));

}

public boolean action(Event e, Object arg){

By: Amit Kumar Agrawal 450

The Smartest Way to Learn Java5

if(e.target instanceof Button)

{String lbl=(String)arg;pa.reset(lbl.equals("ResetBlocks

Number"),Integer.parseInt(s.getText().trim()));return true;

}return false;

}}

PROJECT OF NUMBER PUZZLE

import java.io.*;import java.lang.*;import java.awt.Graphics;import java.awt.*;import java.applet.*;import java.awt.event.*;import java.lang.String;import javax.swing.*;/*<applet code="game_puzzle.class" width =450 height=400></applet>*/public class game_puzzle extends JApplet implements ActionListener,KeyListener{private MyButton[] button;private JLabel label1,label2,label3,label4;private JTextField textf1,textf2;private String[] Strbutton={"7","8","4","3","6","1","2","5"," ","Start","Restart","Finish"};private String[] Strbutton1={ "1","2","3","4","5","6","7","8"," "};private int click_count;// Counts the number of clicks by the player.GridBagLayout grid = new GridBagLayout();GridBagConstraints gbc1 = newGridBagConstraints();JPanel pan1,pan2;

By: Amit Kumar Agrawal 451

The Smartest Way to Learn Java5

String str1="";public void init()// To initialise different variables.{label1 = new JLabel("Puzzle"); //Initialising the labels.label1.setFont(new Font("Times Roman" , Font.BOLD,20));label1.setForeground(Color.blue);label2=new JLabel("Name of the Player");label2.setFont(new Font("Times Roman" ,Font.BOLD,15));label2.setForeground(Color.blue);label3=new JLabel("Number of the Clicks");label3.setFont(new Font("Times Roman",Font.BOLD,15));label3.setForeground(Color.blue);label4=new JLabel ( " ");button =new MyButton[12];for(int i=0;i<12;i++)//Creating the advanced buttons like sin &cos & arcsin{button[i]= new MyButton ( Strbutton[i],Color.black);button[i].addActionListener(this);}textf1=new JTextField(20);textf2=new JTextField(20);textf1.setFont(new Font("Times Roman",Font.BOLD,12));textf2.setFont(new Font("Times Roman",Font.BOLD,12));textf1.setText("");textf1.addKeyListener(this);textf2.setText("");click_count=0;//Initialise the clicks to zero.displayPanel();// Method displayPanel() //is invoked.} //End of init() method.class MyButton extends JButton{public MyButton(String name, Color xyz){this.setLabel(name);this.setForeground(xyz);}class MouseCalcButtonAdapter extends MouseAdapter{public void mouseEntered(MouseEvent me){}

By: Amit Kumar Agrawal 452

The Smartest Way to Learn Java5

public void mouseExited(MouseEvent me){}}}public void keyTyped(KeyEvent e)//Denotes a key press followed by a keyrelease.{char ch;ch=e.getKeyChar();str1 = str1 + ch;}public void keyPressed(KeyEvent e)//Indicates a key is pushed down.{}public void keyReleased(KeyEvent e)//Indicates a key is Released.{}public void actionPerformed(ActionEvent ae) //Provide the functioningto the game.{int index=8,i;String str,temp,count;boolean check;for(i=0;i<9;i++){if(button[i].getLabel()==" ")index=i;// For checking which button contains theblank label.}if(ae.getSource()==button[9])// For enabling the button after thebutton start is clicked.{for(int j=0;j<=8;j++)button[j].setEnabled(true);button[9].setEnabled(false); //Disable the startbutton.}if(ae.getSource()==button[10])//Restart button.{for(i=0;i<9;i++){button[i].setEnabled(true);button[i].setLabel(Strbutton[i]);}

By: Amit Kumar Agrawal 453

The Smartest Way to Learn Java5

click_count=0;textf2.setText("0");}if((ae.getSource() != button[9]) || (ae.getSource() != button[10]) ){check=checkStatus();if(check==false)// Check whether the number is arranged in thecorrect{if (ae.getSource() == button[0]){count=Integer.toString(countClicks());textf2.setText(count);if (index==1||index==3){str=button[0].getLabel();button[0].setLabel(" ");button[index].setLabel (str);}}if (ae.getSource()== button[1]){count=Integer.toString(countClicks());textf2.setText(count);if (index==0|| index==4 ||index==2){str=button[1].getLabel();button[1].setLabel (" ");button[index]. setLabel(str);}}if (ae.getSource()== button[2]){count=Integer.toString(countClicks());textf2.setText(count);if (index==1||index==5){str=button[2]. getLabel();button[2].setLabel(" ");button[index]. setLabel(str);}

By: Amit Kumar Agrawal 454

The Smartest Way to Learn Java5

}if (ae.getSource()== button[3]){count=Integer.toString(countClicks());textf2.setText(count);if (index==0||index==4 ||index==6){str=button[3].getLabel();button[3].setLabel(" ");button[index].setLabel(str);}}if (ae.getSource()==button[4]){count=Integer.toString(countClicks());textf2.setText(count);if (index==1||index==3 ||index==5||index==7){str=button[4]. getLabel();button[4].setLabel(" ");button[index].setLabel(str);}}if (ae.getSource()==button[5]){count=Integer.toString(countClicks());textf2.setText(count);if (index==2||index==4 ||index==8){str=button[5]. getLabel();button[5].setLabel(" ");button[index].setLabel(str);}}if (ae.getSource()==button[6]){count=Integer.toString(countClicks());textf2.setText(count);if (index==3||index==7){str=button[6].getLabel();

By: Amit Kumar Agrawal 455

The Smartest Way to Learn Java5

button[6].setLabel(" ");button[index].setLabel(str);}}if (ae.getSource()==button[7]){count=Integer.toString(countClicks());textf2.setText(count);if (index==6||index==4 ||index==8){str=button[7]. getLabel();button[7].setLabel(" ");button[index].setLabel(str);}}if (ae.getSource()==button[8])//Exit button.{count=Integer.toString(countClicks());textf2.setText(count);if (index==5||index==7){str=button[8]. getLabel();button[8].setLabel(" ");button[index]. setLabel(str);}}if(ae.getSource()==button[10])//Restart button.{for(i=0;i<9;i++){button[i].setEnabled(true);button[i].setLabel(Strbutton[i]);}click_count=0;textf2.setText("0");}if (ae.getSource()==button[11])//Finish button.{for(i=0;i<=8;i++)

By: Amit Kumar Agrawal 456

The Smartest Way to Learn Java5

{button[i].setLabel (Strbutton1[i]);}click_count=0;textf2.setText("0");button[11].setEnabled(false);button[10].setEnabled(false);}}else//If the game is completed.{String st = str1 + ", you have won the game.";for (int j=0;j<=8;j++)button[j].setEnabled(false);JOptionPane.showMessageDialog(null,st);}}}//End of actionPerformed() method.void displayPanel()// Designing the layout.{JPanel pa4 = new JPanel();pan1 = new JPanel(); // Creating the main panel on which all thecomponent will be placed.// Setting the colour for the interface.pan1.setLayout(grid); // Setting the layout as grid bag layout.gbc1.weightx = 100;gbc1.weighty = 100;gbc1.ipady = 0; //Height of Component.gbc1.ipadx = 0; //Width of Component.gbc1.gridwidth =1;gbc1.gridheight=1;gbc1.gridx = 0;gbc1.gridy = 0;grid.setConstraints(label1, gbc1);pan1.add(label1);// Attaching the label //label1 on the panel pan1.gbc1.weightx=100;gbc1.weighty = 100;gbc1.ipady = 5;//Height of Component.gbc1.ipadx = 5; //Width of Component.gbc1.gridwidth =1;

By: Amit Kumar Agrawal 457

The Smartest Way to Learn Java5

gbc1.gridheight=1;gbc1.gridx = 1;gbc1.gridy = 0;grid.setConstraints(button[9], gbc1);pan1.add(button[9]);gbc1.weightx=100;gbc1.weighty = 100;//Vertical Space.gbc1.ipady = 0; //Height of Component.gbc1.ipadx = 0;gbc1.gridwidth =1;gbc1.gridheight=2;gbc1.gridx = 0;gbc1.gridy = 2;grid.setConstraints(label2, gbc1);pan1.add(label2);gbc1.weightx=100;gbc1.weighty = 100;gbc1.ipady = 0;gbc1.ipadx = 0;gbc1.gridwidth =1;gbc1.gridheight=2;gbc1.gridx = 1;gbc1.gridy = 2;grid.setConstraints(textf1, gbc1);pan1.add(textf1);gbc1.weightx = 100;gbc1.weighty = 100;gbc1.ipady = 0;gbc1.ipadx = 0;gbc1.gridwidth =1 ;gbc1.gridheight=2;gbc1.gridx = 0;gbc1.gridy = 4;pa4.setLayout(new GridLayout(3,3,5,5));for(int i=0;i<9;i++){pa4.add(button[i]);button[i].setEnabled(false);}grid.setConstraints(pa4, gbc1);

By: Amit Kumar Agrawal 458

The Smartest Way to Learn Java5

pan1.add(pa4);gbc1.weightx=100;gbc1.weighty=100;gbc1.ipady = 0;gbc1.ipadx = 0;gbc1.gridwidth =1;gbc1.gridheight=1;gbc1.gridx = 0;gbc1.gridy = 6;grid.setConstraints(label3, gbc1);pan1.add(label3);gbc1.ipady = 0;gbc1.ipadx = 0;gbc1.weightx = 100;gbc1.weighty = 100;gbc1.gridwidth =1 ;gbc1.gridheight=1;gbc1.gridx = 1;gbc1.gridy = 6;grid.setConstraints(textf2, gbc1);pan1.add(textf2);gbc1.ipady = 5;gbc1.ipadx = 5;gbc1.weighty = 100;gbc1.weightx = 100;gbc1.gridwidth =1;gbc1.gridheight=1;gbc1.gridx = 0;gbc1.gridy = 7;grid.setConstraints(button[10], gbc1);pan1.add(button[10]);gbc1.ipady = 5;gbc1.ipadx = 5;gbc1.weighty = 100;gbc1.weightx = 100;gbc1.gridwidth =1;gbc1.gridheight=1;gbc1.gridx = 1;gbc1.gridy = 7;grid.setConstraints(button[11], gbc1);

By: Amit Kumar Agrawal 459

The Smartest Way to Learn Java5

pan1.add(button[11]);gbc1.ipady = 0;gbc1.ipadx = 0;gbc1.weighty = 100;gbc1.weightx = 100;gbc1.gridwidth =1;gbc1.gridheight=1;gbc1.gridx = 0;gbc1.gridy = 8;grid.setConstraints(label4, gbc1);pan1.add(label4);gbc1.ipady = 5;gbc1.ipadx = 5;getContentPane().add(pan1);}// End of the method displayPanel().public int countClicks()// For incrementing the clicks counter.{return(++click_count);}//End countClicks() method.public boolean checkStatus()// To check the game is finish or not.{int i;if (button[0].getLabel() == "1" &&button[1].getLabel() == "2"&&button[2].getLabel() == "3" &&button[3].getLabel() == "4"&&button[4].getLabel() == "5" &&button[5].getLabel() == "6"&&button[6].getLabel() == "7" &&button[7].getLabel() == "8"&&button[8].getLabel() == " "){return(true);}elsereturn(false);}//End checkStatus() method.} // End of game_puzzle class.

By: Amit Kumar Agrawal 460

The Smartest Way to Learn Java5

SPECIALLY DESIGNED TO CRACK (SCJP5.0)(By: R.K.Dash & Amit Kumar Agrawal)

Language Fundamentals

1. Source file’s elements (in order)a. Package declarationb. Import statementsc. Class definitions

2. Importing packages doesn’t recursively import sub-packages.

By: Amit Kumar Agrawal 461

The Smartest Way to Learn Java5

3. Sub-packages are really different packages, happen to live within an enclosing package. Classes in sub-packages cannot access classes in enclosing package with default access.

4. Comments can appear anywhere. Can’t be nested.(No matter what type of comments)

5. At most one public class definition per file. This class name should match the file name. If there are more than one public class definitions, compiler will accept the class with the file’s name and give an error at the line where the other class is defined.

6. It’s not required having a public class definition in a file. Strange, but true. ☺ In this case, the file’s name should be different from the names of classes and interfaces (not public obviously).

7. Even an empty file is a valid source file.8. An identifier must begin with a letter, dollar sign ($) or underscore (_).

Subsequent characters may be letters, $, _ or digits.9. An identifier cannot have a name of a Java keyword. Embedded

keywords are OK. true, false and null are literals (not keywords), but they can’t be used as identifiers as well.

10. const and goto are reserved words, but not used.11. Unicode characters can appear anywhere in the source code. The

following code is valid.

ch\u0061r a = 'a';

char \u0062 = 'b';

char c = '\u0063';

By: Amit Kumar Agrawal 462

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 463

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 464

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 465

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 466

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 467

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 468

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 469

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 470

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 471

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 472

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 473

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 474

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 475

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 476

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 477

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 478

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 479

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 480

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 481

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 482

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 483

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 484

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 485

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 486

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 487

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 488

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 489

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 490

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 491

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 492

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 493

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 494

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 495

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 496

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 497

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 498

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 499

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 500

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 501

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 502

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 503

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 504

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 505

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 506

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 507

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 508

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 509

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 510

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 511

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 512

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 513

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 514

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 515

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 516

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 517

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 518

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 519

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 520

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 521

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 522

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 523

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 524

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 525

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 526

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 527

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 528

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 529

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 530

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 531

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 532

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 533

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 534

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 535

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 536

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 537

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 538

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 539

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 540

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 541

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 542

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 543

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 544

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 545

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 546

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 547

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 548

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 549

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 550

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 551

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 552

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 553

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 554

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 555

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 556

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 557

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 558

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 559

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 560

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 561

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 562

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 563

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 564

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 565

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 566

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 567

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 568

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 569

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 570

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 571

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 572

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 573

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 574

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 575

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 576

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 577

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 578

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 579

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 580

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 581

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 582

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 583

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 584

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 585

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 586

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 587

The Smartest Way to Learn Java5

FEW SCJP5.0 QUESTION WITH ANSWERS:

Q1:

Which collection would be the best one to use, if you were working with a Student Information management web application that needs to maintain and search students, stored as instances of a class 'Student'. You should be able to perform the following:

i) identify a Student by its unique alphanumeric identification number. ii) Print out the Student in order of their unique identification numbers

A) List B) ArrayList C) HashMap D) TreeMap E) HashSet F) Arrays G) LinkedList H) Sets

Answer : D (TreeMap)

Explanation :

Option D is correct. Both HashMap and TreeMap enable storing a 'key' and a 'value' combination, where the values and keys can be objects, and the objects are searchable on their keys. However, only TreeMap maintains the natural order of the keys.

Q2:

What is the output of the following code?

//Cafe4JavaSCJP3TreeMapimport java.util.*;

public class Cafe4JavaSCJP3TreeMap {public static void main (String args[]) {

TreeMap treeMap = new TreeMap();ShoppingCartItem item = new

ShoppingCartItem("BOOK234");treeMap.put (item.getSerialNumber(), item);item = new ShoppingCartItem("VCD1464");treeMap.put (item.getSerialNumber(), item);

item = new ShoppingCartItem("PT652");treeMap.put (item.getSerialNumber(), item);for (ShoppingCartItem iterItem: treeMap.values())

By: Amit Kumar Agrawal 588

The Smartest Way to Learn Java5

System.out.println (iterItem.getSerialNumber());

}}

class ShoppingCartItem {private String serialNumber;private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}public void setDescription(String val) {

description = val;}

}

A)

BOOK234PT652VCD1464

B)

BOOK234VCD1464PT652

C)

PT652VCD1464BOOK234

D) The order cannot be determined. Each execution of this code may print out a random order

Answer : A

BOOK234PT652VCD1464

By: Amit Kumar Agrawal 589

The Smartest Way to Learn Java5

Explanation :

Only Option A is correct. TreeMap is a sorted and ordered collection, which returns objects

sorted on its keys. In this example code, the keys of TreeMap are objects of String class

and the values are objects of ShoppingCartItem class. The class String implements the

Comparable Interface, which enables TreeMap to sort its values on its keys.

Q3:

Which collection would you use if you were working with an e-commerce application that

needs to maintain and search shopping cart items, stored as instances of a class

'ShoppingCartItem'. You should be able to identify a shopping cart item by its unique

alphanumeric serial number.

A) List

B) ArrayList

C) Map

D) HashSet

E) Arrays

F) LinkedList

G) Sets

Answer : C (Map)

Explanation :

Only Option C is correct because implementations of interface 'Map' enable storing a 'key'

and a 'value' combination, where the values and keys can be objects, and the objects are

searchable on their keys.

Q4:

Which class is the best option for storing/ accessing a list of objects, which need to be modified rarely?

A) Vector B) ArrayList C) List

By: Amit Kumar Agrawal 590

The Smartest Way to Learn Java5

D) Queue E) SortedSet F) Set

Answer : B (ArrayList)

Explanation :

Only Option B is correct. As per the question, we need to identify a 'class' here, not an 'Interface'. Both option A (Vector) and Option B (ArrayList) are classes, which can be used to store and retrieve a list of objects. Vector and ArrayList offer the same functionality, however, the methods of class Vector are synchronized, whereas the methods of class ArrayList are not synchronized. If a list rarely needs to be modified, class ArrayList is a better option than the class Vector because synchronization has performance/ resources overheads.

Q5:

What is the output of the following code? //Cafe4JavaSCJP3LinkedHashMapimport java.util.*;

public class Cafe4JavaSCJP3LinkedHashMap {public static void main (String args[]) {

LinkedHashMap map = new LinkedHashMap();

ShoppingCartItem item = new ShoppingCartItem("BOOK234Cafe4Java");

map.put (item.getSerialNumber(), item);

item = new ShoppingCartItem("VCD1464Cafe4Java");map.put (item.getSerialNumber(), item);

item = new ShoppingCartItem("PT652Cafe4Java");map.put (item.getSerialNumber(), item);

item = new ShoppingCartItem("BOOK234Cafe4Java");map.put (item.getSerialNumber(), item);

for (ShoppingCartItem iterItem: map.values())System.out.println

(iterItem.getSerialNumber());}

}

By: Amit Kumar Agrawal 591

The Smartest Way to Learn Java5

class ShoppingCartItem {private String serialNumber;private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}public void setDescription(String val) {

description = val;}

} A)

BOOK234Cafe4JavaVCD1464Cafe4JavaPT652Cafe4JavaBOOK234Cafe4Java

B)

BOOK234Cafe4JavaVCD1464Cafe4JavaPT652Cafe4Java

C)

VCD1464Cafe4JavaPT652Cafe4JavaBOOK234Cafe4Java

D)

BOOK234Cafe4JavaPT652Cafe4JavaVCD1464Cafe4Java

E)

BOOK234Cafe4JavaBOOK234Cafe4JavaPT652Cafe4JavaVCD1464Cafe4Java

F) None of the above

By: Amit Kumar Agrawal 592

The Smartest Way to Learn Java5

Answer : B

BOOK234Cafe4JavaVCD1464Cafe4JavaPT652Cafe4Java

Explanation :

Only option 'B' is correct because LinkedHashMap defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

Q6:

Which of the following statements are correct? A) java.util.Collection is a class. B) java.util.Collection is an Interface. C) java.util.Collections is a class. D) java.util.Collections is an Interface

Answer : B (java.util.Collection is an Interface) and C (java.util.Collections is a class)

Q7:

Which collection would you use if you were working with a Hotel Management web application that needs to maintain and search the customers that checks in the hotel. Customer data is stored as an instance of a class 'HotelCustomer'.

You should be able to perform the following:

i) identify a Customer by its unique alphanumeric identification number. ii) Keep Track of the customers in the order they checked-in the hotel. iii) Search a customer on its key.

A) List B) ArrayList C) HashMap D) TreeMap E) HashSet F) Arrays G) LinkedHashMap H) Sets

Answer : G (LinkedHashMap)

Explanation :

By: Amit Kumar Agrawal 593

The Smartest Way to Learn Java5

Option G is correct. LinkedHashMap enables storing a 'key' and a 'value' combination, where the values and keys can be objects, and the objects are searchable on their keys. LinkedHashMap defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Q8:

What is the output of the following code? //Cafe4JavaSCJP3TreeSetimport java.util.*;

public class Cafe4JavaSCJP3TreeSet {public static void main (String args[]) {

TreeSet setString = new TreeSet();

setString.add("BOOK234-Str");setString.add("AVCD1464-Str");setString.add("PT652-Str");

Iterator iterString = setString.iterator();while (iterString.hasNext())

System.out.println (iterString.next());

System.out.println ();

TreeSet setShoppingCart = new TreeSet();

ShoppingCartItem item = new ShoppingCartItem("BOOK234:ShopCart");

setShoppingCart.add (item);

item = new ShoppingCartItem("AVCD1464:ShopCart");setShoppingCart.add (item);

item = new ShoppingCartItem("PT652:ShopCart");setShoppingCart.add (item);

Iterator iterShoppingCart = setShoppingCart.iterator();

while (iterShoppingCart.hasNext())System.out.println

(iterShoppingCart.next().getSerialNumber());}

}

class ShoppingCartItem {private String serialNumber;

By: Amit Kumar Agrawal 594

The Smartest Way to Learn Java5

private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}public void setDescription(String val) {

description = val;}

} A)

OOK234-StrVCD1464-StrT652-Str

OOK234:ShopCartT652:ShopCartVCD1464:ShopCart

B)

T652-StrOOK234-StrVCD1464-Str

BOOK234:ShopCartPT652:ShopCartAVCD1464:ShopCart

C)

AVCD1464-StrBOOK234-StrPT652-Str

AVCD1464:ShopCartBOOK234:ShopCartPT652:ShopCart

D)

By: Amit Kumar Agrawal 595

The Smartest Way to Learn Java5

AVCD1464-StrBOOK234-StrPT652-Str

AVCD1464:ShopCartBOOK234:ShopCartPT652:ShopCart

E) Compilation error F) Runtime Error G) None of the above.

Answer : F (Runtime Error)

Explanation :

TreeSet is a sorted and ordered collection. This class guarantees that the elements will be in ascending order, either according to the natural order (defined by the Comparable or Comparator Interface) or custom comparison rules. Class String implements the Comparable interface and defines the 'compareTo' method, which enables the class TreeSet to sort elements of type 'String'. However the class 'ShoppingCartItem' does not implements the Comparable Interface and hence TreeSet is unable to sort its elements. As a result, the above code throws a Runtime exception

Q9:

Which of the following class would you use to store values with no duplicates? A) HashSet B) Set C) List D) Collection E) A and B

Answer : A (HashSet)

Explanation :

Option B, C, D and E are incorrect because Set, List and Collection are interfaces, not classes

Q10:

Examine the following code and select the modification that will enable the code to execute without any exceptions.

//Cafe4JavaSCJP3TreeSet

import java.util.*;

By: Amit Kumar Agrawal 596

The Smartest Way to Learn Java5

public class Cafe4JavaSCJP3TreeSet {public static void main (String args[]) {

TreeSet setString = new TreeSet();

setString.add("BOOK234-Str");setString.add("AVCD1464-Str");setString.add("PT652-Str");

Iterator iterString = setString.iterator();while (iterString.hasNext())

System.out.println (iterString.next());

TreeSet setShoppingCart = new TreeSet();

ShoppingCartItem item = new ShoppingCartItem("BOOK234:ShopCart");

setShoppingCart.add (item);

item = new ShoppingCartItem("AVCD1464:ShopCart");setShoppingCart.add (item);

item = new ShoppingCartItem("PT652:ShopCart");setShoppingCart.add (item);

Iterator iterShoppingCart = setShoppingCart.iterator();

while (iterShoppingCart.hasNext())System.out.println

(iterShoppingCart.next().getSerialNumber());}

}

class ShoppingCartItem {private String serialNumber;private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}

By: Amit Kumar Agrawal 597

The Smartest Way to Learn Java5

public void setDescription(String val) {description = val;

}}

A)

class ShoppingCartItem implements Comparable{private String serialNumber;

private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}public void setDescription(String val) {

description = val;}public int compareTo(Object o) {

return this.serialNumber.compareTo( ((ShoppingCartItem)o).getSerialNumber());

}} B)

class ShoppingCartItem implements Comparable{private String serialNumber;

private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}public void setDescription(String val) {

By: Amit Kumar Agrawal 598

The Smartest Way to Learn Java5

description = val;}public int compareObjects(Object o) {

return this.serialNumber.compareTo( ((ShoppingCartItem)o).getSerialNumber());

}} C)

class ShoppingCartItem implements Comparable{private String serialNumber;

private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}

public String getSerialNumber() {return serialNumber;

}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}public void setDescription(String val) {

description = val;}public int compare(Object o) {

return this.serialNumber.compareTo(((ShoppingCartItem)o).getSerialNumber());

}} D)

class ShoppingCartItem implements Comparable{private String serialNumber;

private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}

By: Amit Kumar Agrawal 599

The Smartest Way to Learn Java5

public String getDescription() {return description;

}public void setDescription(String val) {

description = val;}public int equals(Object o) {

return this.serialNumber.compareTo( ((ShoppingCartItem)o).getSerialNumber());

}}

Answer : A

class ShoppingCartItem implements Comparable{private String serialNumber;private String description;public ShoppingCartItem (String sNo) {

setSerialNumber(sNo);}public String getSerialNumber() {

return serialNumber;}public void setSerialNumber(String val) {

serialNumber = val;}public String getDescription() {

return description;}public void setDescription(String val) {

description = val;}public int compareTo(Object o) {

return this.serialNumber.compareTo( ((ShoppingCartItem)o).getSerialNumber());

}}

Explanation :

TreeSet is a sorted and ordered collection. This class guarantees that the elements will be in ascending order, either according to the natural order (defined by the Comparable or Comparator Interface) or custom comparison rules. Class String implements the Comparable interface and defines the 'compareTo' method, which enables the class TreeSet to sort elements of type 'String'. Class 'ShoppingCartItem' can be made to implement the Interface Comparable, to ensure that the elements of the

By: Amit Kumar Agrawal 600

The Smartest Way to Learn Java5

ShoppingCartItem can be sorted. Interface Comparable defines the following method, which should be implemented by the class ShoppingCartItem: public int compareTo(Object o);

Q11

Examine the following code and select the correct options, which when inserted at line number 6, will compile/ execute successfully and read/ write 'Cafe4Java' to file 'Cafe4Java.txt'.

line1> // Cafe4JavaE2Q1

line2> import java.io.*;

line3> public class Cafe4JavaE2Q1{

line4> public static void main (String args[]) throws Exception {

line5> File file = new File ("Cafe4Java.txt");

line6> //// INSERT CODE HERE ////

line7> w.write ("Cafe4Java", 0, 9);

line8> w.flush();

line9> w.close();

line10> System.out.println(new BufferedReader (new FileReader

(file)).readLine());

line11> }

line12>}

A)

BufferedWriter w = new BufferedWriter (new PrintWriter (new FileWriter (file))); B)

BufferedWriter w = new BufferedWriter (new FileWriter (new PrintWriter (file))); C)

PrintWriter w = new PrintWriter (new FileWriter (new BufferedWriter (file))); D)

By: Amit Kumar Agrawal 601

The Smartest Way to Learn Java5

PrintWriter w = new PrintWriter (new BufferedWriter (new FileWriter (file))); E)

FileWriter w = new FileWriter (new BufferedWriter (new PrintWriter (file))); F)

FileWriter w = new FileWriter (new PrintWriter (new BufferedWriter (file)));

Answer : A, D

Explanation :

Options B, C, E and F will not compile. Read the questions from number 2 - 11, which cover all the permutations of the classes BufferedWriter, PrintWriter and FileWriter and explain which combinations are correct and why. Q12

What is the output of the following code?

// Cafe4JavaE2Q2import java.io.*;

public class Cafe4JavaE2Q2 { public static void main (String args[]) throws Exception { File f = new File ("Cafe4Java.txt"); f.write ("Cafe4Java", 0, 4); f.flush(); f.close(); FileReader fr = new FileReader ("Cafe4Java.txt"); BufferedReader br = new BufferedReader (fr); String text = br.readLine(); System.out.println (text); }}

A) The code throws a runtime exception. B) The code fails to compile. C) The code prints out the following value:

Cafe4Java D) The code prints out the following value:

By: Amit Kumar Agrawal 602

The Smartest Way to Learn Java5

Cafe

Answer : B

Explanation :

The following lines of code will not compile:

f.write ("Cafe4Java", 0, 4);f.flush();f.close();The class java.io.File does not defines the methods 'write', flush' and 'close'. Object of class 'File' is an abstract representation of file and directory pathnames. You can use a File class to create the physical files (method 'createNewFile') You cannot use object of class File to write to read from an actual, physical file. To do so, you need to 'wrap' it in a 'reader'/ 'writer' object. For example, to write to a file, you need to wrap it in a FileWriter/ PrintWriter.

Q13:

What is the output of the following code?

// Cafe4JavaE2Q3

import java.io.*;

public class Cafe4JavaE2Q3 {

public static void main (String args[]) throws Exception {

File file = new File ("Cafe4Java.txt");

FileWriter fw = new FileWriter (file);

fw.write ("Cafe4Java", 0, 9);

fw.flush();

fw.close();

System.out.println(new BufferedReader (new FileReader

(file)).readLine());

}

}

A) The code prints out:

Cafe4Java

By: Amit Kumar Agrawal 603

The Smartest Way to Learn Java5

B) The code prints out:

Cafe C) The code fails to compile. D) The code throws a runtime exception

Answer : A

Explanation :

You can create an object of class File and 'wrap' it in an object of class 'FileWriter' to write to it.

Q14:

What is the output of the following code?

// Cafe4JavaE2Q4import java.io.*;

public class Cafe4JavaE2Q4 { public static void main (String args[]) throws Exception { File file = new File ("Cafe4Java.txt"); PrintWriter pw = new PrintWriter (file); pw.write ("Cafe4Java", 0, 9); pw.flush(); pw.close(); System.out.println(new BufferedReader (new FileReader (file)).readLine()); }}

A) The code compiles successfully, but fails to execute without exceptions. B) The code fails to compile. C) The code prints out:

Cafe D) The code prints out:

Cafe4Java

Answer : D

Explanation :

By: Amit Kumar Agrawal 604

The Smartest Way to Learn Java5

You can create an object of class File and 'wrap' it in an object of class 'PrintWriter' to write to it.

Q15:

What is the output of the following code?

// Cafe4JavaE2Q5import java.io.*;

public class Cafe4JavaE2Q5{ public static void main (String args[]) throws Exception { File file = new File ("Cafe4Java.txt"); BufferedWriter bw = new BufferedWriter (file); bw.write ("Cafe4Java", 0, 9); bw.flush(); bw.close(); System.out.println(new BufferedReader (new FileReader (file)).readLine()); }}

A) The code compiles successfully, but fails to execute without exceptions. B) The code fails to compile. C) The code prints out:

Cafe D) The code prints out:

Cafe4Java

Answer : B (The code fails to compile)

Explanation :

The following line fails to compile: BufferedWriter bw = new BufferedWriter (file);

The compilation error message is as follows:

cannot find symbolsymbol : constructor BufferedWriter(java.io.File)location: class java.io.BufferedWriter

BufferedWriter bw = new BufferedWriter (file);

By: Amit Kumar Agrawal 605

The Smartest Way to Learn Java5

You cannot create an object of class File and 'wrap' it in an object of class 'BufferedWriter' to write to it.

The signature of the constructors of class BufferedWriter are:

BufferedWriter(Writer out)BufferedWriter(Writer out, int sz)

An object of class BufferedWriter cannot be constructed by passing it an object of class File.

Q16:

What is the output of the following code?

// Cafe4JavaE2Q6import java.io.*;

public class Cafe4JavaE2Q6{ public static void main (String args[]) throws Exception { File file = new File ("Cafe4Java.txt"); PrintWriter pw = new PrintWriter(new BufferedWriter (file)); pw.write ("Cafe4Java", 0, 9); pw.flush(); pw.close(); System.out.println(new BufferedReader (new FileReader (file)).readLine()); }}

A) The code compiles successfully, but fails to execute without exceptions. B) The code fails to compile. C) The code prints out:

Cafe D) The code prints out:

Cafe4Java

Answer : B (The code fails to compile)

Explanation :

Though this question has tried to create an object of class PrintWriter, using an object of

class BufferedWriter, an object of class BufferedWriter cannot be constructed by passing it

an object of class File.

By: Amit Kumar Agrawal 606

The Smartest Way to Learn Java5

In short, if the following cannot compile: new BufferedWriter (file);

The following will also not compile: PrintWriter pw = new PrintWriter(new BufferedWriter

(file));

Q17

What is the output of the following code?

// Cafe4JavaE2Q7import java.io.*;

public class Cafe4JavaE2Q7{ public static void main (String args[]) throws Exception { File file = new File ("Cafe4Java.txt");

PrintWriter pw = new PrintWriter(new FileWriter (file));

pw.write ("Cafe4Java", 0, 9);

pw.flush();

pw.close();

System.out.println(new BufferedReader (new FileReader

(file)).readLine());

}}

A) The code prints out:

Cafe4Java B) The code prints out:

Cafe C) The code fails to compile. D) The code throws a runtime exception

Answer : A (The code prints out: Cafe4Java)

Explanation :

This is an example of creating an object of PrintWriter using FileWriter and File.

By: Amit Kumar Agrawal 607

The Smartest Way to Learn Java5

An object of class PrintWriter can be created by passing it an object of class Writer (Class

FileWriter extends class Writer) and an object of class FileWriter can be created by

passing it an object of class File.

Q18

What is the output of the following code?

// Cafe4JavaE2Q8import java.io.*;

public class Cafe4JavaE2Q8{ public static void main (String args[]) throws Exception { File file = new File ("Cafe4Java.txt"); FileWriter fw = new FileWriter(new PrintWriter (file)); fw.write ("Cafe4Java", 0, 9); fw.flush(); fw.close(); System.out.println(new BufferedReader (new FileReader (file)).readLine()); }}

A) The code prints out:

Cafe4Java B) The code prints out:

Cafe C) The code fails to compile. D) The code throws a runtime exception

Answer : C (Code does not compile)

Explanation :

The following line of code will not compile: FileWriter fw = new FileWriter(new PrintWriter (file));

Compilation error message is as follows: cannot find symbolsymbol : constructor FileWriter(java.io.PrintWriter)location: class java.io.FileWriter

FileWriter fw = new FileWriter(new PrintWriter (file));

By: Amit Kumar Agrawal 608

The Smartest Way to Learn Java5

You cannot pass an object of class PrintWriter to create an object of class FileWriter.

Q19

What is the output of the following code?

// Cafe4JavaE2Q9import java.io.*;

public class Cafe4JavaE2Q9{ public static void main (String args[]) throws Exception { File file = new File ("Cafe4Java.txt"); FileWriter fw = new FileWriter(new BufferedWriter (file)); fw.write ("Cafe4Java", 0, 9); fw.flush(); fw.close(); System.out.println(new BufferedReader (new FileReader (file)).readLine()); }}

A) The code prints out:

Cafe4Java B) The code prints out:

Cafe C) The code fails to compile. D) The code throws a runtime exception

Answer : C (Code does not compile)

Explanation :

The following line of code will not compile: FileWriter fw = new FileWriter(new BufferedWriter (file));

Compilation error message is as follows: cannot find symbolsymbol : constructor BufferedWriter(java.io.File)location: class java.io.BufferedWriter

FileWriter fw = new FileWriter(new BufferedWriter (file));You cannot pass an object of class File to create an object of class BufferedWriter

By: Amit Kumar Agrawal 609

The Smartest Way to Learn Java5

Q20:

What is the output of the following code?

// Cafe4JavaE2Q10import java.io.*;

public class Cafe4JavaE2Q10{

public static void main (String args[]) throws Exception {

File file = new File ("Cafe4Java.txt");

BufferedWriter bw = new BufferedWriter (new FileWriter (file));

bw.write ("Cafe4Java", 0, 9);

bw.flush();

bw.close();

System.out.println(new BufferedReader (new FileReader

(file)).readLine());

}}

A) The code prints out:

Cafe4Java B) The code prints out:

Cafe C) The code fails to compile. D) The code throws a runtime exception.

Answer : A (Cafe4Java)

Explanation :

There are no errors with the following line of code: FileWriter fw = new FileWriter(new BufferedWriter (file));

By: Amit Kumar Agrawal 610

The Smartest Way to Learn Java5

Q21

What is the output of the following code?

// Cafe4JavaE2Q11import java.io.*;

public class Cafe4JavaE2Q11{ public static void main (String args[]) throws Exception { File file = new File ("Cafe4Java.txt"); BufferedWriter bw = new BufferedWriter (new PrintWriter (file)); bw.write ("Cafe4Java", 0, 9); bw.flush(); bw.close(); System.out.println(new BufferedReader (new FileReader (file)).readLine()); }}

A) The code prints out:

Cafe4Java B) The code prints out:

Cafe C) The code fails to compile. D) The code throws a runtime exception.

Answer : A (Cafe4Java)

Explanation :

There are no errors with the following line of code:

BufferedWriter bw = new BufferedWriter (new PrintWriter (file));

Q22:

By: Amit Kumar Agrawal 611

The Smartest Way to Learn Java5

What is the output of class TestCafe4Java?

class SuperCafe4Java {public Object get () {

return ("SuperCafe4Java");}

}

class SubCafe4Java extends SuperCafe4Java {public String get () {

return ("SubCafe4Java");}

}

class TestCafe4Java {public static void main (String[] arguments) {

SuperCafe4Java superFoo;SubCafe4Java subFoo;

superFoo = new SubCafe4Java();System.out.println (superFoo.get());

subFoo = new SubCafe4Java();superFoo = subFoo;System.out.println (superFoo.get());

}}

A)

SubCafe4JavaSubCafe4Java

B)

SuperCafe4JavaSuperCafe4Java

C)

SubCafe4JavaSuperCafe4Java

D)

SuperCafe4JavaSubCafe4Java

E) Compilation Error

By: Amit Kumar Agrawal 612

The Smartest Way to Learn Java5

Answer : A

Explanation : B) Option B is incorrect. The method get() is overridden in class SubCafe4Java class. In

Java5, an overriding method can define a return type, which is a sub-class of the return type of the method in the super class. In case of overridden methods, the method that is invoked depends on the type of the actual object on which it is invoked, and not on the type of the reference variable, which is used to refer to an object.

C) Option C is incorrect. The method get() is overridden in class SubCafe4Java class. In Java5, an overriding method can define a return type, which is a sub-class of the return type of the method in the super class. In case of overridden methods, the method that is invoked depends on the type of the actual object on which it is invoked, and not on the type of the reference variable, which is used to refer to an object.

D) Option D is incorrect. The method get() is overridden in class SubCafe4Java class. In Java5, an overriding method can define a return type, which is a sub-class of the return type of the method in the super class. In case of overridden methods, the method that is invoked depends on the type of the actual object on which it is invoked, and not on the type of the reference variable, which is used to refer to an object.

E) Option E is incorrect because the code compiles successfully. F) Option F is incorrect because the code executes without any exceptions. G) Option G is incorrect because the code executes without any errors.

Q22:

What is the output of class TestCafe4Java, if the class SubCafe4Java is compiled as follows (using JDK 1.5)?

javac -source 1.4 SubCafe4Java.java:

class SuperCafe4Java {public Object get () {

return ("SuperCafe4Java");}

}

class SubCafe4Java extends SuperCafe4Java {public String get () {

return ("SubCafe4Java");}

}

class TestCafe4Java {public static void main (String[] arguments) {

SuperCafe4Java superFoo;SubCafe4Java subFoo;

superFoo = new SubCafe4Java();

System.out.println (superFoo.get());

By: Amit Kumar Agrawal 613

The Smartest Way to Learn Java5

subFoo = new SubCafe4Java();

superFoo = subFoo;

System.out.println (superFoo.get());}

}

A)

SubCafe4JavaSubCafe4Java

B)

SuperCafe4JavaSuperCafe4Java

C)

SubCafe4JavaSuperCafe4Java

D)

SuperCafe4JavaSubCafe4Java

E) Compilation Error

F) Runtime Exception

G) Runtime Error

Answer : E

Explanation : A) Option A is incorrect. Covariant returns are valid starting from J2SE5.0 for overridden

methods. Prior to J2SE 5.0, an overriding method could not return a data type that is a subclass of the return type of the method defined in the Super class. Class 'SubCafe4Java' will fail to compile with the error 'attempting to use incompatible return type'. (String is a subclass of Object). However, covariant returns are valid in J2SE5.0.

B) Option B is incorrect. Covariant returns are valid starting from J2SE5.0 for overridden methods. Prior to J2SE 5.0, an overriding method could not return a data type that is a subclass of the return type of the method defined in the Super class. Class 'SubCafe4Java' will fail to compile with the error 'attempting to use incompatible return type'. (String is a subclass of Object). However, covariant returns are valid in J2SE5.0.

C) Option C is incorrect. Covariant returns are valid starting from J2SE5.0 for overridden methods. Prior to J2SE 5.0, an overriding method could not return a data type that is a

By: Amit Kumar Agrawal 614

The Smartest Way to Learn Java5

subclass of the return type of the method defined in the Super class. Class 'SubCafe4Java' will fail to compile with the error 'attempting to use incompatible return type'. (String is a subclass of Object). However, covariant returns are valid in J2SE5.0.

D) Option D is incorrect. Covariant returns are valid starting from J2SE5.0 for overridden methods. Prior to J2SE 5.0, an overriding method could not return a data type that is a subclass of the return type of the method defined in the Super class. Class 'SubCafe4Java' will fail to compile with the error 'attempting to use incompatible return type'. (String is a subclass of Object). However, covariant returns are valid in J2SE5.0.

F) Option F is incorrect because the code fails to compile. G) Option G is incorrect because the code fails to compile.

Q23:

Which of the following statements are true with respect to the Covariant return types? A) An overriding method, should define exactly same set of argument list, as the overridden

method, or else we will end up defining an overloaded method. This includes the covariant data types, i.e., if any argument in the overriding method is a subclass of the argument defined in the super class, we will end up defining an overloaded method.

B) A valid overriding method can define a return type, which is a subclass of the return type defined by the Overridden method in the super class.

C) Option B can be applied to JDK 1.4 compiler also. D) None of the above.

Answer : A, BExplanation :

C) Option C is incorrect because covariant returns are not accepted as valid return type, prior to J2SE 5.0.

D) Option D is incorrect because options A and B are correct.

Q24:

Select all the correct statements regarding Enums (Select any 2 options) a) All enums are subclasses of interface java.lang.Enum. b) Enums is simply a data structure and hence it is not compiled to a .class file. c) Enums enable you to define a new data type. For example, If you create an

Enum 'Days' you can declare a variable of type 'Days'. d) All instances of Enums are serializable by default.

Answer : c, dExplanation :

a) java.lang.Enum is a class and not an interface. b) Enums are compiled to a .class file. c) Enums enable you to define a new data type, in a manner similar to the way a

class allows you to define a new data type.

By: Amit Kumar Agrawal 615

The Smartest Way to Learn Java5

d) Enums are subclasses of class java.lang.Enum, which implements the interface java.io.Serializable. If a class implements the interface java.io.Serialisable, its objects are serializable

Q25:

What is the output of the following code:

line1> public enum IceCream {line2> VANILLA ("white"),line3> STRAWBERRY ("pink"),line4> WALNUT ("brown"),line5> CHOCOLATE ("dark brown");line6>line7> String color;line8>line9> IceCream (String color) {line10> this.color = color;line11> }line12>line13> public static void main (String[] args) {line14> System.out.println (VANILLA);line15> System.out.println (CHOCOLATE);line16> }line17> }

Options: a) Compilation error : Cannot run an enum as a standalone application. b) Compilation error at line no 14 & 15 : Cannot access VANILLA and

CHOLOCLATE in 'static' main method. c) No errors. Output:

VANILLACHOCOLATE

d) No errors. Output:

white

dark brown

Answer : c

Explanation : a) An enum can define a main method and it can be executed as a standalone

application.

By: Amit Kumar Agrawal 616

The Smartest Way to Learn Java5

b) The instances of enums defined in an enum are static and hence available to any static method defined within the enum.

d) The overridden toString method in the Enum class returns the name of this enum constant, as contained in the declaration. You can override the toString method to return a customised String value

Q26:

What is the output of the following code: line1> public enum Day {line2> MONDAY (1),line3> TUESDAY (2),line4> WEDNESDAY (3) {public String toString() {

return "Good Morning"; } },line5> THURSDAY (4),line6> FRIDAY (5),line7> SATURDAY (6),line8> SUNDAY (7);line9>line10> int dayNumber;line11>line12> Day (int dayNumber) {line13> this.dayNumber = dayNumber;line14> }line15>line16> public static void main (String[] args) {line17> for (Day d : Day.values())line18> System.out.println (d);line19> }line20> }Options:

a) Compilation error at line number 4 : Invalid code. b) Executes OK giving OUTPUT:

MONDAYTUESDAYGood MorningTHURSDAYFRIDAYSATURDAYSUNDAY

c) Runtime error : Cannot execute enum 'Day' as a standalone application. d) Executes OK giving OUTPUT:

MONDAYTUESDAY

By: Amit Kumar Agrawal 617

The Smartest Way to Learn Java5

WEDNESDAYTHURSDAYFRIDAYSATURDAYSUNDAY

Answer : b Explanation :

a) The code is valid. A single instance of enum can override the methods available to it.

c) An enum can define a main method and it can be executed as a standalone application.

d) The toString method for enum instance 'WEDNESDAY' returns 'Good Morning'

Q27:

Examine the following code and select the correct options: enum Rating {

AVERAGE,GOOD,EXCELLENT;

abstract String performance();}

class Test {public static void main (String[] args) {

System.out.println (Rating.AVERAGE);}

} a) What rubbish, An Enum can never define an abstract method. b) class Test cannot access the enum constant AVERAGE using the code

"Rating.AVERAGE". c) The above mentioned code will fail to compile. d) If the enum 'Ratings' is defined as an abstract 'enum', it will compile successfully

Answer : cExplanation : The code will fail to compile because the abstract method 'performance' needs to be implemented by all the enum constants, i.e., AVERAGE, GOOD and EXCELLENT.

a) It is OK to define an abstract method in an enum. b) Since Enum is not defined in class Test, its constant 'AVERAGE' should be

prefixed with the Enum name 'Ratings' to access it in class Test. d) We cannot define abstract enums.

Q28:

By: Amit Kumar Agrawal 618

The Smartest Way to Learn Java5

Examine the following code and select the correct options that follow: line1> public enum IceCream {line2> VANILLA ("white"),line3> STRAWBERRY ("pink"),line4> WALNUT ("brown"),line5> CHOCOLATE ("dark brown");line6>line7> String color;line8>line9> IceCream (String color) {line10> this.color = color;line11> }line12> }line13>line14> public class Test {line15> public static void main (String[] args) {line16> IceCream vanilla = new IceCream ("white");line17> System.out.println ( vanilla );line18> }line19> }

a) The code prints out 'white'. b) The code prints out 'VANILLA'. c) The code fails at runtime. d) Enums may not be instantiated.

Answer : d

Explanation : Enums cannot be instantiated. The code mentioned in this question will not compile.

Q29:

Examine the following code: line1> enum Size {line2> XS ("Extra Small") { int age() { return 5; }},

line3> S ("Small") { int age() { return 8; }},

line4> M ("Medium") { int age() { return 10; }},

line5> L ("Large") { int age() { return 15; }},

line6> XL ("Extra Large") { int age() { return 20; }};

line7>line8> String description;

line9>

By: Amit Kumar Agrawal 619

The Smartest Way to Learn Java5

line10> Size (String desc) {

line11> this.description = desc;

line12> }

line13>

line14> > // INSERT CODE HERE

line15> }

line16>

line17> class Test {

line18> public static void main (String[] args) {

line19> for (Size size : Size.values())

line20> System.out.println (size);

line21> }

line22> }

Select the correct lines of code, which when inserted at line number 14, will print out the following output:

XSSMLXL

Options: a) int age() { return 0; } b) abstract int age(); c) short age() { return 100; } d) abstract short age();

Answer: a, b

Explanation : Since all the enum constants, i.e., XS, S, M, L, XL implement the age method, this method can either be defined as a non-abstract method, or as an abstract method.

Options c and d are not valid because the method "short age()" cannot override the method "int age()".

c) The method "short age() { return 100; }" cannot override either of the methods "int age()" and "abstract int age()".

d) The method "abstract short age() { return 100; }" cannot override either of the methods "int age()" and "abstract int age()".

By: Amit Kumar Agrawal 620

The Smartest Way to Learn Java5

Q30:

Examine the following code: import java.util.*;

enum Colours {YELLOW (Personality.EXPRESSIVE),GREEN (Personality.AMIABLE),RED (Personality.ASSERTIVE),BLUE (Personality.ANALYTICAL);

Personality personality;

Colours (Personality personality) {this.personality = personality;

}

enum Personality {ASSERTIVE, EXPRESSIVE, AMIABLE, ANALYTICAL };}

class TestColours {public static void main (String[] args) {

// INSERT LINE OF CODE HERE}

}Which line of code when replaced with "// INSERT LINE OF CODE HERE", will output a value "true":

a) System.out.println (Colours.Personality.ASSERTIVE instanceof Colours.Personality);

b) System.out.println (Personality.EXPRESSIVE instanceof Personality); c) System.out.println (EXPRESSIVE instanceof Personality); d) None of the above

Answer : aExplanation :

Enums may be used as a operand for the instanceof operator in the same way that it can be used by a class.

Q31:

Examine the following code and select the correct options:

enum Rating {POOR (0.0, 5.0),AVERAGE (5.1, 7.0),GOOD (7.0, 8.5),

By: Amit Kumar Agrawal 621

The Smartest Way to Learn Java5

EXCELLENT (8.6, 9.9);

double lowerLimit, upperLimit;

Rating (double ll, double ul) {this.lowerLimit = ll;this.upperLimit = ul;

}

int raise() {switch (this) {

case POOR : return 0;case AVERAGE : return 5;case GOOD : return 20;case EXCELLENT: return 45;

}return 0;

}}

class Appraisal {public static void main (String args[])

throws NumberFormatException {double currentSalary = 100;double increment = 0;

for (Rating r : Rating.values()) {increment = currentSalary/ 100 * r.raise();System.out.println

(r + " Performance, Revised Salary = "

+ (currentSalary + increment));}

}}Options:

a) The above code will not compile: enums cannot be used as an argument to switch statement.

b) Code will compile, giving the following output:

POOR Performance, Revised Salary = 100.0AVERAGE Performance, Revised Salary = 105.0GOOD Performance, Revised Salary = 120.0EXCELLENT Performance, Revised Salary = 145.0

c) The code will compile, giving the same results as mentioned in option 'b', if the enum Rating is defined as follows:

enum Rating {

By: Amit Kumar Agrawal 622

The Smartest Way to Learn Java5

POOR (0.0, 5.0) { int raise() { return 0; } },AVERAGE (5.1, 7.0) { int raise() { return 5; } },GOOD (7.0, 8.5) { int raise() { return 20; } },EXCELLENT (8.6, 9.9) { int raise() { return 45; } };

double lowerLimit, upperLimit;

Rating (double ll, double ul) {this.lowerLimit = ll;this.upperLimit = ul;

}

abstract int raise();} d) The constructor of an enum cannot accept 2 method parameters.

Answers : b, cExplanation :

a) Enums can be used in switch statements. c) An enum constant can override any number of methods available to it. d) An enum can define more than 1 constructor (similar to a class) and its

constructor can accept more than 1 method parameter

Q32:

Examine the following code and select the correct options: enum Shape {

CIRCLE (0, "red"),TRIANGLE (3),SQUARE (4),RECTANGLE (4),PENTAGON (5),HEXAGON (6, "yellow"),OCTAGON (8, "pink");

int numberOfSides;String shapeColor;

Shape (int sides) { numberOfSides = sides; }Shape (int sides, String colour) {

numberOfSides = sides;shapeColor = colour;

}

public static void main (String[] args) {for (Shape s : Shape.values())

System.out.println(s);}

By: Amit Kumar Agrawal 623

The Smartest Way to Learn Java5

}

Options: a) Output of the code is as follows:

CIRCLETRIANGLESQUARERECTANGLEPENTAGONHEXAGONOCTAGON

b) Output of the code is as follows:

CIRCLE redTRIANGLESQUARERECTANGLEPENTAGONHEXAGON yellowOCTAGON pink

c) The code will not compile : Cannot define more than one constructor in an enum.

d) The code will compile successfully, but throw a runtime error.

Answer : a

Explanation : b) The default implementation of the toString method returns the name of the

enum constant. To get any other customised value, override the toString method. c) The code will compile. An enum can define more than 1 constructor. d) There is no runtime error with the code.

Q33:

Examine the following code:

public enum Day {MONDAY (1),TUESDAY (2),WEDNESDAY (3),THURSDAY (4),FRIDAY (5),SATURDAY (6),SUNDAY (7);

int dayNumber;

By: Amit Kumar Agrawal 624

The Smartest Way to Learn Java5

Day (int dayNumber) {this.dayNumber = dayNumber;

}

// INSERT CODE HERE

public static void main (String[] args) {for (Day d : Day.values())

System.out.println (d);}

}Select from the following options the correct method, which when inserted in the above enum line, will print out the following result: 1 day of week2 day of week3 day of week4 day of week5 day of week6 day of week7 day of weekOptions:

a)

public String toString () {return dayNumber + " day of week";}

b)

public String name () {return dayNumber + " day of week";

}

Answer : aExplanation :

a) name is a final method, which cannot be overridden. It returns the name of the enum constant, exactly as declared in its enum declaration

By: Amit Kumar Agrawal 625

The Smartest Way to Learn Java5

FEW CORE JAVA INTERVIEW QUESTIONS AND ANSWERS

1. What is transient variable?

Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

2. Name the container which uses Border Layout as their default layout?

Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

3. What do you understand by Synchronization?

Answer: 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 one 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.

E.g. Synchronizing a function:public synchronized void Method1 () {// Appropriate method-related code.}

E.g. Synchronizing a block of code inside a function:public myFunction (){synchronized (this) {// Synchronized code here.}}

4. What is Collection API?

By: Amit Kumar Agrawal 626

The Smartest Way to Learn Java5

Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.

By: Amit Kumar Agrawal 627

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 628

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 629

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 630

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 631

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 632

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 633

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 634

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 635

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 636

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 637

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 638

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 639

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 640

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 641

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 642

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 643

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 644

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 645

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 646

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 647

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 648

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 649

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 650

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 651

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 652

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 653

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 654

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 655

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 656

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 657

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 658

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 659

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 660

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 661

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 662

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 663

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 664

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 665

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 666

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 667

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 668

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 669

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 670

The Smartest Way to Learn Java5

By: Amit Kumar Agrawal 671

The Smartest Way to Learn Java5

CHAPTER WISE QUESTIONS AND ANSWAERS

Java Basics

1.The Java interpreter is used for the execution of the source code.

a)True

b)False

Ans: a.

2) On successful compilation a file with the class extension is created.

a) True

b) FalseAns: a.

3) The Java source code can be created in a Notepad editor.a) Trueb) False

By: Amit Kumar Agrawal 672

The Smartest Way to Learn Java5

Ans: a.

4) The Java Program is enclosed in a class definition.a) Trueb) False

Ans: a.

5) What declarations are required for every Java application?Ans: A class and the main( ) method declarations.

6) What are the two parts in executing a Java program and their purposes?Ans: Two parts in executing a Java program are:Java Compiler and Java Interpreter.The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application.

7) What are the three OOPs principles and define them?Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs Principles.

Encapsulation:Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.Inheritance:Is the process by which one object acquires the properties of another object.Polymorphism:Is a feature that allows one interface to be used for a general class of actions.

 8) What is a compilation unit?Ans : Java source code file.

9) What output is displayed as the result of executing the following statement?System.out.println("// Looks like a comment.");// Looks like a comment

a)The statement results in a compilation error

b)Looks like a comment

c)No output is displayed

By: Amit Kumar Agrawal 673

The Smartest Way to Learn Java5

Ans : a.

10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?a)It must have a package statement b)It must be named Test.java c)It must import java.lang d)It must declare a public class named TestAns : b

11) What are identifiers and what is naming convention?Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters,numbers or underscore or dollar sign and must not begin with numbers.

12) What is the return type of program’s main( ) method?Ans : void

13) What is the argument type of program’s main( ) method?Ans : string array.

14) Which characters are as first characters of an identifier?Ans : A – Z, a – z, _ ,$

15) What are different comments?Ans : 1) // -- single line comment2) /* --*/ multiple line comment 3) /** --*/ documentation

16) What is the difference between constructor method and method?Ans : Constructor will be automatically invoked when an object is created. Whereas method has to be call explicitly.

17) What is the use of bin and lib in JDK?Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib contains all packages and variables.

By: Amit Kumar Agrawal 674

The Smartest Way to Learn Java5

  Data types,variables and Arrays

1) What is meant by variable?Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared.

2) What are the kinds of variables in Java? What are their uses?Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states.

3) How are the variables declared?Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition. Variables with the same data type can be declared together. Local variables must be given a value before usage.

4) What are variable types?Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.

5) How do you assign values to variables?Ans: Values are assigned to variables using the assignment operator =.

6) What is a literal? How many types of literals are there?Ans: A literal represents a value of a certain type where the type describes how that value behaves.There are different types of literals namely number literals, character literals, boolean literals, string literals,etc.

7) What is an array?

By: Amit Kumar Agrawal 675

The Smartest Way to Learn Java5

Ans: An array is an object that stores a list of items.

8) How do you declare an array?Ans: Array variable indicates the type of object that the array holds.Ex: int arr[];

9) Java supports multidimensional arrays.a)Trueb)FalseAns: a.

10) An array of arrays can be created.a)Trueb)FalseAns: a.

11) What is a string?Ans: A combination of characters is called as string.

12) Strings are instances of the class String.a)Trueb)FalseAns: a.

13) When a string literal is used in the program, Java automatically creates instances of the string class.a)Trueb)FalseAns: a.

14) Which operator is to create and concatenate string?Ans: Addition operator(+).

15) Which of the following declare an array of string objects?a)String[ ] s; b)String [ ]s: c)String[ s]: d)String s[ ]:Ans : a, b and d

By: Amit Kumar Agrawal 676

The Smartest Way to Learn Java5

16) What is the value of a[3] as the result of the following array declaration?1 2 3 4Ans : d

17) Which of the following are primitive types?a)byte b)String c)integer d)FloatAns : a.

18) What is the range of the char type?a)0 to 216

b)0 to 215

c)0 to 216-1 d)0 to 215-1Ans. D

19) What are primitive data types?Ans : byte, short, int, longfloat, doublebooleanchar

20) What are default values of different primitive types?Ans : int - 0short - 0byte - 0long - 0 lfloat - 0.0 fdouble - 0.0 d boolean - falsechar – null

By: Amit Kumar Agrawal 677

The Smartest Way to Learn Java5

21) Converting of primitive types to objects can be explicitly.a)Trueb)FalseAns: b.

22) How do we change the values of the elements of the array?Ans : The array subscript expression can be used to change the values of the elements of the array.

23) What is final varaible?Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant.

24) What is static variable?Ans : Static variables are shared by all instances of a class. Operators1) What are operators and what are the various types of operators available in Java?Ans: Operators are special symbols used in expressions.The following are the types of operators:Arithmetic operators,Assignment operators, Increment & Decrement operators, Logical operators, Biwise operators, Comparison/Relational operators andConditional operators

2) The ++ operator is used for incrementing and the -- operator is used for decrementing.a)Trueb)FalseAns: a.

3) Comparison/Logical operators are used for testing and magnitude.a)Trueb)False

By: Amit Kumar Agrawal 678

The Smartest Way to Learn Java5

Ans: a.

4) Character literals are stored as unicode characters.a)Trueb)FalseAns: a.

5) What are the Logical operators?Ans: OR(|), AND(&), XOR(^) AND NOT(~).

6) What is the % operator?Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.

7) What is the value of 111 % 13?a)3 b)5 c)7 d)9 Ans : c.

8) Is &&= a valid operator?Ans : No.

9) Can a double value be cast to a byte?Ans : Yes

10) Can a byte object be cast to a double value ?Ans : No. An object cannot be cast to a primitive value.

11) What are order of precedence and associativity?Ans : Order of precedence the order in which operators are evaluated in expressions.Associativity determines whether an expression is evaluated left-right or right-left.

12) Which Java operator is right associativity?Ans : = operator.

13) What is the difference between prefix and postfix of -- and ++ operators?

By: Amit Kumar Agrawal 679

The Smartest Way to Learn Java5

Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.The postfix form returns the current value of all of the expression and then performs the increment or decrement operation on that value.

14) What is the result of expression 5.45 + "3,2"?a)The double value 8.6 b)The string ""8.6" c)The long value 8. d)The String "5.453.2"Ans : d

15) What are the values of x and y ?x = 5; y = ++x; Ans : x = 6; y = 6

16) What are the values of x and z?x = 5; z = x++; Ans : x = 6; z = 5 Control Statements1) What are the programming constructs?Ans:a) Sequentialb) Selection -- if and switch statementsc) Iteration -- for loop, while loop and do-while loop

2) class conditional {public static void main(String args[]) {int i = 20;int j = 55;int z = 0;z = i < j ? i : j; // ternary operatorSystem.out.println("The value assigned is " + z);}}

What is output of the above program?Ans: The value assigned is 20

3) The switch statement does not require a break.a)True

By: Amit Kumar Agrawal 680

The Smartest Way to Learn Java5

b)FalseAns: b.

4) The conditional operator is otherwise known as the ternary operator.a)Trueb)FalseAns: a.

5) The while loop repeats a set of code while the condition is false.a)Trueb)FalseAns: b.

6) The do-while loop repeats a set of code atleast once before the condition is tested.a)Trueb)FalseAns: a.

7) What are difference between break and continue?Ans: The break keyword halts the execution of the current loop and forces control out of the loop.The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration. 8) The for loop repeats a set of statements a certain number of times until a condition is matched.a)Trueb)FalseAns: a.

9) Can a for statement loop indefintely?Ans : Yes.

10) What is the difference between while statement and a do statement/Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.

By: Amit Kumar Agrawal 681

The Smartest Way to Learn Java5

A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.   Introduction to Classes and Methods

1) Which is used to get the value of the instance variables?Ans: Dot notation.

2) The new operator creates a single instance named class and returns a reference to that object.a)Trueb)FalseAns: a.

3) A class is a template for multiple objects with similar features.a)Trueb)FalseAns: a.

4) What is mean by garbage collection?Ans: When an object is no longer referred to by any variable, Java automatically reclaims memory used by that object. This is known as garbage collection.

5) What are methods and how are they defined?Ans: Methods are functions that operate on instances of classes in which they are defined.Objects can communicate with each other using methods and can call methods in other classes.Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above.

6) What is calling method?Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation. Ex: obj.methodname(param1,param2)

7) Which method is used to determine the class of an object?

By: Amit Kumar Agrawal 682

The Smartest Way to Learn Java5

Ans: getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects.

8) All the classes in java.lang package are automatically imported whena program is compiled.a)Trueb)FalseAns: a.

9) How can class be imported to a program?Ans: To import a class, the import keyword should be used as shown.;import classname;

10) How can class be imported from a package to a program?Ans: import java . packagename . classname (or) import java.package name.*;

11) What is a constructor?Ans: A constructor is a special kind of method that determines how an object is initialized when created.

12) Which keyword is used to create an instance of a class?Ans: new.

13) Which method is used to garbage collect an object?Ans: finalize ().

14) Constructors can be overloaded like regular methods.a)Trueb)FalseAns: a.

15) What is casting?Ans: Casting is bused to convert the value of one type to another. 16) Casting between primitive types allows conversion of one primitive type to another.

By: Amit Kumar Agrawal 683

The Smartest Way to Learn Java5

a)Trueb)FalseAns: a.

17) Casting occurs commonly between numeric types.a)Trueb)FalseAns: a.

18) Boolean values can be cast into any other primitive type.a)Trueb)FalseAns: b.

19) Casting does not affect the original object or value.a)Trueb)FalseAns: a.

20) Which cast must be used to convert a larger value into a smaller one?Ans: Explicit cast.

21) Which cast must be used to cast an object to another class?Ans: Specific cast.

22) Which of the following features are common to both Java & C++?A.The class declarationb.The access modifiersc.The encapsulation of data & methods with in objectsd.The use of pointersAns: a,b,c.

23) Which of the following statements accurately describe the use of access modifiers within a class definition?a.They can be applied to both data & methodsb.They must precede a class's data variables or methodsc.They can follow a class's data variables or methodsd.They can appear in any order

By: Amit Kumar Agrawal 684

The Smartest Way to Learn Java5

e.They must be applied to data variables first and then to methodsAns: a,b,d.

24) Suppose a given instance variable has been declared private.Can this instance variable be manipulated by methods out side its class?a.yesb.noAns: b.

25) Which of the following statements can be used to describe a public method?a.It is accessible to all other classes in the hierarchyb.It is accessablde only to subclasses of its parent classc.It represents the public interface of its classd.The only way to gain access to this method is by calling one of the public classmethodsAns: a,c.

26) Which of the following types of class members can be part of the internal part of a class?a.Public instance variablesb.Private instance variablesc.Public methodsd.Private methodsAns: b,d.

27) You would use the ____ operator to create a single instance of a named class.a.newb.dotAns: a.

28) Which of the following statements correctly describes the relation between an object and the instance variable it stores?a.Each new object has its own distinctive set of instance variablesb.Each object has a copy of the instance variables of its classc.the instance variable of each object are seperate from the variables of other objects

By: Amit Kumar Agrawal 685

The Smartest Way to Learn Java5

d.The instance variables of each object are stored together with the variables of other objectsAns: a,b,c.

29) If no input parameters are specified in a method declaration then the declaration will include __.a.an empty set of paranthesesb.the term voidAns: a.

30) What are the functions of the dot(.) operator?a.It enables you to access instance variables of any objects within a classb.It enables you to store values in instance variables of an object c.It is used to call object methodsd.It is to create a new objectAns: a,b,c.

31) Which of the following can be referenced by this variable?a.The instance variables of a class onlyb.The methods of a class onlyc.The instance variables and methods of a class Ans: c.

32) The this reference is used in conjunction with ___methods.a.staticb.non-staticAns: b.

33) Which of the following operators are used in conjunction with the this and super references?a.The new operatorb.The instanceof operatorc.The dot operatorAns: c.

34) A constructor is automatically called when an object is instantiated

By: Amit Kumar Agrawal 686

The Smartest Way to Learn Java5

a. trueb. false Ans: a.

35) When may a constructor be called without specifying arguments?a. When the default constructor is not calledb. When the name of the constructor differs from that of the classc. When there are no constructors for the classAns: c.

36) Each class in java can have a finalizer methoda. trueb.falseAns: a.

37) When an object is referenced, does this mean that it has been identified by the finalizer method for garbage collection?a.yesb.noAns: b.

38) Because finalize () belongs to the java.lang.Object class, it is present in all ___.a.objectsb.classesc.methodsAns: b.

39) Identify the true statements about finalization.a.A class may have only one finalize method b.Finalizers are mostly used with simple classesc.Finalizer overloading is not allowedAns: a,c.

40) When you write finalize() method for your class, you are overriding a finalizer inherited from a super class.a.trueb.falseAns: a.

By: Amit Kumar Agrawal 687

The Smartest Way to Learn Java5

41) Java memory management mechanism garbage collects objects which are no longer referenceda trueb.falseAns: a.

42) are objects referenced by a variable candidates for garbage collection when the variable goes out of scope?a yesb. noAns: a.

43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to relinquish the processor.a.high b.lowAns: a,b.

44) The garbage collector will run immediately when the system is out of memorya.true b.falseAns: a.

45) You can explicitly drop a object reference by setting the value of a variable whose data type is a reference type to ___Ans: null

46) When might your program wish to run the garbage collecter?a. before it enters a compute-intense section of codeb. before it enters a memory-intense section of codec. before objects are finalizedd. when it knows there will be some idle timeAns: a,b,d

47) For externalizable objects the class is solely responsible for the external format of its contentsa.true b.false

By: Amit Kumar Agrawal 688

The Smartest Way to Learn Java5

Ans: a

48) When an object is stored, are all of the objects that are reachable from that object stored as well?a.trueb.falseAns: a49) The default__ of objects protects private and trancient data, and supports the __ of the classesa.evolutionb.encodingAns: b,a.

50) Which are keywords in Java?a) NULLb) sizeofc) friendd) extendse) synchronizedAns : d and e

51) When must the main class and the file name coincide?Ans :When class is declared public.

52) What are different modifiers?Ans : public, private, protected, default, static, trancient, volatile, final, abstract.

53) What are access modifiers?Ans : public, private, protected, default.

54) What is meant by "Passing by value" and " Passing by reference"?Ans : objects – pass by referrenceMethods - pass by value

55) Is a class a subclass of itself?Ans : A class is a subclass itself. 56) What modifiers may be used with top-level class?Ans : public, abstract, final.

By: Amit Kumar Agrawal 689

The Smartest Way to Learn Java5

57) What is an example of polymorphism?Inner class Anonymous classes Method overloading Method overridingAns : c  Packages and interface

1) What are packages ? what is use of packages ?Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package.Signature... package pkg;Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism.

2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ?Ans :"java.applet.Applet" will import only the class Applet from the package java.appletWhere as "java.applet.*" will import all the classes from java.applet package.

3) What do you understand by package access specifier?Ans : public: Anything declared as public can be accessed from anywhere private: Anything declared in the private can’t be seen outside of its class.default: It is visible to subclasses as well as to other classes in the same package.

4) What is interface? What is use of interface?Ans : It is similar to class which may contain method’s signature only but not bodies. Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance.

5) Is it is necessary to implement all methods in an interface?Ans : Yes. All the methods have to be implemented.

6) Which is the default access modifier for an interface method?Ans : public.

7) Can we define a variable in an interface ?and what type it should be ?

By: Amit Kumar Agrawal 690

The Smartest Way to Learn Java5

Ans : Yes we can define a variable in an interface. They are implicitly final and static.

8) What is difference between interface and an abstract class?Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract. In Interface we need not use the keyword abstract for the methods.9) By default, all program import the java.lang package.True/FalseAns : True

10) Java compiler stores the .class files in the path specified in CLASSPATH environmental variable.True/FalseAns : False 11) User-defined package can also be imported just like the standard packages.True/FalseAns : True

12) When a program does not want to handle exception, the ______class is used.Ans : Throws

13) The main subclass of the Exception class is _______ class.Ans : RuntimeException

14) Only subclasses of ______class may be caught or thrown.Ans : Throwable

15) Any user-defined exception class is a subclass of the _____ class.Ans : Exception

16) The catch clause of the user-defined exception class should ______ itsBase class catch clause.Ans : Exception

17) A _______ is used to separate the hierarchy of the class while declaring anImport statement.Ans : Package 

By: Amit Kumar Agrawal 691

The Smartest Way to Learn Java5

18) All standard classes of Java are included within a package called _____.Ans : java.lang

19) All the classes in a package can be simultaneously imported using ____.Ans : *

20) Can you define a variable inside an Interface. If no, why? If yes, how?Ans.: YES. final and static

21) How many concrete classes can you have inside an interface?Ans.: None

22) Can you extend an interface?Ans.: Yes

23) Is it necessary to implement all the methods of an interface while implementing the interface? Ans.: No

24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ?Ans.: abstract

25) How do you achieve multiple inheritance in Java?Ans: Using interfaces.

26) How to declare an interface example?Ans : access class classname implements interface.

27) Can you achieve multiple interface through interface?a)True b) falseAns : a.

28) Can variables be declared in an interface ? If so, what are the modifiers?Ans : Yes. final and static are the modifiers can be declared in an interface.

29) What are the possible access modifiers when implementing interface methods?Ans : public.

By: Amit Kumar Agrawal 692

The Smartest Way to Learn Java5

30) Can anonymous classes be implemented an interface?Ans : Yes.

31) Interfaces can’t be extended.a)Trueb)FalseAns : b.

32) Name interfaces without a method?Ans : Serializable, Cloneble & Remote.

33) Is it possible to use few methods of an interface in a class ? If so, how?Ans : Yes. Declare the class as abstract.  Exception Handling

1) What is the difference between ‘throw’ and ‘throws’ ?And it’s application?Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not handle, it must specify this behavior so the callers of the method can guard against that exception.

2) What is the difference between ‘Exception’ and ‘error’ in java?Ans : Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.

3) What is ‘Resource leak’?Ans : Freeing up other resources that might have been allocated at the beginning of a method.

4)What is the ‘finally’ block?

By: Amit Kumar Agrawal 693

The Smartest Way to Learn Java5

Ans : Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.

5) Can we have catch block with out try block? If so when?Ans : No. Try/Catch or Try/finally form a unit.

6) What is the difference between the following statements?Catch (Exception e),Catch (Error err),Catch (Throwable t)Ans :The first one catch an Exception object, The second one cach an Error class object and the final one catch a Throwable class object.   7) What will happen to the Exception object after exception handling?Ans : It will go for Garbage Collector. And frees the memory.

8) How many Exceptions we can define in ‘throws’ clause?Ans : We can define multiple exceptions in throws clause.Signature is..type method-name (parameter-list) throws exception-list 9) The finally block is executed when an exception is thrown, even if no catch matches it.True/FalseAns : True

10) The subclass exception should precede the base class exception when used within the catch clause.True/FalseAns : True

11) Exceptions can be caught or rethrown to a calling method.True/FalseAns : True

By: Amit Kumar Agrawal 694

The Smartest Way to Learn Java5

12) The statements following the throw keyword in a program are not executed.True/FalseAns : True

13) The toString ( ) method in the user-defined exception class is overridden.True/FalseAns : True MULTI THREADING

1) What are the two types of multitasking?Ans : 1.process-based

2) What are the two ways to create the thread?Ans : 1.by implementing Runnable 2.by extending Thread

3) What is the signature of the constructor of a thread class?Ans : Thread(Runnable threadob,String threadName)

4) What are all the methods available in the Runnable Interface?Ans : run()

5) What is the data type for the method isAlive() and this method is available in which class?Ans : boolean, Thread

6) What are all the methods available in the Thread class?Ans : 1.isAlive()2.join()3.resume()4.suspend()5.stop()6.start()7.sleep()8.destroy()

By: Amit Kumar Agrawal 695

The Smartest Way to Learn Java5

7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?

Ans :1. wait(),notify() & notifyall()2. Object class

8) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time?Ans : Synchronisation

9) What is the procedure to own the moniter by many threads?Ans : not possible

10) What is the unit for 1000 in the below statement?ob.sleep(1000)Ans : long milliseconds

11) What is the data type for the parameter of the sleep() method?Ans : long

12) What are all the values for the following level?max-priority min-prioritynormal-priorityAns : 10,1,5

13) What is the method available for setting the priority?Ans : setPriority()

14) What is the default thread at the time of starting the program?Ans : main thread

15) The word synchronized can be used with only a method.True/ FalseAns : False

16) Which priority Thread can prompt the lower primary Thread?Ans : Higher Priority

17) How many threads at a time can access a monitor?

By: Amit Kumar Agrawal 696

The Smartest Way to Learn Java5

Ans : one

18) What are all the four states associated in the thread?Ans : 1. new 2. runnable 3. blocked 4. dead

19) The suspend()method is used to teriminate a thread?True /FalseAns : False

20) The run() method should necessary exists in clases created as subclass of thread?True /FalseAns : True

21) When two threads are waiting on each other and can't proceed the programe is said to be in a deadlock?True/False Ans : True

22) Which method waits for the thread to die ?Ans : join() method 23) Which of the following is true?1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method2) Among wait(),notify(),notifyall() the wait() method only throws IOException3) wait(),notify(),notifyall() & sleep() are methods of object class a)1 b)2 c)3 d)1 & 2 e)1,2 & 3Ans : D

24) Garbage collector thread belongs to which priority?Ans : low-priority

25) What is meant by timeslicing or time sharing?

By: Amit Kumar Agrawal 697

The Smartest Way to Learn Java5

Ans : Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.

26) What is meant by daemon thread? In java runtime, what is it's role?Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.Inheritance

1) What is the difference between superclass & subclass?Ans : A super class is a class that is inherited whereas subclass is a class that does the inheriting.

2) Which keyword is used to inherit a class?Ans : extends

3) Subclasses methods can access superclass members/ attributes at all times?True/FalseAns : False 4) When can subclasses not access superclass members?Ans : When superclass is declared as private.

5) Which class does begin Java class hierarchy?Ans : Object class

6) Object class is a superclass of all other classes?True/FalseAns : True

7) Java supports multiple inheritance?True/FalseAns : False

8) What is inheritance?Ans : Deriving an object from an existing class. In the other words, Inheritance is the process of inheriting all the features from a class

9) What are the advantages of inheritance?Ans : Reusability of code and accessibility of variables and methods of the superclass by subclasses.

By: Amit Kumar Agrawal 698

The Smartest Way to Learn Java5

10) Which method is used to call the constructors of the superclass from the subclass?Ans : super(argument)

11) Which is used to execute any method of the superclass from the subclass?Ans : super.method-name(arguments)

12) Which methods are used to destroy the objects created by the constructor methods?Ans : finalize()

13) What are abstract classes?Ans : Abstract classes are those for which instances can’t be created.

14) What must a class do to implement an interface?Ans: It must provide all of the methods in the interface and identify the interface in its implements clause.

15) Which methods in the Object class are declared as final?Ans : getClass(), notify(), notifyAll(), and wait()

16) Final methods can be overridden.True/FalseAns : False

17) Declaration of methods as final results in faster execution of the program?True/FalseAns: True

18) Final variables should be declared in the beginning?True/FalseAns : True

19) Can we declare variable inside a method as final variables? Why?Ans : Cannot because, local variable cannot be declared as final variables.

20) Can an abstract class may be final?Ans : An abstract class may not be declared as final.

By: Amit Kumar Agrawal 699

The Smartest Way to Learn Java5

21) Does a class inherit the constructors of it's super class?Ans: A class does not inherit constructors from any of it's super classes.

22) What restrictions are placed on method overloading?Ans: Two methods may not have the same name and argument list but different return types.

23) What restrictions are placed on method overriding?Ans : Overridden methods must have the same name , argument list , and return type. The overriding method may not limit the access of the method it overridees.The overriding method may not throw any exceptions that may not be thrown by the overridden method.

24) What modifiers may be used with an inner class that is a member of an outer class?Ans : a (non-local) inner class may be declared as public, protected, private, static, final or abstract.

25) How this() is used with constructors?Ans: this() is used to invoke a constructor of the same class

26) How super() used with constructors?Ans : super() is used to invoke a super class constructor

27) Which of the following statements correctly describes an interface?a)It's a concrete classb)It's a superclassc)It's a type of abstract classAns: c

28) An interface contains __ methodsa)Non-abstractb)Implementedc)unimplementedAns:c

STRING HANDLING

By: Amit Kumar Agrawal 700

The Smartest Way to Learn Java5

1)Which package does define String and StringBuffer classes? Ans : java.lang package.

2)Which method can be used to obtain the length of the String? Ans : length( ) method.

3)How do you concatenate Strings? Ans : By using " + " operator.

4)Which method can be used to compare two strings for equality? Ans : equals( ) method.

5)Which method can be used to perform a comparison between strings that ignores case differences? Ans : equalsIgnoreCase( ) method.

6)What is the use of valueOf( ) method? Ans : valueOf( ) method converts data from its internal format into a human-readable form.

7)What are the uses of toLowerCase( ) and toUpperCase( ) methods? Ans : The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The method toUpperCase( ) converts all the characters in a string from lowercase to uppercase.

8)Which method can be used to find out the total allocated capacity of a StrinBuffer? Ans : capacity( ) method.

9)Which method can be used to set the length of the buffer within a StringBuffer object? Ans : setLength( ).

10)What is the difference between String and StringBuffer? Ans : String objects are constants, whereas StringBuffer objects are not.String class supports constant strings, whereas StringBuffer class supports growable, modifiable strings.

By: Amit Kumar Agrawal 701

The Smartest Way to Learn Java5

11)What are wrapper classes? Ans : Wrapper classes are classes that allow primitive types to be accessed as objects.

12)Which of the following is not a wrapper class?a)String b)Integer c)Boolean d)CharacterAns : a.

13)What is the output of the following program?public class Question {public static void main(String args[]) {String s1 = "abc";String s2 = "def";String s3 = s1.concat(s2.toUpperCase( ) );System.out.println(s1+s2+s3);}}a)abcdefabcdef b)abcabcDEFDEF c)abcdefabcDEF d)None of the aboveANS : c.

13)Which of the following methods are methods of the String class?a)delete( ) b)append( ) c)reverse( ) d)replace( )Ans : d.

14)Which of the following methods cause the String object referenced by s to be changed?a)s.concat( ) b)s.toUpperCase( )

By: Amit Kumar Agrawal 702

The Smartest Way to Learn Java5

c)s.replace( ) d)s.valueOf( )Ans : a and b.

15)String is a wrapper class?True /FalseAns : false.

16)String is a classs>true/falseAns:true

17) If you run the code below, what gets printed out? String s=new String("Bicycle"); int iBegin=1; char iEnd=3; System.out.println(s.substring(iBegin,iEnd));a)Bic b)ic c) icy d) error: no method matching substring(int,char)Ans : b.

18) Given the following declarations String s1=new String("Hello") String s2=new String("there"); String s3=new String();Which of the following are legal operations? s3=s1 + s2; s3=s1 - s2; c) s3=s1 & s2 d) s3=s1 && s2 Ans : a.

19) Which of the following statements are true? a)The String class is implemented as a char array, elements are addressed using the stringname[] convention

By: Amit Kumar Agrawal 703

The Smartest Way to Learn Java5

b) Strings are a primitive type in Java that overloads the + operator for concatenation c) Strings are a primitive type in Java and the StringBuffer is used as the matching wrapper type d) The size of a string can be retrieved using the length property.Ans : b.  INPUT / OUTPUT : EXPLORING JAVA.IO1)What is meant by Stream and what are the types of Streams and classes of the Streams? Ans : A Stream is an abstraction that either produces or consumes information.There are two types of Streams. They are:Byte Streams : Byte Streams provide a convenient means for handling input and output of bytes. Character Streams : Character Streams provide a convenient means for handling input and output of characters.Byte Stream classes : Byte Streams are defined by using two abstract classes. They are:InputStream and OutputStream.Character Stream classes : Character Streams are defined by using two abstract classes. They are : Reader and Writer.

2)Which of the following statements are true?a)UTF characters are all 8-bits. b)UTF characters are all 16-bits. c)UTF characters are all 24-bits. d)Unicode characters are all 16-bits. e)Bytecode characters are all 16-bits.Ans : d.

3)Which of the following statements are true?a)When you construct an instance of File, if you do not use the filenaming semantics of the local machine, the constructor will throw an IOException. b)When you construct an instance of File, if the corresponding file does not exist on the local file system, one will be created. c)When an instance of File is garbage collected, the corresponding file on the local file system is deleted. d)None of the above.Ans : a,b and c.

By: Amit Kumar Agrawal 704

The Smartest Way to Learn Java5

4)The File class contains a method that changes the current working directory.True FalseAns : b.

5)It is possible to use the File class to list the contents of the current working directory.a)True b)FalseAns : a.

6)Readers have methods that can read and return floats and doubles.a)True b)FalseAns : b.

7)You execute the code below in an empty directory. What is the result?File f1 = new File("dirname");File f2 = new File(f1, "filename");a)A new directory called dirname is created in the current working directory. b)A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname. c)A new directory called dirname and a new file called filename are created, both in the current working directory. d)A new file called filename is created in the current working directory. e)No directory is created, and no file is created.Ans : e.

8)What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?Ans : The Reader/Writer class hierarchy is character-oriented and the InputStream/OutputStream class hierarchy is byte-oriented.

9)What is an I/O filter? Ans : An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

10)What is the purpose of the File class?

By: Amit Kumar Agrawal 705

The Smartest Way to Learn Java5

Ans : The File class is used to create objects that provide access to the files and directories of a local file system.

11)What interface must an object implement before it can be written to a stream as an object? Ans : An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

12)What is the difference between the File and RandomAccessFile classes? Ans : The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

13)What class allows you to read objects directly from a stream? Ans : The ObjectInputStream class supports the reading of objects from input streams.

14)What value does read( ) return when it has reached the end of a file? Ans : The read( ) method returns – 1 when it has reached the end of a file.

15)What value does readLine( ) return when it has reached the end of a file? Ans : The readLine( ) method returns null when it has reached the end of a file.

16)How many bits are used to represent Unicode, ASCII, UTF-16 and UTF-8 characters? Ans : Unicode requires 16-bits and ASCII requires 8-bits. Although the ASCII character set uses only 1-bits, it is usually represented as 8-bits. UTF-8 represents characters using 8, 16 and 18-bit patterns. UTF-16 uses 16-bit and larger bit patterns.

17)Which of the following are true?a)The InputStream and OutputStream classes are byte-oriented. b)The ObjectInputStream and ObjectOutputStream do not support serialized object input and output. c)The Reader and Writer classes are character-oriented. d)The Reader and Writer classes are the preferred solution to serialized object output.Ans : a and c.

18)Which of the following are true about I/O filters?

By: Amit Kumar Agrawal 706

The Smartest Way to Learn Java5

a)Filters are supported on input, but not on output. b)Filters are supported by the InputStream/OutputStream class hierarchy, but not by the Reader/Writer class hierarchy. c)Filters read from one stream and write to another. d)A filter may alter data that is read from one stream and written to another.Ans : c and d.

19)Which of the following are true?a)Any Unicode character is represented using 16-bits. b)7-bits are needed to represent any ASCII character. c)UTF-8 characters are represented using only 8-bits. d)UTF-16 characters are represented using only 16-bits.Ans : a and b.

20)Which of the following are true?

a)The Serializable interface is used to identify objects that may be written to an output stream. b)The Externalizable interface is implemented by classes that control the way in which their objects are serialized. c)The Serializable interface extends the Externalizable interface. d)The Externalizable interface extends the Serializable interface.

Ans : a, b and d.

21)Which of the following are true about the File class?

a)A File object can be used to change the current working directory. b)A File object can be used to access the files in the current directory. c)When a File object is created, a corresponding directory or file is created in the local file system. d)File objects are used to access files and directories on the local file system. e)File objects can be garbage collected. f)When a File object is garbage collected, the corresponding file or directory is deleted.

Ans : b, d and e.

EVENT HANDLING

By: Amit Kumar Agrawal 707

The Smartest Way to Learn Java5

1)The event delegation model, introduced in release 1.1 of the JDK, is fully compatible with the event model.a)True b)FalseAns : b.

2)A component subclass that has executed enableEvents( ) to enable processing of a certain kind of event cannot also use an adapter as a listener for the same kind of event.a)True b)FalseAns : b.

3)What is the highest-level event class of the event-delegation model? Ans : The java.util.eventObject class is the highest-level class in the event-delegation hierarchy.

4)What interface is extended by AWT event listeners? Ans : All AWT event listeners extend the java.util.EventListener interface.

5)What class is the top of the AWT event hierarchy? Ans : The java.awt.AWTEvent class is the highest-level class in the AWT event class hierarchy.

6)What event results from the clicking of a button? Ans : The ActionEvent event is generated as the result of the clicking of a button.

7)What is the relationship between an event-listener interface and an event-adapter class? Ans : An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event.An event adapter provides a default implementation of an event-listener interface.

8)In which package are most of the AWT events that support the event-delegation model defined? Ans : Most of the AWT–related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

By: Amit Kumar Agrawal 708

The Smartest Way to Learn Java5

9)What is the advantage of the event-delegation model over the earlier event-inheritance model?Ans : The event-delegation has two advantages over the event-inheritance model. They are : It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use.It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.

10)What is the purpose of the enableEvents( ) method? Ans :The enableEvents( ) method is used to enable an event for a particular object.

11)Which of the following are true?a)The event-inheritance model has replaced the event-delegation model. b)The event-inheritance model is more efficient than the event-delegation model. c)The event-delegation model uses event listeners to define the methods of event-handling classes. d)The event-delegation model uses the handleEvent( ) method to support event handling.Ans : c.

12)Which of the following is the highest class in the event-delegation model?a)java.util.EventListener b)java.util.EventObject c)java.awt.AWTEvent d)java.awt.event.AWTEventAns : b.

13)When two or more objects are added as listeners for the same event, which listener is first invoked to handle the event?a)The first object that was added as listener. b)The last object that was added as listener. c)There is no way to determine which listener will be invoked first. d)It is impossible to have more than one listener for a given event.Ans : c.

14)Which of the following components generate action events?a)Buttons

By: Amit Kumar Agrawal 709

The Smartest Way to Learn Java5

b)Labels c)Check boxes d)WindowsAns : a.

15)Which of the following are true?

a)A TextField object may generate an ActionEvent. b)A TextArea object may generate an ActionEvent. c)A Button object may generate an ActionEvent. d)A MenuItem object may generate an ActionEvent.Ans : a,c and d.

16)Which of the following are true?a)The MouseListener interface defines methods for handling mouse clicks. b)The MouseMotionListener interface defines methods for handling mouse clicks. c)The MouseClickListener interface defines methods for handling mouse clicks. d)The ActionListener interface defines methods for handling the clicking of a button.Ans : a and d.

APPLETS

1)What is an Applet? Should applets have constructors?

Ans : Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java capable browser. We don’t have the concept of Constructors in Applets.

2)How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string?

Ans : Use the parseInt() method in the Integer Class, the Float(String) constructor in the Class Float, or the Double(String) constructor in the class Double.

3)How can I arrange for different applets on a web page to communicate with each other?

By: Amit Kumar Agrawal 710

The Smartest Way to Learn Java5

Ans : Name your applets inside the Applet tag and invoke AppletContext’s

getApplet() method in your applet code to obtain references to the other applets on

the page.

4)How do I select a URL from my Applet and send the browser to that page? Ans : Ask the applet for its applet context and invoke showDocument() on that context object.

Eg. URL targetURL;String URLStringAppletContext context = getAppletContext();try{targetUR L = new URL(URLString);} catch (Malformed URLException e){// Code for recover from the exception }context. showDocument (targetURL);Can applets on different pages communicate with each other?

Ans : No. Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system.

5)How do Applets differ from Applications? Ans : Appln: Stand Alone

Applet: Needs no explicit installation on local m/c.

Appln: Execution starts with main() method.

Applet: Execution starts with init() method.

Appln: May or may not be a GUI

Applet: Must run within a GUI (Using AWT)

6)How do I determine the width and height of my application?

By: Amit Kumar Agrawal 711

The Smartest Way to Learn Java5

Ans : Use the getSize() method, which the Applet class inherits from the

Component class in the Java.awt package. The getSize() method returns the size of

the applet as a Dimension object, from which you extract separate width, height

fields.

Eg. Dimension dim = getSize ();int appletwidth = dim.width ();

7) What is AppletStub Interface?Ans : The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface.It is essential to have both the .java file and the .html file of an applet in the same directory.a)True. b)False.Ans : b.

8)The <PARAM> tag contains two attributes namely _________ and _______. Ans : Name , value. 9)Passing values to parameters is done in the _________ file of an applet.Ans : .html.

10) What tags are mandatory when creating HTML to display an applet a)name, height, width b)code, name c)codebase, height, width d) code, height, width Ans : d.

11)Applet’s getParameter( ) method can be used to get parameter values.a)True. b)False.Ans : a.

12)What are the Applet’s Life Cycle methods? Explain them? Ans : init( ) method - Can be called when an applet is first loaded.start( ) method - Can be called each time an applet is started.

By: Amit Kumar Agrawal 712

The Smartest Way to Learn Java5

paint( ) method - Can be called when the applet is minimized or refreshed.stop( ) method - Can be called when the browser moves off the applet’s page.destroy( ) method - Can be called when the browser is finished with the applet.

13)What are the Applet’s information methods? Ans : getAppletInfo( ) method : Returns a string describing the applet, its author ,copy right information, etc.getParameterInfo( ) method : Returns an array of string describing the applet’s parameters.

14)All Applets are subclasses of Applet.a)True. b)False.Ans : a.

15)All Applets must import java.applet and java.awt.a)True. b)False.Ans : a.

16)What are the steps involved in Applet development? Ans : a) Edit a Java source file,b) Compile your program andc) Execute the appletviewer, specifying the name of your applet’s source file.

17)Applets are executed by the console based Java run-time interpreter.a)True. b)False.Ans : b.

18)Which classes and interfaces does Applet class consist? Ans : Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub and AudioClip.

19)What is the sequence for calling the methods by AWT for applets?Ans : When an applet begins, the AWT calls the following methods, in this sequence.init( ) start( )

By: Amit Kumar Agrawal 713

The Smartest Way to Learn Java5

paint( )

20)Which method is used to output a string to an applet? Ans : drawString ( ) method.

21)Every color is created from an RGB value.a)True. b)FalseAns : a.

AWT : WINDOWS, GRAPHICS AND FONTS

1)How would you set the color of a graphics context called g to cyan?a)g.setColor(Color.cyan); b)g.setCurrentColor(cyan); c)g.setColor("Color.cyan"); d)g.setColor("cyan’); e)g.setColor(new Color(cyan));Ans : a.

2)The code below draws a line. What color is the line?g.setColor(Color.red.green.yellow.red.cyan);g.drawLine(0, 0, 100,100);

a)Red b)Green c)Yellow d)Cyan e)BlackAns : d.

3)What does the following code draw?g.setColor(Color.black);g.drawLine(10, 10, 10, 50);g.setColor(Color.RED);g.drawRect(100, 100, 150, 150);a)A red vertical line that is 40 pixels long and a red square with sides of 150 pixels b)A black vertical line that is 40 pixels long and a red square with sides of 150 pixels

By: Amit Kumar Agrawal 714

The Smartest Way to Learn Java5

c)A black vertical line that is 50 pixels long and a red square with sides of 150 pixels d)A red vertical line that is 50 pixels long and a red square with sides of 150 pixels e)A black vertical line that is 40 pixels long and a red square with sides of 100 pixelAns : b.

4)Which of the statements below are true?a)A polyline is always filled.b) A polyline can not be filled.c) A polygon is always filled.d) A polygon is always closede) A polygon may be filled or not filledAns : b, d and e.

5)What code would you use to construct a 24-point bold serif font?a)new Font(Font.SERIF, 24,Font.BOLD); b)new Font("SERIF", 24, BOLD"); c)new Font("BOLD ", 24,Font.SERIF); d)new Font("SERIF", Font.BOLD,24); e)new Font(Font.SERIF, "BOLD", 24);Ans : d.

6)What does the following paint( ) method draw?

Public void paint(Graphics g) {g.drawString("question #6",10,0);}

a)The string "question #6", with its top-left corner at 10,0 b)A little squiggle coming down from the top of the component, a little way in from the left edgeAns : b. 7)What does the following paint( ) method draw?

Public void paint(Graphics g) {

By: Amit Kumar Agrawal 715

The Smartest Way to Learn Java5

g.drawString("question #6",10,0);}a)A circle at (100, 100) with radius of 44 b)A circle at (100, 44) with radius of 100 c)A circle at (100, 44) with radius of 44 d)The code does not compileAns : d.

8)What is relationship between the Canvas class and the Graphics class?Ans : A Canvas object provides access to a Graphics object via its paint( ) method.

9)What are the Component subclasses that support painting. Ans : The Canvas, Frame, Panel and Applet classes support painting.

10)What is the difference between the paint( ) and repaint( ) method? Ans : The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting method.

10)What is the difference between the Font and FontMetrics classes? Ans : The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

11)Which of the following are passed as an argument to the paint( ) method?a)A Canvas object b)A Graphics object c)An Image object d)A paint objectAns : b.

12)Which of the following methods are invoked by the AWT to support paint and repaint operations?a)paint( ) b)repaint( ) c)draw( ) d)redraw( )Ans : a.

By: Amit Kumar Agrawal 716

The Smartest Way to Learn Java5

13)Which of the following classes have a paint( ) method?a)Canvas b)Image c)Frame d)Graphics Ans : a and c.

14)Which of the following are methods of the Graphics class?a)drawRect( ) b)drawImage( ) c)drawPoint( ) d)drawString( )Ans : a, b and d.

15)Which Font attributes are available through the FontMetrics class?a)ascent b)leading c)case d)heightAns : a, b and d.

16)Which of the following are true?a)The AWT automatically causes a window to be repainted when a portion of a window has been minimized and then maximized. b)The AWT automatically causes a window to be repainted when a portion of a window has been covered and then uncovered. c)The AWT automatically causes a window to be repainted when application data is changed. d)The AWT does not support repainting operations. Ans : a and b.

17)Which method is used to size a graphics object to fit the current size of the window? Ans : getSize( ) method.

18)What are the methods to be used to set foreground and background colors?Ans : setForeground( ) and setBackground( ) methods.

By: Amit Kumar Agrawal 717

The Smartest Way to Learn Java5

19) You have created a simple Frame and overridden the paint method as follows

public void paint(Graphics g){ g.drawString("Dolly",50,10);}What will be the result when you attempt to compile and run the program?

a)The string "Dolly" will be displayed at the centre of the frameb) An error at compilation complaining at the signature of the paint method c) The lower part of the word Dolly will be seen at the top of the form, with the top hidden. d) The string "Dolly" will be shown at the bottom of the form Ans : c.

20) Where g is a graphics instance what will the following code draw on the screen. g.fillArc(45,90,50,50,90,180);a) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting at an angle of 90 degrees traversing through 180 degrees counter clockwise.b) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting at an angle of 90 degrees traversing through 180 degrees clockwise.c) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45, 90, starting at 90 degrees and traversing through 180 degrees counter clockwise.d) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a box of height 50, width 50 with a centre point of 90, 180.Ans : c.

21) Given the following code import java.awt.*;public class SetF extends Frame{public static void main(String argv[]){SetF s = new SetF();s.setSize(300,200);s.setVisible(true);}

By: Amit Kumar Agrawal 718

The Smartest Way to Learn Java5

} How could you set the frame surface color to pinka)s.setBackground(Color.pink);b)s.setColor(PINK);c)s.Background(pink);d)s.color=Color.pinkAns : a.

AWT: CONTROLS, LAYOUT MANAGERS AND MENUS

1)What is meant by Controls and what are different types of controls?Ans : Controls are componenets that allow a user to interact with your application.The AWT supports the following types of controls:Labels Push buttons Check boxes Choice lists Lists Scroll bars Text componentsThese controls are subclasses of Component.

2)You want to construct a text area that is 80 character-widths wide and 10 character-heights tall. What code do you use?a)new TextArea(80, 10) b)new TextArea(10, 80)Ans: b.

3)A text field has a variable-width font. It is constructed by calling new TextField("iiiii"). What happens if you change the contents of the text field to "wwwww"? (Bear in mind that is one of the narrowest characters, and w is one of the widest.)a)The text field becomes wider. b)The text field becomes narrower. c)The text field stays the same width; to see the entire contents you will have to scroll by using the ß and à keys. d)The text field stays the same width; to see the entire contents you will have to scroll by using the text field’s horizontal scroll bar.

By: Amit Kumar Agrawal 719

The Smartest Way to Learn Java5

Ans : c.

4)The CheckboxGroup class is a subclass of the Component class.a)True b)FalseAns : b.

5) What are the immediate super classes of the following classes?a) Container class b) MenuComponent class c) Dialog class d) Applet class e) Menu classAns : a) Container - Component b) MenuComponent - Object c) Dialog - Window d) Applet - Panele) Menu - MenuItem

6) What are the SubClass of Textcomponent Class?Ans : TextField and TextArea

7) Which method of the component class is used to set the position and the size of a component?Ans : setBounds()

8) Which TextComponent method is used to set a TextComponent to the read-only state?Ans : setEditable()

9) How can the Checkbox class be used to create a radio button?Ans : By associating Checkbox objects with a CheckboxGroup.

10) What Checkbox method allows you to tell if a Checkbox is checked?Ans : getState()

11) Which Component method is used to access a component's immediate Container?a)getVisible() b)getImmediate

By: Amit Kumar Agrawal 720

The Smartest Way to Learn Java5

c)getParent() d)getContainerAns : c.

12) What methods are used to get and set the text label displayed by a Button object?Ans : getLabel( ) and setLabel( )

13) What is the difference between a Choice and a List?Ans : A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice.A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

14) Which Container method is used to cause a container to be laid out and redisplayed?Ans : validate( )

15) What is the difference between a Scollbar and a Scrollpane?Ans : A Scrollbar is a Component, but not a Container.A Scrollpane is a Container and handles its own events and performs its own scrolling.

16) Which Component subclass is used for drawing and painting?Ans : Canvas.

17) Which of the following are direct or indirect subclasses of Component?a)Button b)Label c)CheckboxMenuItem d)Toolbar e)FrameAns : a, b and e.

18) Which of the following are direct or indirect subclasses of Container?a)Frame b)TextArea c)MenuBar

By: Amit Kumar Agrawal 721

The Smartest Way to Learn Java5

d)FileDialog e)AppletAns : a,d and e.

19) Which method is used to set the text of a Label object?a)setText( ) b)setLabel( ) c)setTextLabel( ) d)setLabelText( )Ans : a.20) Which constructor creates a TextArea with 10 rows and 20 columns?a)new TextArea(10, 20) b)new TextArea(20, 10) c)new TextArea(new Rows(10), new columns(20)) d)new TextArea(200)Ans : a.

(Usage is TextArea(rows, columns)

21) Which of the following creates a List with 5 visible items and multiple selection enabled?a)new List(5, true) b)new List(true, 5) c)new List(5, false) d)new List(false,5)Ans : a.

[Usage is List(rows, multipleMode)]

22) Which are true about the Container class?a)The validate( ) method is used to cause a Container to be laid out and redisplayed. b)The add( ) method is used to add a Component to a Container. c)The getBorder( ) method returns information about a Container’s insets. d)The getComponent( ) method is used to access a Component that is contained in a Container.Ans : a, b and d.

23)What will be the result of compiling the following code: public class Test {

By: Amit Kumar Agrawal 722

The Smartest Way to Learn Java5

public static void main (String args []) {int age;age = age + 1;System.out.println("The age is " + age);}}1) Compiles and runs with no output2) Compiles and runs printing out The age is 13) Compiles but generates a runtime error4) Does not compile5) Compiles but generates a compile time errorAnswer : 4

24)Which of these is the correct format to use to create the literal char value a? (multiple)1) 'a'2) "a"3) new Character(a)4) \000aAnswer : 1

25)What is the legal range of a byte integral type? 1) 0 - 65, 5352) (-128) - 1273) (-32,768) - 32,7674) (-256) - 255Answer : 2

26)Which of the following is illegal: 1) int i = 32;2) float f = 45.0;3) double d = 45.0;Answer 2

27)What will be the result of compiling the following code: public class Test {static int age;public static void main (String args []) {age = age + 1;System.out.println("The age is " + age);

By: Amit Kumar Agrawal 723

The Smartest Way to Learn Java5

}}1) Compiles and runs with no output2) Compiles and runs printing out The age is 13) Compiles but generates a runtime error4) Does not compile5) Compiles but generates a compile time errorAnswer : 2

28)Which of the following are correct? (multiple)1) 128 >> 1 gives 642) 128 >>> 1 gives 643) 128 >> 1 gives -644) 128 >>> 1 gives -64Answer : 1

29)Which of the following return true? (multiple)1) "john" == new String("john")2) "john".equals("john")3) "john" = "john"4) "john".equals(new Button("john"))Answer : 2

30)Which of the following do not lead to a runtime error? (multiple)1) "john" + " was " + " here"2) "john" + 33) 3 + 54) 5 + 5.5answer 1,2,3,4

31)Which of the following are so called "short circuit" logical operators? (multiple)1) &2) ||3) &&4) |

By: Amit Kumar Agrawal 724

The Smartest Way to Learn Java5

Answer : 2,3

32)Which of the following are acceptable? (multiple)1) Object o = new Button("A");2) Boolean flag = true;3) Panel p = new Frame();4) Frame f = new Panel();5) Panel p = new Applet();Answer : 1,533)What is the result of compiling and running the following code: public class Test {static int total = 10;public static void main (String args []) {new Test();}public Test () {System.out.println("In test");System.out.println(this);int temp = this.total;if (temp > 5) {System.out.println(temp);}}}(multiple)1) The class will not compile2) The compiler reports and error at line 23) The compiler reports an error at line 94) The value 10 is one of the elements printed to the standard output5) The class compiles but generates a runtime errorAnswer : 4

34)Which of the following is correct: 1) String temp [] = new String {"j" "a" "z"};2) String temp [] = { "j " " b" "c"};3) String temp = {"a", "b", "c"};4) String temp [] = {"a", "b", "c"};Answer 4

By: Amit Kumar Agrawal 725

The Smartest Way to Learn Java5

35)What is the correct declaration of an abstract method that is intended to be public: 1) public abstract void add();2) public abstract void add() {}3) public abstract add();4) public virtual add();Answer : 1

36)Under what situations do you obtain a default constructor? 1) When you define any class2) When the class has no other constructors3) When you define at least one constructorAnswer : 2

37)Which of the following can be used to define a constructor for this class, given the following code: public class Test {...}1) public void Test() {...}2) public Test() {...}3) public static Test() {...}4) public static void Test() {...}Answer : 2

38)Which of the following are acceptable to the Java compiler: (multiple)1) if (2 == 3) System.out.println("Hi");2) if (2 = 3) System.out.println("Hi");3) if (true) System.out.println("Hi");4) if (2 != 3) System.out.println("Hi");5) if (aString.equals("hello")) System.out.println("Hi");Answer : 1,3,4,5

39)Assuming a method contains code which may raise an Exception (but not a RuntimeException), what is the correct way for a method to indicate that it expects the caller to handle that exception: 1) throw Exception

By: Amit Kumar Agrawal 726

The Smartest Way to Learn Java5

2) throws Exception3) new Exception4) Don't need to specify anythingAnswer : 2

40)What is the result of executing the following code, using the parameters 4 and 0: public void divide(int a, int b) {try {int c = a / b;} catch (Exception e) {System.out.print("Exception ");} finally {System.out.println("Finally");}1) Prints out: Exception Finally2) Prints out: Finally3) Prints out: Exception4) No outputAnswer : 1

41)Which of the following is a legal return type of a method overloading the following method: public void add(int a) {...}1) void2) int3) Can be anythingAnswer : 3

42)Which of the following statements is correct for a method which is overriding the following method: public void add(int a) {...}1) the overriding method must return void2) the overriding method must return int3) the overriding method can return whatever it likesAnswer : 1

43)Given the following classes defined in separate files, what will be the effect of compiling and running this class Test? class Vehicle {

By: Amit Kumar Agrawal 727

The Smartest Way to Learn Java5

public void drive() {System.out.println("Vehicle: drive");}}class Car extends Vehicle {public void drive() {System.out.println("Car: drive");}}public class Test {public static void main (String args []) {Vehicle v;Car c;v = new Vehicle();c = new Car();v.drive();c.drive();v = c;v.drive();}}1) Generates a Compiler error on the statement v= c;2) Generates runtime error on the statement v= c;3) Prints out:Vehicle: driveCar: driveCar: drive4) Prints out: Vehicle: driveCar: driveVehicle: driveAnswer : 3

44)Where in a constructor, can you place a call to a constructor defined in the super class? 1) Anywhere2) The first statement in the constructor3) The last statement in the constructor4) You can't call super in a constructorAnswer : 2

By: Amit Kumar Agrawal 728

The Smartest Way to Learn Java5

45)Which variables can an inner class access from the class which encapsulates it? (multiple)1) All static variables2) All final variables3) All instance variables4) Only final instance variables5) Only final static variablesAnswer : 1,2,3

46)What class must an inner class extend: 1) The top level class2) The Object class3) Any class or interface4) It must extend an interfaceAnswer 3

47)In the following code, which is the earliest statement, where the object originally held in e, may be garbage collected: 1. public class Test {2. public static void main (String args []) {3. Employee e = new Employee("Bob", 48);4. e.calculatePay();5. System.out.println(e.printDetails());6. e = null;7. e = new Employee("Denise", 36);8. e.calculatePay();9. System.out.println(e.printDetails());10. }11. }

1) Line 102) Line 113) Line 74) Line 85) NeverAnswer : 3

By: Amit Kumar Agrawal 729

The Smartest Way to Learn Java5

48)What is the name of the interface that can be used to define a class that can execute within its own thread? 1) Runnable2) Run3) Threadable4) Thread5) ExecutableAnswer : 1

49)What is the name of the method used to schedule a thread for execution? 1) init();2) start();3) run();4) resume();5) sleep();Answer : 2

50)Which methods may cause a thread to stop executing? (multiple)1) sleep();2) stop();3) yield();4) wait();5) notify();6) notifyAll()7) synchronized()Answer : 1,2,3,4

51)Which of the following would create a text field able to display 10 characters (assuming a fixed size font) displaying the initial string "hello": 1) new TextField("hello", 10);2) new TextField("hello");3) new textField(10);4) new TextField();Answer : 1

52)Which of the following methods are defined on the Graphics class:

By: Amit Kumar Agrawal 730

The Smartest Way to Learn Java5

(multiple)1) drawLine(int, int, int, int)2) drawImage(Image, int, int, ImageObserver)3) drawString(String, int, int)4) add(Component);5) setVisible(boolean);6) setLayout(Object);Answer : 1,2,3

53)Which of the following layout managers honours the preferred size of a component: (multiple)1) CardLayout2) FlowLayout3) BorderLayout4) GridLayoutAnswer : 2

54)Given the following code what is the effect of a being 5: public class Test {public void add(int a) {loop: for (int i = 1; i < 3; i++){for (int j = 1; j < 3; j++) {if (a == 5) {break loop;}System.out.println(i * j);}}}}

1) Generate a runtime error2) Throw an ArrayIndexOutOfBoundsException3) Print the values: 1, 2, 2, 44) Produces no outputAnswer : 4

By: Amit Kumar Agrawal 731

The Smartest Way to Learn Java5

55)What is the effect of issuing a wait() method on an object 1) If a notify() method has already been sent to that object then it has no effect2) The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method3) An exception will be raised4) The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object.Answer : 2

56)The layout of a container can be altered using which of the following methods: (multiple)1) setLayout(aLayoutManager);2) addLayout(aLayoutManager);3) layout(aLayoutManager);4) setLayoutManager(aLayoutManager);Answer : 1

57)Using a FlowLayout manager, which is the correct way to add elements to a container: 1) add(component);2) add("Center", component);3) add(x, y, component);4) set(component);Answer : 1

58)Given that a Button can generate an ActionEvent which listener would you expect to have to implement, in a class which would handle this event? 1) FocusListener2) ComponentListener3) WindowListener4) ActionListener5) ItemListenerAnswer : 4

59)Which of the following, are valid return types, for listener methods: 1) boolean2) the type of event handled3) void

By: Amit Kumar Agrawal 732

The Smartest Way to Learn Java5

4) ComponentAnswer : 3

60)Assuming we have a class which implements the ActionListener interface, which method should be used to register this with a Button? 1) addListener(*);2) addActionListener(*);3) addButtonListener(*);4) setListener(*);Answer : 261)In order to cause the paint(Graphics) method to execute, which of the following is the most appropriate method to call: 1) paint()2) repaint()3) paint(Graphics)4) update(Graphics)5) None - you should never cause paint(Graphics) to executeAnswer : 2

62)Which of the following illustrates the correct way to pass a parameter into an applet: 1) <applet code=Test.class age=33 width=100 height=100>2) <param name=age value=33>3) <applet code=Test.class name=age value=33 width=100 height=100>4) <applet Test 33>Answer : 2

63)Which of the following correctly illustrate how an InputStreamReader can be created: (multiple)1) new InputStreamReader(new FileInputStream("data"));2) new InputStreamReader(new FileReader("data"));3) new InputStreamReader(new BufferedReader("data"));4) new InputStreamReader("data");5) new InputStreamReader(System.in);Answer : 1,5

64)What is the permanent effect on the file system of writing data to a new FileWriter("report"), given the file report already exists? 1) The data is appended to the file

By: Amit Kumar Agrawal 733

The Smartest Way to Learn Java5

2) The file is replaced with a new file3) An exception is raised as the file already exists4) The data is written to random locations within the fileAnswer : 2

65)What is the effect of adding the sixth element to a vector created in the following manner: new Vector(5, 10);1) An IndexOutOfBounds exception is raised.2) The vector grows in size to a capacity of 10 elements3) The vector grows in size to a capacity of 15 elements4) Nothing, the vector will have grown when the fifth element was addedAnswer : 3

66)What is the result of executing the following code when the value of x is 2: switch (x) {case 1:System.out.println(1);case 2:case 3:System.out.println(3);case 4:System.out.println(4);}

1) Nothing is printed out2) The value 3 is printed out3) The values 3 and 4 are printed out4) The values 1, 3 and 4 are printed outAnswer : 3

67)What is the result of compiling and running the Second class? Consider the following example:class First {public First (String s) {System.out.println(s);}}public class Second extends First {public static void main(String args []) {

By: Amit Kumar Agrawal 734

The Smartest Way to Learn Java5

new Second();}}

1) Nothing happens2) A string is printed to the standard out3) An instance of the class First is generated4) An instance of the class Second is created5) An exception is raised at runtime stating that there is no null parameter constructor in class First.6) The class second will not compile as there is no null parameter constructor in the class FirstAnswer : 6

68)What is the result of executing the following fragment of code: boolean flag = false;if (flag = true) {System.out.println("true");} else {System.out.println("false");}1) true is printed to standard out2) false is printed to standard out3) An exception is raised4) Nothing happensAnswer : 1

69)Consider the following classes. What is the result of compiling and running this class? public class Test {public static void test() {this.print();}public static void print() {System.out.println("Test");}public static void main(String args []) {test();}}

By: Amit Kumar Agrawal 735

The Smartest Way to Learn Java5

(multiple)1) The string Test is printed to the standard out.2) A runtime exception is raised stating that an object has not been created.3) Nothing is printed to the standard output.4) An exception is raised stating that the method test cannot be found.5) An exception is raised stating that the variable this can only be used within an instance.6) The class fails to compile stating that the variable this is undefined.Answer : 670)Examine the following class definition: public class Test {public static void test() {print();}public static void print() {System.out.println("Test");}public void print() {System.out.println("Another Test");}}What is the result of compiling this class:1) A successful compilation.2) A warning stating that the class has no main method.3) An error stating that there is a duplicated method.4) An error stating that the method test() will call one or other of the print() methods.Answer : 3

71)What is the result of compiling and executing the following Java class: public class ThreadTest extends Thread {public void run() {System.out.println("In run");suspend();resume();System.out.println("Leaving run");}public static void main(String args []) {(new ThreadTest()).start();

By: Amit Kumar Agrawal 736

The Smartest Way to Learn Java5

}}1) Compilation will fail in the method main.2) Compilation will fail in the method run.3) A warning will be generated for method run.4) The string "In run" will be printed to standard out.5) Both strings will be printed to standard out.6) Nothing will happen.Answer : 472)Given the following sequence of Java statements, Which of the following options are true: 1. StringBuffer sb = new StringBuffer("abc");2. String s = new String("abc");3. sb.append("def");4. s.append("def");5. sb.insert(1, "zzz");6. s.concat(sb);7. s.trim();

(multiple)1) The compiler would generate an error for line 1.2) The compiler would generate an error for line 2.3) The compiler would generate an error for line 3.4) The compiler would generate an error for line 4.5) The compiler would generate an error for line 5.6) The compiler would generate an error for line 6.7) The compiler would generate an error for line 7.Answer : 4,6

73)What is the result of executing the following Java class: import java.awt.*;public class FrameTest extends Frame {public FrameTest() {add (new Button("First"));add (new Button("Second"));add (new Button("Third"));pack();setVisible(true);}public static void main(String args []) {

By: Amit Kumar Agrawal 737

The Smartest Way to Learn Java5

new FrameTest();}}

1) Nothing happens.2) Three buttons are displayed across a window.3) A runtime exception is generated (no layout manager specified).4) Only the "first" button is displayed.5) Only the "second" button is displayed.6) Only the "third" button is displayed.Answer : 6

74)Consider the following tags and attributes of tags, which can be used with the <AAPLET> and </APPLET> tags? 1. CODEBASE2. ALT3. NAME4. CLASS5. JAVAC6. HORIZONTALSPACE7. VERTICALSPACE8. WIDTH9. PARAM10. JAR(multiple)1) line 1, 2, 32) line 2, 5, 6, 73) line 3, 4, 54) line 8, 9, 105) line 8, 9Answer : 1,5

75)Which of the following is a legal way to construct a RandomAccessFile: 1) RandomAccessFile("data", "r");2) RandomAccessFile("r", "data");3) RandomAccessFile("data", "read");4) RandomAccessFile("read", "data");Answer : 1Carefully examine the following code, When will the string "Hi there" be printed? public class StaticTest {

By: Amit Kumar Agrawal 738

The Smartest Way to Learn Java5

static {System.out.println("Hi there");}public void print() {System.out.println("Hello");}public static void main(String args []) {StaticTest st1 = new StaticTest();st1.print();StaticTest st2 = new StaticTest();st2.print();}}1) Never.2) Each time a new instance is created.3) Once when the class is first loaded into the Java virtual machine.4) Only when the static method is called explicitly.Answer : 3

76)What is the result of the following program: public class Test {public static void main (String args []) {boolean a = false;if (a = true)System.out.println("Hello");elseSystem.out.println("Goodbye");}}1) Program produces no output but terminates correctly.2) Program does not terminate.3) Prints out "Hello"4) Prints out "Goodbye"Answer : 3

77)Examine the following code, it includes an inner class, what is the result: public final class Test4 {class Inner {void test() {if (Test4.this.flag); {

By: Amit Kumar Agrawal 739

The Smartest Way to Learn Java5

sample();}} }private boolean flag = true;public void sample() {System.out.println("Sample");}public Test4() {(new Inner()).test();}public static void main(String args []) {new Test4();} }

1) Prints out "Sample"2) Program produces no output but terminates correctly.3) Program does not terminate.4) The program will not compileAnswer : 1

78)Carefully examine the following class: public class Test5 {public static void main (String args []) {/* This is the start of a commentif (true) {Test5 = new test5();System.out.println("Done the test");}/* This is another comment */System.out.println ("The end");}}1) Prints out "Done the test" and nothing else.2) Program produces no output but terminates correctly.3) Program does not terminate.4) The program will not compile.5) The program generates a runtime exception.6) The program prints out "The end" and nothing else.

By: Amit Kumar Agrawal 740

The Smartest Way to Learn Java5

7) The program prints out "Done the test" and "The end"Answer : 6

79)What is the result of compiling and running the following applet: import java.applet.Applet;import java.awt.*;public class Sample extends Applet {private String text = "Hello World";public void init() {add(new Label(text));}public Sample (String string) {text = string;}}It is accessed form the following HTML page:<html><title>Sample Applet</title><body><applet code="Sample.class" width=200 height=200></applet></body></html>

1) Prints "Hello World".2) Generates a runtime error.3) Does nothing.4) Generates a compile time error.Answer : 2

80)What is the effect of compiling and (if possible) running this class:public class Calc {public static void main (String args []) {int total = 0;for (int i = 0, j = 10; total > 30; ++i, --j) {System.out.println(" i = " + i + " : j = " + j);total += (i + j);}System.out.println("Total " + total);}}

By: Amit Kumar Agrawal 741

The Smartest Way to Learn Java5

1) Produce a runtime error2) Produce a compile time error3) Print out "Total 0"4) Generate the following as output:i = 0 : j = 10i = 1 : j = 9i = 2 : j = 8Total 30Answer : 3  Utility Package

1) What is the Vector class?ANSWER : The Vector class provides the capability to implement a growable array of objects.

2) What is the Set interface?ANSWER : The Set interface provides methods for accessing the elements of a finite mathematical set.Sets do not allow duplicate elements.

3) What is Dictionary class?ANSWER : The Dictionary class is the abstarct super class of Hashtable and Properties class.Dictionary provides the abstarct functions used to store and retrieve objects by key-value.This class allows any object to be used as a key or value.

4) What is the Hashtable class?ANSWER : The Hashtable class implements a hash table data structure. A hash table indexes and stores objects in a dictionary using hash codes as the objects' keys. Hash codes are integer values that identify objects.

5) What is the Properties class?Answer : The properties class is a subclass of Hashtable that can be read from or written to a stream.It also provides the capability to specify a set of default values to be used if a specified key is not found in the table. We have two methods load() and save().

6) What changes are needed to make the following prg to compile?import java.util.*;class Ques{public static void main (String args[]) {

By: Amit Kumar Agrawal 742

The Smartest Way to Learn Java5

String s1 = "abc";String s2 = "def";Vector v = new Vector();v.add(s1);v.add(s2);String s3 = v.elementAt(0) + v.elementAt(1);System.out.println(s3);}}

ANSWER : A)Declare Ques as public B) Cast v.elementAt(0) to a StringC) Cast v.elementAt(1) to an Object. D) Import java.lang

ANSWER : B) Cast v.elementAt(0) to a String

7) What is the output of the prg.import java.util.*;class Ques{public static void main (String args[]) {String s1 = "abc";String s2 = "def";Stack stack = new Stack(); stack.push(s1);stack.push(s2);try{String s3 = (String) stack.pop() + (String) stack.pop() ;System.out.println(s3);}catch (EmptyStackException ex){}}}A) abcdef B) defabc C) abcabc D) defdefANSWER : B) defabc

8) Which of the following may have duplicate elements?A) Collection B) List C) Map D) SetANSWER : A and B Neither a Map nor a Set may have duplicate elements.

By: Amit Kumar Agrawal 743

The Smartest Way to Learn Java5

9) Can null value be added to a List?ANSWER : Yes.A Null value may be added to any List.

10) What is the output of the following prg.import java.util.*;class Ques{public static void main (String args[]) {HashSet set = new HashSet();String s1 = "abc";String s2 = "def";String s3 = "";set.add(s1);set.add(s2);set.add(s1);set.add(s2);Iterator i = set.iterator();while(i.hasNext()){s3 += (String) i.next();}System.out.println(s3);}}

A) abcdefabcdef B) defabcdefabc C) fedcbafedcba D) defabcANSWER : D) defabc. Sets may not have duplicate elements.

11) Which of the following java.util classes support internationalization?

A) Locale B) ResourceBundle C) Country D) Language

ANSWER : A and B . Country and Language are not java.util classes.

12 ) What is the ResourceBundle?The ResourceBundle class also supports internationalization.ResourceBundle subclasses are used to store locale-specific resources that can be loaded by a program to tailor the program's appearence to the paticular locale in which it is being run. Resource Bundles provide the capability to isolate a program's locale-specific resources in a standard and modular manner.

By: Amit Kumar Agrawal 744

The Smartest Way to Learn Java5

13) How are Observer Interface and Observable class, in java.util package, used?ANSWER : Objects that subclass the Observable class maintain a list of Observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

14) Which java.util classes and interfaces support event handling?ANSWER : The EventObject class and the EventListener interface support event processing.

15) Does java provide standard iterator functions for inspecting a collection of objects?ANSWER : The Enumeration interface in the java.util package provides a framework for stepping once through a collection of objects. We have two methods in that interface.public interface Enumeration {boolean hasMoreElements();Object nextElement();}

16) The Math.random method is too limited for my needs- How can I generate random numbers more flexibly?ANSWER : The random method in Math class provide quick, convienient access to random numbers, but more power and flexibility use the Random class in the java.util package.double doubleval = Math.random();The Random class provide methods returning float, int, double, and long values.nextFloat() // type float; 0.0 <= value < 1.0nextDouble() // type double; 0.0 <= value < 1.0nextInt() // type int; Integer.MIN_VALUE <= value <= Integer.MAX_VALUEnextLong() // type long; Long.MIN_VALUE <= value <= Long.MAX_VALUEnextGaussian() // type double; has Gaussian("normal") distribution with mean 0.0 and standard deviation 1.0)Eg. Random r = new Random();float floatval = r.nextFloat(); 

By: Amit Kumar Agrawal 745

The Smartest Way to Learn Java5

 17) How can we get all public methods of an object dynamically?ANSWER : By using getMethods(). It return an array of method objects corresponding to the public methods of this class. getFields() returns an array of Filed objects corresponding to the public Fields(variables) of this class.getConstructors() returns an array of constructor objects corresponding to the public constructors of this class.  

JDBC

1) What are the steps involved in establishing a connection?ANSWER : This involves two steps: (1) loading the driver and (2) making the connection.

2) How can you load the drivers?ANSWER : Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:Eg.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:Eg.Class.forName("jdbc.DriverXYZ");

3) What Class.forName will do while loading drivers?ANSWER : It is used to create an instance of a driver and register it with the DriverManager.When you have loaded a driver, it is available for making a connection with a DBMS.

4) How can you make the connection?ANSWER : In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:Eg.String url = "jdbc:odbc:Fred";

By: Amit Kumar Agrawal 746

The Smartest Way to Learn Java5

Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

5) How can you create JDBC statements?ANSWER : A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate.

Eg.It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :Statement stmt = con.createStatement();

6) How can you retrieve data from the ResultSet?ANSWER : Step 1.JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.Eg.ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");Step2.String s = rs.getString("COF_NAME");The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs

7) What are the different types of Statements?ANSWER : 1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall)

8) How can you use PreparedStatement?ANSWER : This special type of statement is derived from the more general class, Statement.If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement

By: Amit Kumar Agrawal 747

The Smartest Way to Learn Java5

object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first. Eg.PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

9) What setAutoCommit does?ANSWER : When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit modeEg.con.setAutoCommit(false);Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. Eg.con.setAutoCommit(false);PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");updateSales.setInt(1, 50);updateSales.setString(2, "Colombian");updateSales.executeUpdate();PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");updateTotal.setInt(1, 50);updateTotal.setString(2, "Colombian");updateTotal.executeUpdate();con.commit();con.setAutoCommit(true);

10) How to call a Strored Procedure from JDBC?ANSWER : The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure;Eg.CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

By: Amit Kumar Agrawal 748

The Smartest Way to Learn Java5

ResultSet rs = cs.executeQuery();

11) How to Retrieve Warnings?ANSWER : SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling objectEg.SQLWarning warning = stmt.getWarnings();if (warning != null) {System.out.println("\n---Warning---\n");while (warning != null) {System.out.println("Message: " + warning.getMessage());System.out.println("SQLState: " + warning.getSQLState());System.out.print("Vendor error code: ");System.out.println(warning.getErrorCode());System.out.println("");warning = warning.getNextWarning();}}

12) How can you Move the Cursor in Scrollable Result Sets ?ANSWER : One of the new features in the JDBC 2.0 API is the ability to move a result set's cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor. Eg.Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE . The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must

By: Amit Kumar Agrawal 749

The Smartest Way to Learn Java5

specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY

13) What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?ANSWER : You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopenedEg.Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");srs.afterLast();while (srs.previous()) {String name = srs.getString("COF_NAME");float price = srs.getFloat("PRICE");System.out.println(name + " " + price);}

14) How to Make Updates to Updatable Result Sets?ANSWER : Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.Eg.

By: Amit Kumar Agrawal 750

The Smartest Way to Learn Java5

Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Servlets 1) What is the servlet?ANSWER : Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

2) Whats the advantages using servlets than using CGI?ANSWER : Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

3) What are the uses of Servlets?ANSWER : A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets.Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

4) Which pakage provides interfaces and classes for writing servlets?ANSWER : javax

5) Whats the Servlet Interfcae?

By: Amit Kumar Agrawal 751

The Smartest Way to Learn Java5

ANSWER : The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.Servlets-->Generic Servlet-->HttpServlet-->MyServlet.The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

6) When a servlet accepts a call from a client, it receives two objects- What are they?ANSWER : ServeltRequest: Which encapsulates the communication from the client to the server.ServletResponse: Whcih encapsulates the communication from the servlet back to the client.ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

7) What information that the ServletRequest interface allows the servlet access to?ANSWER : Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

8) What information that the ServletResponse interface gives the servlet methods for replying to the client? ANSWER : It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

9) What is the servlet Lifecycle?ANSWER : Each servlet has the same life cycle: A server loads and initializes the servlet (init())The servlet handles zero or more client requests (service())

By: Amit Kumar Agrawal 752

The Smartest Way to Learn Java5

The server removes the servlet (destroy())(some servers do this step only when they shut down)

10) How HTTP Servlet handles client requests?ANSWER : An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

SOME VERY TRICKY QUESTIONS IN CORE JAVA

THREAD

Q: Explain the Green Threads and Native Threads?

Ans: Thread that is implemented in JVM itself is called Green Thread and It can run in any OS, That’s why it is also called blind thread. Native thread is totally depend upon the JVM as it is going to be served or processed by a Uni-Processor System. It is totally Hardware and Software dependent in nature.

Q: Is the Quited Thread can be restarted?

Ans: No, The Thread that is out of the run loop can not be restart.we have to use either wait or notify or we can create a new thread.

Q: What is the reason behind the thread sleeps for a longer time than that we mention in our code? (Generally after few time of run)

Ans: Java Development Kit never guaranted that it will run exactly for xxxx ms(milli second) but it will never wakeup before the time mention. For achieving good result we can refer PERC from www.nemonics.com or something else.

Q: Is it possible to run two different threads in two different JVM can find each other?

By: Amit Kumar Agrawal 753

The Smartest Way to Learn Java5

Ans: Yes, Using of piped streams is only support to achieve the same goal in one JVM and by using socket we can perform IPC kind of task as asked in the question. RMI is also another way to perform the same required task.

Q: When will a thread object is garbage collected?

Ans: As thread is also a object it will only garbage collected when the count is zero. We think that when the thread is in dead state it is useless, why not garbage collect it? That is because thread object may itself contain some usefull information, even the thread is in dead state. So it is non-sense to do garbage collect before the count is zero.

APPLET

Q: Is it possible to perform a connection with a other machine in internet using sockets with Applet?

Ans: No, It is not possible to connect with a URL through socket in Applet as the standard security concept of a Applet is a “Sandbox”. An Applet can’t talk with a machine (outside’s memory space), can’t talk to any file atall, can’t talk in internet except the parent machine. This can only be possible if the URL is nothing but URL of parent machine.

Q: How do I view the error output from my java-Applet in Internet Explorer?

Ans: The file windows\java\javalog.txt contain all the information about the last loaded applet file in the browser. All the system.out messages and the exception information stored in this file. To enabled this service we have to first go View/Option/Advanced then select the “Enable Java Logging” option of the InternetExplorer then click OK and re-start the system.

Q: Is it possible to reduce the download time of the Applet file?

Ans: Yes, It possible to reduce the download time of the java Applet. It is possible by creating the JAR file of the same Applet file. JAR file is the compressed file that is useful for reducing the size of the actual file and enhance the download speed of the file.

By: Amit Kumar Agrawal 754

The Smartest Way to Learn Java5

Q: When I reload my applet my hidden canvas is shown directly Why?

Ans: If we set the mycavas.setVisible(false); in the init() method then this problem occurs so by writing this code in start() method we can avoid the same problem.

Q: What are the restriction with Applet?

Ans: Applets are prevented to do reading and writing task from the client machine. Making network connection with other machine except the parent one. It doesn’t allow to run other programs, It also restrict to load libraries into the client machine from the host-machine etc.

Q: What is a “MAGIC NUMBER” and generally When we fot a message like “WRONG MAGIC NUMBER” and why?

Ans: The firt thing a JVM does when it loads a class file is to check for the first four bytes (in hex) CA FE BA BE or not,this is called the magic number. This tend the mention error that “WRONG MAGIC NUMBER” because the file that we are trying to load into the browser is not a class file.

Q: Is the DOS window(Win98 SE) support java Applet?

Ans: No, A DOS window is CUI based device. We cann’t use appletviewer program that comes with JDK. AWT and SWINGS

Q: How we can minimize flickers in animation?

Ans: By overriding update method.public void update(Graphics g){

paint(g);}

Also By using double buffering we minimize the flicker in animation. Double buffer means we are using two buffers to draw the image and switch between them.

Q: How we can set JFrame to be full screen at the start of the program? I don’t need a border and title just want to utilize the full screen?

By: Amit Kumar Agrawal 755

The Smartest Way to Learn Java5

Ans: Instead of using JFrame we can use JWindow that can easily be customize to have no border and title at the starting of the program. We have to go for the other method to achive our goal setBounds(), getDefaultScreenDevice(), getDefaultConfiguration() to fillout the whole screen.

Q: Why we cannot mix both AWT and SWINGS in a single program?

Ans: There are fundamental incompatibilities in the way they draw themselves. AWT java classes are not “pure java file”, they use underlying native codes where as the SWINGS are purly written in java and this make it more flexibleand platform independent. This is why there will be some conflict between them they cannot be mixed.

Q: Can I use Unicode directly in JTextField characters?

Ans: Yes, we can use Unicode character that is corresponding to our require character set. A table of Unicode is found in www.unicode.org/charts/.

Q: Is it possible to set a password in java application that will not echo on screen?

Ans: If you are using swing you can use JPasswordField, and set your echo character.

Q: How can I change the default icon in the application window to my own?

Ans:window.setIconImage(Toolkit.getDefaultToolkit().getImage(“filename.gif”));

Q: Why should any one use AWT rather than SWINGS?

Ans: There are somany handheld devices that donot have more memory or CPU poewer available, AWT is more suitable in this case.

Q: Why there is no change occurred when we change the title of dialog box using setTitle() method?

Ans: We need to update the dialog box by calling validate() ot invalidate().

By: Amit Kumar Agrawal 756

The Smartest Way to Learn Java5

Q: How we can disable the rightclick on the label ?

Ans: By using a if statement that will only execute when the left mouse button is clicked we can achieve the same.

Q: What is the difference between Frame and Canvas?

Ans: A Frame is window with Border, Maximize, Minimize, Restore, close buttons

and can not contain other elements, such as menu bar, buttons panel etc. A canvas

is a user interface element onto which you can draw and display something.

Q: How can we restrict the java not to set Background?

Ans: Just make a gif image with a transparent background having no element (Generally easy to draw using Photoshop) Java already handles drawing of transparent .gif files. This is how we can enable the java to not set any background.

MISCELLANEOUS

Q: What is the difference between VJ++ and Java by sun microsystem?

Ans: VJ++ is a Microsoft product designed as a “spoiler” product. It is totally windows based any code that is written in VJ++ can only be runned through Windows Operating System only. But the Java by sun micro system is platform independent in nature that .class file that is generated by JDK by sun microsystem is a instruction file for the JVM (It is platform specific(Generally set by OS vendordirectly)).

Q: Is password encryption of zip file is possible by using java.util.zip classes?

Ans: No, It is not possible, but Zips built-in encryption is not safe anymore as per the todays standard.

Q: Differenciate JDK, SDK and IDE?

By: Amit Kumar Agrawal 757

The Smartest Way to Learn Java5

Ans: IDE is acroynym for the Integrated Development Environment, these products are of one stop shops for coding. Here you can code, debug, create, package your software very easily. It gives a GUI based environment for the development, some popular JAVA IDE’s are JBuilder, NetBeans etc.

JDK is Java Design Kit is the CUI based JVM and classes that allow you to develop Java programs. Here the programmer is responcible for all kind of task, here the programmer write code and compile the same by himself and debug the same if any error is there. This allow the user to use any Text Editor to develop the java code.

SDK is the standard version of Java among the many of the available version such as Enterprise, Microedition and Standard. The SDK is used by most of the people in there Java programming.

Q: Why a programmer need to go only for JAVA?

Ans: Java is Object Oriented (Purely) and simple to understand. There are three basic piller for a good program that attract any programmer towards the same are SECURITY, SPEED, and PORTABILITY. These piller stabilize the program.

Picture that shows you stability level of the Languages.

By: Amit Kumar Agrawal 758

The Smartest Way to Learn Java5

C and C++ are the languages those are very much speed but it is not secure

and as well as not portable, this makes these languages not stable.

Smalltalk is the language that is Portable and Speed but the security aspect

of this language makes it incomplete.

Tcl is a security based language and as well as Portable but the Native

speed of the same language is not up to the mark that make the language

adaptable by every kind of programmer.

JAVA is the only language that is more stable in all these three aspect those

are SPEED, SECURE, and PORTABLE.

JAVA Security Model

Java is the only language that have a very flexible eror handling mechanism with a very powerful security model that makes the program bullet proof (Fault Proof). This aspect help you to prepare a program that will never hang, it will complete its execution cycle in every run.

PORTABILITY:

By: Amit Kumar Agrawal 759

The Smartest Way to Learn Java5

Java is portable as the java code is using a new type of file coding system that is called as Bytecode file. Byte code file is a set of instruction for the JVM(Java Virtual Machine) that is machine specific the JVM is generally provided by the system vendors directly so this never be a set of trouble for the java programmer. It can directly run in any kind machine with any kind of configuration. Bytecode file and JVM makes the java protable.

SPEED:

There is a mis-conception in most of the programmer that the Java is more slower then any other same level native languages like C and C++. Is speed is so much importan for any programmer? before we erase our JDK copy from the system we must have look with our currently available System that (Intel P-4 3.2 GHz HTprocessor, 512MB – 1GB RAM, 80-100GB HDD etc….) will minimize this speed problem and enhance the speed of the Java program.

Q: Why Java is called strongly typed?

Ans: It imposes strict rules on the declarations made in the code itself. Some languages allow a variable to represent an unknown data type, but languages such as Java force you to declare all variables to be a specific type before they can be used.

Q: Is there is a way to run a code after the Virtual Machine is instructed to exit?

Ans: In JDK1.3 we can use Runtime.addShutdownHook(Thread hook).

Q: Is it possible to run UNIX shell script from Java application?

Ans: Yes, It is possible to run a UNIX shell script through a java application. Execute a shellcand then write the name of the shell script on the shells stdin stream.

Process child=rtime.exec(“/bin/bash”);BufferedWriter BW=new BufferedWriter( new OutputStreamWritter( child.getOutputStream()));

By: Amit Kumar Agrawal 760

The Smartest Way to Learn Java5

BW.writeLine(“File Name”);BW.flush();

Q:class Voop{public static void main(String [] args){doStuff(1);doStuff(1,2);}// insert code here}

Which, inserted at line 6, will compile? (Choose all that apply.)

A). static void doStuff(int... doArgs) { }B). static void doStuff(int[] doArgs) { }C). static void doStuff(int doArgs...) { }D). static void doStuff(int... doArgs, int y) { }E). static void doStuff(int x, int... doArgs) { }F). None of the above code fragments will compile.

Ans: A and E use valid var-args syntax.

Q:

class Bird{{System.out.print("b1 ");}public Bird() { System.out.print("b2 "); }}class Raptor extends Bird{static {System.out.print("r1 "); }public Raptor() {System.out.print("r2 "); }{System.out.print("r3 ");}static {System.out.print("r4 ");}}class Hawk extends Raptor

By: Amit Kumar Agrawal 761

The Smartest Way to Learn Java5

{public static void main(String[] args){System.out.print("pre ");new Hawk();System.out.println("hawk ");}}

What is the result?

A). pre b1 b2 r3 r2 hawk

B). pre b2 b1 r2 r3 hawk

C). pre b2 b1 r2 r3 hawk r1 r4

D). r1 r4 pre b1 b2 r3 r2 hawk

E). r1 r4 pre b2 b1 r2 r3 hawk

F). pre r1 r4 b1 b2 r3 r2 hawk

G). pre r1 r4 b2 b1 r2 r3 hawk

H). The order of output cannot be predicted

I). Compilation fails

Ans: D is correct. Note: you'll probably never see this many choices on the realexam!

Q: Which are most typically thrown by an API developer or an application developer as opposed to being thrown by the JVM? (Choose all that apply.)

A). ClassCastExceptionB). IllegalStateExceptionC). NumberFormatExceptionD). IllegalArgumentExceptionE). ExceptionInInitializerError

Ans: B, C and D are correct.

By: Amit Kumar Agrawal 762

The Smartest Way to Learn Java5

Q: Is JavaScript and Java are same?

Ans: No, It is surprising that many programmer, including web designer are not understand the difference between the Java and JavaScript. JAVA is a product of sun microsystem which is a complete Object Oriented language. It is used for developing standalone application, applet etc. JavaScript is designed by Netscape, it is smaller and simple scripting language that doesn’t create any applets or standalone applications. In its most common form it resides inside the HTML(Hyper Text Markup Language) code. It don’t require any serever based CGI (Common Gateway Interface) programs.

Q: Why JVM is called Virtual Machine?

Ans: JVM stands for Java Virtual Machine, because there is no physical hardware require to interprete the Bytecodes. If you go through any Low Level Programming (Assembly) for any micro-processor then you can understand why we need real hardware to interprete the code. A micro processor has a bulletin set of instruction for interpreting the Assembly code. Similarly JVM is behaves like micro-processor in the sense it has its own set of instruction set but is implemented in software.

Q: Is there is any way to provide value to vector in the source code, analogous to array initializer?

Ans: The vector class constructors takes no arguments other than Collection, (since JDK1.2), which is abstract, and since a vector is a structure whose size can be change at runtime, it’s contents can only be initialized through member methods.

Q: What is JIT compiler?

Ans: It is a JVM compiler that compiles Java instructions(Bytecode) into native machine instruction at runtime and then uses this compiled code when the corresponding java code is needed this reduces the constant overhead of interpretation which was there in first generation JVM’s.

By: Amit Kumar Agrawal 763