0% found this document useful (0 votes)
319 views

Core Java

Computer is an electronic device that accepts data as input, processes it, stores the output and provides information to the user. There are different types of software like application software, system software, development software, distributed software, internet software and mobile applications. Programming languages are used to write programs which are a set of instructions that produce a desired output. Some key languages include C, C++, Java and Python.

Uploaded by

Steve Rogers
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
319 views

Core Java

Computer is an electronic device that accepts data as input, processes it, stores the output and provides information to the user. There are different types of software like application software, system software, development software, distributed software, internet software and mobile applications. Programming languages are used to write programs which are a set of instructions that produce a desired output. Some key languages include C, C++, Java and Python.

Uploaded by

Steve Rogers
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 648

Computer: Computer is an electronic device which is used to perform arithmetical and logical operations.

Or
Computer is an electronic device which accepts the data,processes it,stores it and gives the
output/information

Data: The collection of raw variables like numbers,characters and alpha numericals is called data.

Or
The collection of facts and figures is called data.

Hardware: The physical components of the computer which we can see,touch and feel is called hardware.

Software: A set of programs that executes on hardware

Types of Software

Application Software
System Software
Development Software
Languages
Packages
Databases
Relational Databases

Distributed Software
Internet Software
Mobile Applications
Wearable Software

C language

Languages: A language is one in which programs must be written to get the acquired result.

Program:
Group of statements arranged in an orderly fashion to get the acquired result is
called a program.
Depending on writing of a program languages are

1. Unstructured languages
2. Structured languages

An unstructured language is one in which every statement in a program


contains line number or label.

Ex: BASIC

10 begin
20 let a=30,b=20,c;
30 c=a+b;
40 goto 30:print c
50 end

A strucutured language is one in which the statments in a program


does not contain any line number or label.

Ex: C,C++

#include<stdio.h>
#include<conio.h>
main()
{
int a=30,b=20,c;
c=a+b;
printf("c=%d",c);
}
After writing a program we will error check it. Depending on error
checking languages are

1. Interpreter based languages: An interpreter based language is one in which


the interpretation stops wherever the error exists and it won't proceed for
the next statements until and unless we correct errors in that statement

Ex: BASIC

2. compiler based languages:


A compiler based language is one in which the
whole program will be compiled first and errors are shown at last.

Ex: C,C++

3. Psuedo compiler based languages: A psuedo compiler based language is ome which
some times acts as an interpreter and some times as a compiler

Ex: Visual Basic,Java

Generations of languages

1. Machine level
2. Low level
3. Middle level
4. High level
5. 5th Generatiion Languages or 5GL's
6. web languages

Basing on paradigm(Syntax) languages are again classified into

1. Procedural or function oriented


2. Object Oriented
3. Object Oriented web programming

Procedure Oriented Programming (POP)


1. Main program is divided into small parts depending on the functions.

2. The Different part of the program connects with each other by parameter passing & using operating system.

3. Every function contains different data.

4. Functions get more importance than data in program.

5. Most of the functions use global data.

6. Same data may be transfer from one function to another

7. There is no perfect way for data hiding.

8. Functions communicate with other functions maintaining as usual rules.

9. More data or functions can not be added with program if necessary. For this purpose full program need to be
change.

10. To add new data in program user should be ensure that function allows it.

11. Top down process is followed for program design.

12. Example: Pascal, Fortran

Object Oriented Programming (OOP): Object Oriented programming

1. Main program is divided into small object depending on the problem.

2. Functions of object linked with object using message passing.


3. Data & functions of each individual object act like a single unit.

4. Data gets more importance than functions in program.

5. Each object controls its own data.

6. Data does not possible transfer from one object to another.

7. Data hiding possible in OOP which prevent illegal access of function from outside of it. This is one of the best
advantages of OOP also.

8. One object link with other using the message passing.

9. More data or functions can be added with program if necessary. For this purpose full program need not to be
change.

10. Message passing ensure the permission of accessing member of an object from other object.

11. Bottom up process is followed for program design.

12. Example: C++, Java.

OOPS concepts in java

Java is a pure object oriented programming language. It is based on the concept of object. Java implements all the
features of object oriented programming like

1. Abstraction

2. Encapsulation

3. Polymorphism

4. Inheritance
5. Class

6. Objects

7. Methods

Object oriented programming provide a great flexibility, reusability, modularity and security to an application.

Data hiding is a very powerful feature. It provides security to various sensitive methods and variables.

Abstraction provides a way to hide the less essential properties so as to reduce complexity and increase efficiency.

Encapsulation is an information hiding and securing mechanism. It helps in restricting the access of data from the
outside entities it means only the methods in a class can access its member variables. Encapsulation reduces the
system complexity and increases robustness.

Polymorphism is a way to have more than one form of a method. In polymorphism, we use the method overloading
and method overriding techniques.

Inheritance is used to reduce the code and reuse the already available code. Here we extend a base class to a derived
class. The derived class then inherits the properties of its base class.

Class is a very essential entity in java. Every program in java has a class. Class is like a blueprint of an object. A
class contains member variables and methods.

Object is soul of object oriented programming. An object is an instance of its class. Object is used to access the
methods and variables in a class.

Methods are the operations that an object can perform. Methods define the behavior of an object.

All of the above object oriented programming concepts are widely used when we write java codes. OOPS concepts
are one of the reason for the power and success of java programming language.

JAVA

Java language developed by company “Sun Micro System” and creator is Jamesh Gosling. Sun micro System
Started by group of the students who are studding in Standard University. These peoples found the problem in their
room with electronic consumable remote. That means one electronic consumable control is not worked on another
electronics consumable. These people want to develop a common remote control which is controlling all the
electronic consumables so their contacted James Gosling and requested for the projects. Sun Micro System started
by group of students out of them one person also Indian whose name “Vinode Khosla”.

James Gosling and his team members given the project name as “Green” started in the year 1990 and common
remote control completed in the year 1992.

The James Gosling team develop a new language called as “OAK” But this name is already selected by some other
company renamed as Java but java has no meaning representation of Island in Indonesia. The unofficial
abbreviation of java is "Just another virtual analyzer" (JAVA).

Java technology is widely used currently. Let's start learning of java from basic questions like what is java, where it
is used, what type of applications are created in java and why use java?

What is Java?

Java is a programming language and a platform.

Platform Any hardware or software environment in which a program runs, known as a platform. Since Java has its
own Runtime Environment (JRE) and API, it is called platform.

Where it is used?

According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them
are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus etc.


2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

Types of Java Applications

There are mainly 4 type of applications that can be created using java:
1) Standalone Application

It is also known as desktop application or window-based application. An application that we need to install on
every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone
applications.

2) Web Application

An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet,
jsp, struts, jsf etc. technologies are used for creating web applications in java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications etc. It has the advantage of high level
security, load balancing and clustering. In java, EJB is used for creating enterprise applications.

4) Mobile Application

An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile
applications.

Java history is interesting to know. Java team members (also known as Green Team), initiated a revolutionary
task to develop a language for digital devices such as set-top boxes, televisions etc.

For the green team members, it was an advance concept at that time. But, it was suited for internet programming.
Later, Java technology as incorporated by Netscape.

James Gosling

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given
the major points that describes the history of java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Oak name for java language?


5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France,
Germany, Romania etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java name for java language?

7) Why they choosed java name for java language? The team gathered to choose a new name. The suggested
words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted something that reflected the
essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.

According to James Gosling "Java was one of the top choices along with Silk". Since java was so unique, most of
the team members preferred java.

8) Java is an island of Indonesia where first coffee was produced (called java coffee).

9) Notice that Java is just a name not an acronym.

10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation)
and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 released in(January 23, 1996).


Java Version History

Now a day 8 versions of java are released, which is listed below with realizing date.

 JDK Alpha and Beta (1995)

 JDK 1.0 (23rd Jan, 1996)

 JDK 1.1 (19th Feb, 1997)

 J2SE 1.2 (8th Dec, 1998)

 J2SE 1.3 (8th May, 2000)

 J2SE 1.4 (6th Feb, 2002)

 J2SE 5.0 (30th Sep, 2004)

 Java SE 6 (11th Dec, 2006)

 Java SE 7 (28th July, 2011)

 Java SE 8 (18th March, 2014)

Features Of Java
There is given many features of java. They are also known as java buzzwords.

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that incorporates
both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by
providing some rules.
Basic concepts of OOPs are:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Platform Independent
A platform is the hardware or software environment in which a program runs. There are two types of platforms
software-based and hardware-based. Java provides software-based platform. The Java platform differs from most
other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It
has two components:

Runtime Environment
API(Application Programming Interface)

java is platform independent Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS
etc. Java code is compiled by the compiler and converted into bytecode.This bytecode is a platform independent
code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
Secured
Java is secured because:

No explicit pointer
Programs run inside virtual machine sandbox.

how java is secured how java is secured


Classloader- adds security by separating the package for the classes of the local file system from those that are
imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access right to objects.
Security Manager- determines what resources a class can access such as reading and writing to the local disk.

These security are provided by java language. Some security can also be provided by application developer through
SSL,JAAS,cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security
problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism
in java. All these points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.

A Language or Technology is said to be Architectural neutral which can run on any available processors in the real

world without considering there architecture and vendor (providers) irrespect to its development and compilation.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a
compiled language (e.g., C++)

Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may
access files by calling the methods from any machine on the internet.
Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks
at once by defining multiple threads. The main advantage of multi-threading is that it shares the same memory.
Threads are important for multi-media, Web applications etc.
Feature C C++ Java
Procedural, OOP, Generic OOP, Generic Programming
Paradigms Procedural
Programming (from Java 5)
Form of Compiled Executable Native
Executable Native Code Java bytecode
Source Code Code
Memory Managed, using a garbage
Manual Manual
management collector
Yes, very commonly Yes, very commonly used, but some No pointers; references are used
Pointers
used. form of references available too. instead.
Preprocessor Yes Yes No
String Type Character arrays Character arrays, objects Objects
Complex Data Types Structures, unions Structures, unions, classes Classes
Single class inheritance, multiple
Inheritance N/A Multiple class inheritance
interface implementation
Operator
N/A Yes No
Overloading
Yes, with warnings if Yes, with warnings if loss could Not at all if loss could occur;
Automatic coercions
loss could occur occur msut cast explicitly
Variadic Parameters Yes Yes No
Goto Statement Yes Yes No
Difference between JDK, JRE and JVM
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because
configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:

Loads code
Verifies code
Executes code
Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

DK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
JVM Architecture

JVM (Java Virtual Machine) is a software. It is a specification that provides runtime environment in which java

bytecode can be executed.


Operation of JVM

JVM mainly performs following operations.

 Allocating sufficient memory space for the class properties.

 Provides runtime environment in which java bytecode can be executed

 Converting byte code instruction into machine level instruction.


JVM is separately available for every Operating System while installing java software so that JVM is platform

dependent.

Note: Java is platform Independent but JVM is platform dependent because every Operating system have different-

different JVM which is install along with JDK Software.

Class loader subsystem:

Class loader subsystem will load the .class file into java stack and later sufficient memory will be allocated for all the

properties of the java program into following five memory locations.

 Heap area

 Method area

 Java stack

 PC register
 Native stack

Heap area:

In which object references will be stored.

Method area

In which static variables non-static and static method will be stored.

Java Stack

In which all the non-static variable of class will be stored and whose address referred by object reference.

Pc Register

Which holds the address of next executable instruction that means that use the priority for the method in the

execution process?

Native Stack

Native stack holds the instruction of native code (other than java code) native stack depends on native library. Native

interface will access interface between native stack and native library.

Execution Engine

Which contains Interpreter and JIT compiler whenever any java program is executing at the first time interpreter will

comes into picture and it converts one by one byte code instruction into machine level instruction JIT compiler (just in

time compiler) will comes into picture from the second time onward if the same java program is executing and it gives

the machine level instruction to the process which are available in the buffer memory.

Note: The main aim of JIT compiler is to speed up the execution of java program.
Data Type

Datatype is a spacial keyword used to allocate sufficient memory space for the data, in other words Data type is

used for representing the data in main memory (RAM) of the computer.

In general every programming language is containing three categories of data types. They are

 Fundamental or primitive data types


 Derived data types

 User defined data types.

Primitive data types

Primitive data types are those whose variables allows us to store only one value but they never allows us to store

multiple values of same type. This is a data type whose variable can hold maximum one value at a time.
Example

int a; // valid
a=10; // valid
a=10, 20, 30; // invalid

Here "a" store only one value at a time because it is primitive type variable.

Derived data types

Derived data types are those whose variables allow us to store multiple values of same type. But they never allows

to store multiple values of different types. These are the data type whose variable can hold more than one value of

similar type. In general derived data type can be achieve using array.
Example

int a[] = {10,20,30}; // valid


int b[] = {100, 'A', "ABC"}; // invalid

Here derived data type store only same type of data at a time not store integer, character and string at same time.
User defined data types

User defined data types are those which are developed by programmers by making use of appropriate features of

the language.

User defined data types related variables allows us to store multiple values either of same type or different type or

both. This is a data type whose variable can hold more than one value of dissimilar type, in java it is achieved using

class concept.

Note: In java both derived and user defined data type combined name as reference data type.

In C language, user defined data types can be developed by using struct, union, enum etc. In java programming user

defined datatype can be developed by using the features of classes and interfaces.

Example

Student s = new Student();

In java we have eight data type which are organized in four groups. They are

 Integer category data types

 Character category data types

 Float category data types

 Boolean category data types

Integer category data types

These category data types are used for storing integer data in the main memory of computer by allocating sufficient

amount of memory space.

Integer category data types are divided into four types which are given in following table

Data Type Size Range


1 Byte 1 + 127 to -128
2 Short 2 + 32767 to -32768
3 Int 4 + x to - (x+1)
4 Long 8 + y to - (y+1)

Character category data types

A character is an identifier which is enclosed within single quotes. In java to represent character data, we use a data

type called char. This data type takes two byte since it follows Unicode character set.

Data Type Size(Byte) Range


Char 2 232767 to -32768

Why Java take 2 byte of memory for store character ?

Java support more than 18 international languages so java take 2 byte for characters, because for 18 international

language 1 byte of memory is not sufficient for storing all characters and symbols present in 18 languages. Java

supports Unicode but c support ascii code. In ascii code only English language are present, so for storing all English

latter and symbols 1 byte is sufficient. Unicode character set is one which contains all the characters which are

available in 18 international languages and it contains 65536 characters

Float category data types

Float category data type are used for representing float values. This category contains two data types, they are in the

given table

Data Type Size Range Number of decimal places


Float 4 +2147483647 to -2147483648 8
Double 8 + 9.223*1018 16

Boolean category data types

Boolean category data type is used for representing or storing logical values is true or false. In java programming to

represent Boolean values or logical values, we use a data type calledBoolean.


Why Boolean data types take zero byte of memory ?

Boolean data type takes zero bytes of main memory space because Boolean data type of java implemented by Sun

Micro System with a concept of flip - flop. A flip - flop is a general purpose register which stores one bit of information

(one true and zero false).

Note: In C, C++ (Turbo) Boolean data type is not available for representing true false values but a true value can

be treated as non-zero value and false values can be represented by zero


Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

ata Conversion

In java programming we have six data conversion technique they are:.

1 Converting numeric string type data into numerical / fundamental type values

In order to convert numerical string into numerical or fundamental values we use the following generalized

predefined method which is present in wrapper classes.

Here xxx represent any fundamental data type.

Example:
String s1="100";
int x=Integer.parseInt(s1);

Example:

String s2="100.75f";
Float y=Float.parseFloat(s2);

2 Converting numeric / fundamental type values into string type values

In order to convert numeric / fundamental type values into string values, we use the following predefined static

overloaded method.

Here XXX represent any fundamental data type values

Example:

int a=10;
3 Converting fundamental type values into object type values:

In order to convert the fundamental data into equivalent wrapper class object type data we use the following

generalized predefined parameterized constructor by taking fundamental data type as a parameter.

Example:
in JDK 1.4 converting fundamental data type values into wrapper class object is known as boxing. In the case of JDK

1.5 and in higher version it is optional to the java programmer to convert fundamental data type value into

equivalent wrapper class object. That is implicitly taken care by JVM and it is known as auto boxing.

Definition of auto boxing

The process of implicitly converting fundamental type value into equivalent wrapper class object is known as auto

boxing.
4 Converting object type value into fundamental type value:

In order to convert wrapper class object data into fundamental type data, we use the following predefined instance

method present in each and every wrapper class.

In case of JDK 1.5 and in higher version it is optional to the java programmer to convert object data into fundamental

type data and this process is known as auto un-boxing and its takes care by JVM.

Definition of auto un-boxing

In process of implicitly conversion objects type data into fundamental type data is known as auto un-boxing.
5 Converting String type data into object type data

In order to convert String type numeric data into equivalent wrapper class object, we use the following predefined

parameterized constructor by each and every wrapper class except character class.

6 Converting wrapper class object type data into String type data

To convert wrapper class object type data into string type data we use the following generalized predefined instant

method which is present each and every wrapper class.


Example

int a=10;

 String is=String.valueOf(a);

 Integer io=new Integer(is);

 int x=io.intValue();

 Integer io=new Integer(n);

 String so=io.toString();

 int x=Integer.parseInt(so);
Boxing and Unboxing

Definition of auto boxing

The process of implicitly converting fundamental type value into equivalent wrapper class object is known as auto

boxing.

Converting fundamental type values into object type values:

In order to convert the fundamental data into equivalent wrapper class object type data we use the following

generalized predefined parameterized constructor by taking fundamental data type as a parameter.

Example:
in JDK 1.4 converting fundamental data type values into wrapper class object is known as boxing. In the case of JDK

1.5 and in higher version it is optional to the java programmer to convert fundamental data type value into equivalent

wrapper class object. That is implicitly taken care by JVM and it is known as auto boxing.

Definition of auto Unboxing.

In process of implicitly conversion objects type data into fundamental type data is known as auto un-boxing.
Converting object type value into fundamental type value:

In order to convert wrapper class object data into fundamental type data, we use the following predefined instance

method present in each and every wrapper class.

In case of JDK 1.5 and in higher version it is optional to the java programmer to convert object data into fundamental

type data and this process is known as auto un-boxing and its takes care by JVM.
Variable

Variable is an identifier which holds data or another one variable is an identifier whose value can be changed at the

execution time of program. Variable is an identifier which can be used to identify input data in a program.

Syntax

Variable_name = value;

Rules to declare a Variable

 Every variable name should start with either alphabets or underscore ( _ ) or dollar ( $ ) symbol.

 No space are allowed in the variable declarations.

 Except underscore ( _ ) no special symbol are allowed in the middle of variable declaration

 Variable name always should exist in the left hand side of assignment operators.

 Maximum length of variable is 64 characters.

 No keywords should access variable name.

Variable declarations

In which sufficient memory will be allocated and holds default values.


Syntax

Datatype variable_name;
byte b1;

Variable initialization

It is the process of storing user defined values at the time of allocation of memory space.

Variable assignment

Value is assigned to a variable if that is already declared or initialized.

Syntax

Variable_Name = value
int a = 100;
Syntax

int a= 100;
int b;
b = 25; // ------> direct assigned variable
b = a; // ------> assigned value in term of variable
b = a+15; // ------> assigned value as term of expression

Operators

Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation. Java

supports following lists of operators.

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Ternary or Conditional Operators


Arithmetic Operators

Given table shows all the Arithmetic operator supported by Java Language. Lets suppose variable A hold 8

and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0

Relational Operators

Which can be used to check the Condition, it always return true or false. Lets suppose variable A hold 8 and B hold

3.
Operators Example (int A=8, B=3) Result
< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
!= A!=(-4) True

Logical Operator

Which can be used to combine more than one Condition?. Suppose you want to combined two

conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here &&is Logical

Operator.
Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True
Truth table of Logical Operator

C1 C2 C1 && C2 C1 || C2 !C1 !C2


T T T T F F
T F F T F T
F T F T T F
F F F F T T

Assignment operators

Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
=a=b Value of b will be assigned to a

Ternary operator

If any operator is used on three operands or variable is known as ternary operator. It can be represented with " ?: "

Ternary operator Read in detailRead in detail

Java Environment Setup

Path

Path variable is set for providing path for all java tools like java, javac, javap, javah, jar, appletviewer which are use in

java programming. These all tools are available in bin folders so we set path upto bin folders.
classpath

classpath variable is set for providing path of all java classes which is used in our application. All classes are

available in lib/rt.jar so we set classpath upto lib/rt.jar.

Java Folder Hierarchy

Why set path ?

The following programming error is general for all java programmers when they compile any java program.

'javac' is not recognized as an internal or external command, operable program or batch file.

When you get this type of error, then your operating system cannot find the java compiler (javac). To solve this error

you need to set the PATH variable.


Javac is a tool which is available in bin folder so you must set the PATH upto bin folder. In a binfolder all tools are

available like javap, javah, jar, javac, java, appletviewer etc. These all tools are used for different-different

purpose.

set the path and classpath

Go on my computer icon and right click, after that click on properties option.


Now click on advance setting

Click on advance
Click on Advance variables
Click on new button which is below the first box.
Now one dilog box is appear, now ignore this but do not close.

Now open my computer open c:/ > Programs Files > java > java1.6.0 > bin copy this path
Now come back on previous open dilogbox and write variable name 'path' and for variable value paste all copied

path upto bin folder. Put .; at the end. It (.) select all the tools from bin folder.
Now open my computer open c:/ > Programs Files > java > java1.6.0 > jre > lib > rt.jar copy this path

Note: rt.jar is available in lib folder this jar files contains all classes of jdk.

Now again come back on Environment variable dilogbox and click on new. now one box is open and write path

variable as 'classpath' and for variable value paste all copied path upto rt.jar. Put .; at the end. It (.) select all the

classes from lib folder.


Note: Finally after set classpath Restart your system, or you can re-open command prompt.
Difference between Path and Classpath

Path

Path variable is set for provide path for all java tools like java, javac, javap, javah, jar, appletviewer which are use at

the time of java programming like for run java any program we use java tool and for compile java code use javac tool.

These all tools are available in bin folder so we set path upto bin folder.

classpath

classpath variable is set for provide path of all java classes which is used in our application. All classes are available

in lib/rt.jar so we set classpath upto lib/rt.jar.

Java Folder Hierarchy


Difference between Path and ClassPath

Path variable is set for use all the tools like java, javac, javap, javah, jar, appletviewer etc.

Example

"C:\Program Files\Java\jdk1.6.0\bin"

All the tools are present in bin folder so we set path upto bin folder.

Classpath variable is used for set the path for all classes which is used in our program so we set classpath upto

rj.jar. in rt.jar file all the .class files are present. When we decompressed rt.jar file we get all .class files.
Example

"C:\Program Files\Java\jre1.6.0\jre\lib\rt.jar"

In above rt.jar is a jar file where all the .class files are present so we set the classpath upto rt.jar.
class classname
{
public static void main(String[]args)
{
Statement-1;
Statement-2;
:
:
:
Statement-n;
}
As java is a pure Object Oriented programming Languge
everything in java must be under a class.

public
* The keyword public indicates that the method can be

called by any object.

static
* The keyword static indicates that the method is a class

method, which can be called without the requirement to

instantiate an object of the class. This is used by the Java

interpreter to launch the program by invoking the main method


of the class identified in the command to start the program.

void
* The keyword void indicates that the method doesn’t

return any value.

args
* The formal parameter args is an array of type String,

which contains arguments entered at the command line. Note

that the args parameter must be specified whether or not the

user is required to enter a command-line argument and whether

or not the code in – Write the method signature for the main

method in a Java application.

main() method is starting execution block of a java program or any java program start their execution from main

method. If any class contain main() method known as main class.

Syntax of main() method:

Syntax

public static void main(String args[])


{
.......
.......
}
Public

public is a keyword in a java language whenever if it is preceded by main() method the scope is available anywhere

in the java environment that means main() method can be executed from anywhere. main() method must be

accessed by every java programmer and hence whose access specifier must be public.

Static

static is a keyword in java if it is preceded by any class properties for that memory is allocated only once in the

program. Static method are executed only once in the program. main() method of java executes only once

throughout the java program execution and hence it declare must be static.

Void

void is a special datatype also known as no return type, whenever it is preceded by main() method that will be never

return any value to the operating system. main() method of java is not returning any value and hence its return type

must be void.

String args[]

String args[] is a String array used to hold command line arguments in the form of String values.

In case of main() method following changes are acceptable

1. We can declare String[] in any valid form.

 String[] args

 String args[]

 String []args

2. Instance of String[] we can take var-arg String parameter is String...

Syntax

main(String[] args) --> main(String... args)


3. We can change the order of modifiers i.e Instead of

Syntax

public static we can take static public

4. Instead of args we can take any valid java identifier.

Syntax

public static void main(String a[])

We can overload main() method ?

Yes, We can overload main() method. A Java class can have any number of main() methods. But run the java

program, which class should have main() method with signature as "public static void main(String[] args). If you

do any modification to this signature, compilation will be successful. But, not run the java program. we will get the run

time error as main method not found.

Example of override main() method


Example

public class mainclass


{
public static void main(String[] args)
{
System.out.println("Execution starts from Main()");
}
void main(int args)
{
System.out.println("Override main()");
}
double main(int i, double d)
{
System.out.println("Override main()");
return d;
}
}

Output

Execution starts from Main()

Java Naming conventions

Naming Conversion of Java

Sun micro system was given following conversions by declaring class, variable, method etc. So that it is highly

recommended to follow this conversion while writing real time code.

Why Using naming Conversion

Different Java programmers can have different styles and approaches to write program. By using standard Java

naming conventions they make their code easier to read for themselves and for other programmers. Readability of

Java code is important because it means less time is spent trying to figure out what the code does, and leaving more

time to fix or modify it.

1. Every package name should exist a lower case latter.

Example

package student; // creating package

import java.lang; // import package

2. First letter of every word of class name or interface name should exists in upper case.
Example

class StudentDetails
{
.....
.....
}
interface FacultyDetail
{
.....
.....
}

3. Every constant value should exists in upper case latter. It is containing more than one word than it should be

separated with underscore (-).

Example

class Student
{
final String COLLEGE_NAME="abcd";
....
....
}

Note: if any variable is preceded by final keyword is known as constant value.


Example

class Student
{
Final String Student_name="abcd";
}

While declaring variable name, method, object reference the first letter of first word should be exits in lower case but

from the second words onward the first letter should exists in upper case.
Example

class Student
{
String StudentName="xyz";
void instantStudentDetails();
{
....
....
}
Student final

CamelCase in java naming conventions

Java follows camelcase syntax for naming the class, interface, method and variable According to CamelCase if

name is combined with two words, second word will start with uppercase letter always. General Example

studentName, customerAccount. In term of java programming e.g. actionPerformed(), firstName, ActionEvent,

ActionListener etc.

Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
press windowskey+r
type cmd
press enter

type e:
press enter

md [directoryname]

Ex: md myjavapro

cd [directoryname]

Ex: cd myjavapro

Programming

notepad <filename.java>

ex: notepad Test1.java

class Test1
{
public static void main(String[]args)
{
System.out.print("Welcome to Java");
}
}

press ctrl+s
press alt+tab

Compiling java code


javac Test1.java

Execution

java Test1

Note: The filename and the class name must be the same.

Note:

In the above example

System : is the class


out : is the object
print : is the method/function
Steps For compile Java Program

 First Save Java program with same as class name with .java extension. 
Example: Sum.java
 Compile: javac Filename.java 
Example, javac Sum.java
Note: Here javac is tools or application programs or exe files which is used for Compile the Java program.

Steps For Run Java Program

 For run java program use java tool.


 Run by: java Filename 
Example: java sum
Note: Here java is tools or application programs or exe files which is used for run the Java program.

Steps For compiling and executing the java program

The following sequence of steps represented in the diagram use compiling the java program and executing the java

programs.

In the above diagram javac and java are called tools or application programs or exe files developed by sun micro

system and supply as a part of jdk 1.5/1.6/1.7 in bin folder (starting directory of java is called java home directory).
Internal Details of Hello Java Program
What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java code
into bytecode.

What happens at runtime?


At runtime, following steps are performed:
Classloader: is the subsystem of JVM that is used to load class files.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
Interpreter: read bytecode stream then execute the instructions.

Q)Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:
To compile: javac Hard.java
To execute: java Simple

Q)Can you have multiple classes in a java source file?


Yes, like the figure given below illustrates:
class Test2
{
public static void main(String[] args)
{
System.out.print("I Like Java");
System.out.print("I Like Android");
}
}

class Test2
{
public static void main(String[] args)
{
System.out.println("I Like Java");
System.out.println("I Like Android");
}
}
class Test3
{
public static void main(String[]args)
{
int a=20;
System.out.println("a="+a);
}
}

class Test3
{
public static void main(String[]args)
{
int a=20,b=10;
System.out.println("a="+a);
System.out.println("b="+b);
}
}

class Test3
{
public static void main(String[]args)
{
int a=20,b=10,c;
c=a+b;
System.out.println("C="+c);
}
}

class Test3
{
public static void main(String[]args)
{
int a=20,b=10;
System.out.println("C="+(a+b));
}
}

+ addition
- subtraction
* multiplication
/ division
% modulus

wrapper method: A method that acts as a middle-man between a caller and a helper method, often offering an
interface that is cleaner than the helper method’s.

wrapper class: One of the Java classes, like Double and Integer that provide objects to contain primitive types, and
methods that operate on primitives.
Wrapper classes wrap the primitive data types to objects of that class. In Java there are eight primitive data types
and each data type has the corresponding wrapper class. These wrapper classes belongs to the java.lang package. In
Java the wrapper classes are required to allow the null values because objects can be null whereas, the primitives
can't. Wrapper classes are used in to include the values in Collection, it is required for type safety. It is required
when treating the primitives values as an object with other objects. The table given below lists the primitive data
types and its respective wrapper class :

Primitive Data Type Wrapper Class


boolean Boolean
byte Byte
char Character
int Integer
float Float
double Double
long Long
short Short
Almost all of each wrapper class has the parseXXX(), toString(), xxxxValue() etc. Below we are discussing some
of the methods of java.lang.Integer class but, these methods are usually applies on almost all wrapper classes.

Method Name Method Description


This method is used to parse the String representation of number to signed decimal
parseInt(String s) integer.
Syntax : public static int parseInt(String s) throws NumberFormatException
This method is used to represent an Integer value to a String object.
toString()
Syntax : public String toString()
This method is used to represent the value of String as an Integer object.
valueOf(String s)
Syntax : public static Integer valueOf(String s) throws NumberFormatException
This method is used to compare the object with the specified object whether they are
equals(Object obj) equals or not.
Syntax : public boolean equals(Object obj)
This method is used to find the hash code of the Integer.
hashCode()
Syntax : public int hashCode()
This method is used to compare two Integers. It returns 0 (zero) if the values are equal,
returns negative value if the specified object value is greater than the invoking object
compareTo(Integer
vlaue, returns positive value if the specified object value is lower than the invoking object
anotherInteger)
value.
Syntax : public int compareTo(Integer anotherInteger)
This method is used to compare the Integer object to another object.
compareTo(Object o)
Syntax : public int compareTo(Object o)
Import Statements

Import is a keyword in java language used to import the predefined properties of java API into current working java

program.

Syntax

import package1.package2.......*;

Used to import all the predefined properties of given package.

Syntax

import pack1.package2.............Class_Name/Interface_Name;
Used to import specific class or interface in a java program.

Java API is a collection of package, package is a container which is collection of predefined classes and interfaces.

Note: Import statement should be the first statement of the java programs.

import java.io.*;
class Test4
{
public static void main(String[]args) throws IOException
{
InputStreamReader I=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(I);
int age;
System.out.print("Enter Your Age..:");
age=Integer.parseInt(br.readLine());
System.out.println("Your Age="+age);
}
}

import java.io.*;
class Test4
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));
int age;
System.out.print("Enter Your Age..:");
age=Integer.parseInt(br.readLine());
System.out.println("Your Age="+age);
}
}

import java.io.*;
class Test4
{
public static void main(String[]args) throws IOException
{
DataInputStream d=new DataInputStream(System.in);
int age;
System.out.print("Enter Your Age..:");
age=Integer.parseInt(d.readLine());
System.out.println("Your Age="+age);
}
}

import java.util.*;
class Test4
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int age;
System.out.print("Enter Your Age..:");
age=sc.nextInt();
System.out.println("Your Age="+age);
}
}

import java.lang.*;
import java.io.*;
class Test5
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

int eno;
String ename;
double esal;

System.out.print("Enter Eno..:");
eno=Integer.parseInt(br.readLine());

System.out.print("Enter Ename..:");
ename=br.readLine();

System.out.print("Enter Esal..:");
esal=Double.parseDouble(br.readLine());
System.out.println("Eno="+eno);
System.out.println("Ename="+ename);
System.out.println("Esal="+esal);
}
}

Scanner Class

Java Scanner Class

Scanner is one of the predefined class which is used for reading the data dynamically from the keyboard.

Import Scanner class

Syntax

java.util.Scanner

Constructor of Scanner Class

Scanner(InputStream)

This constructor create an object of Scanner class by talking an object of InputStream class. An object of

InputStream class called in is created as a static data member in the System class.

Example

Scanner sc=new Scanner(System.in);

Here the object 'in' use the control of keyboard


Instance methods of Scanner Class

 public byte nextByte()

 public short nextShort()

 public int nextInt()

 public long nextLong()

 public long nextLong()

 public double nextDouble()

 public char nextChar()

 public boolean nextBoolean()

 public String nextLine()

Method 1 to 8 are used for reading fundamental values from the keyboard. Method 9 (public String nextLine() ) is

used for reading any kind of data in the form of String data.

For Remember all above methods

From method 1 to 8 combindly we represent as public xxx nextxxx(). Here xxx represents any fundamental data

type. These methods are used for reading the fundamental data from keyboard.
Accept two values dynamically from the keyboard and compute sum.
Example

import java.util.Scanner
public class ScannerDemo
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter first no= ");
int num1=s.nextInt();
System.out.println("Enter second no= ");
int num2=s.nextInt();
System.out.println("Sum of no is= "+(num1+num2));
}
}

Output

Enter first no=4

Enter second no=5

Sum of no is=9

Program which is accept two number as a string and compute their sum.
Example

import java.util.Scanner;
class Dataread
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter first number: ");
String s1=s.nextLine();
System.out.println("Enter second number: ");
String s2=s.nextLine();
int res=Integer.parseInt(s1) + Integer.parseInt(s2);
System.out.println("Sum= "+res);
}
}

Output

Enter first number: 5

Enter second number: 6

Sum= 11

Write a java program which will accept two values dynamically from the keyboard and
compute sum.
import java.util.Scanner
public class ScannerDemo
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter first no= ");
int num1=s.nextInt();
System.out.println("Enter second no= ");
int num2=s.nextInt();
System.out.println("Sum of no is= "+(num1+num2));
}
}

Output

Enter first no=4


Enter second no=5
Sum of no is=9

import java.util.*;
class Test6
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter any character");
String str=sc.next();//Inputs String
char ch=str.charAt(0);
System.out.print("Entered Character="+ch);
}
}

import java.lang.*;
import java.io.*;
import java.util.*;
class Test6
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

Scanner sc=new Scanner(System.in);


int eno;
String ename;
double esal;
System.out.print("Enter Eno..:");
eno=Integer.parseInt(br.readLine());

System.out.print("Enter Ename..:");
ename=br.readLine();

System.out.print("Enter Esal..:");
esal=Double.parseDouble(br.readLine());

System.out.print("Enter Egrade..:");
String tegrade=sc.next();
char egrade=tegrade.charAt(0);
System.out.println("Eno="+eno);
System.out.println("Ename="+ename);
System.out.println("Esal="+esal);
System.out.println("Egrade="+egrade);
}
}

Conditional statements
Conditional statements are those which are used to
check the condition and return a statement when the
condition is true otherwise nothing will be executed.

if(condition)
{
statment;
}
The statement under if will be executed when the
condition at if is true otherwise nothing will
be executed.

import java.io.*;
import java.lang.*;
class Test7
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

int a,b;

System.out.print("Enter a..:");
a=Integer.parseInt(br.readLine());

System.out.print("Enter b..:");
b=Integer.parseInt(br.readLine());
if(a>b)
{
System.out.println("a is big");
}
}
}

if else

if(condition)
{
statement;
}
else
{
statement;
}

The statement under if will be executed when


the condition at if is true otherwise the statement under
else will be executed.

import java.io.*;
import java.lang.*;
class Test7
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

int a,b;

System.out.print("Enter a..:");
a=Integer.parseInt(br.readLine());

System.out.print("Enter b..:");
b=Integer.parseInt(br.readLine());
if(a>b)
{
System.out.println("a is big");
}
else
{
System.out.println("b is big");
}
}
}

if(condition)
{
statement;
}
else if(condition)
{
statement;
}

The statement under if will be executed when


the condition at if is true otherwise condition at
else if will be checked then the statement under
else if will be executed.

import java.io.*;
import java.lang.*;
class Test7
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

int a,b;

System.out.print("Enter a..:");
a=Integer.parseInt(br.readLine());

System.out.print("Enter b..:");
b=Integer.parseInt(br.readLine());
if(a>b)
{
System.out.println("a is big");
}
else if(a<b)
{
System.out.println("b is big");
}
}
}
if(condition)
{
statement;
}
else if(condition)
{
statement;
}
else if(condition)
{
statement;
}
else if(condition)
{
statement;
}

import java.io.*;
import java.lang.*;
class Test7
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

int a,b;

System.out.print("Enter a..:");
a=Integer.parseInt(br.readLine());

System.out.print("Enter b..:");
b=Integer.parseInt(br.readLine());
if(a>b)
{
System.out.println("a is big");
}
else if(a<b)
{
System.out.println("b is big");
}
else if(a==b)
{
System.out.println("both are equal");
}
}
}

import java.io.*;
import java.lang.*;
class Test7
{
public static void main(String[]args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

int a,b,c;

System.out.print("Enter a..:");
a=Integer.parseInt(br.readLine());

System.out.print("Enter b..:");
b=Integer.parseInt(br.readLine());

System.out.print("Enter c..:");
c=Integer.parseInt(br.readLine());

if(a>b && a>c)


{
System.out.println("a is big");
}
else if(b>c)
{
System.out.println("b is big");
}
else
{
System.out.println("c is big");
}
}
}
Ternary Operator

If any operator is used on three operands or variable is known as Ternary Operator. It can be
represented with ? : . It is also called as conditional operator

Advantage of Ternary Operator

Using Ternary Operator reduce the number of line codes and improve the performance of
application.

Syntax

expression-1 ? expression-2 : expression-3

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value or variable or statement or any mathematical expression. If condition will be true expression-
2 will be execute otherwise expression-3 will be executed.

Syntax

a<b ? printf("a is less") : printf("a is greater");


Flow Diagram

Find largest number among 3 numbers using ternary operator

Loops:
Loops are used to execute a statement repeatedly until
the given condition is satisfied.

for loop:
A for loop is used when we know how many times the
loop should be repeated.
for(initialization expression;test expression;incrementation expression)
{
statement;
}

class Test4
{
public static void main(String[]args)
{
int i;
for(i=1;i<=10;i++)
{
System.out.print("\t"+i);
}
}
}

for(;;)
A for loop is used when we know how many times the loop should be repeated
but some times we don't know how many times the loop should be repeated
at this for(;;) is used.

import java.util.*;
import java.io.*;
class Test9 {
public static void main(String[] args)
{
char ch;
Scanner sc=new Scanner(System.in);
for(;;)
{
String str=sc.next();
ch=str.charAt(0);//Inputs String
if(ch=='Z')
break;
}
}
}

while loop:
A while loop is called concise format of the for loop because
a while loop contains only test expression with in it.

while(expression)
{
statement;
}

class Test7
{
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
System.out.println("\t"+i);
i++;
}
}
}

do while loop:
In a while loop the condition is evaluated at the beginning of
the loop but in do while loop the condition is evaluated at the
end of the loop that is the statements will be executed atleast
once whether the condition is true or false.

class Test7
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println("\t"+i);
i++;
}while(i<=10);
}
}

import java.util.*;
import java.io.*;
class CharScan {
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b,c;
char ch;
Scanner sc=new Scanner(System.in);
do {
System.out.print("Enter a..:");
a=Integer.parseInt(br.readLine());

System.out.print("Enter b..:");
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println("c="+c);

System.out.println("Want to Sum More(Y/N)...:");


String str=sc.next();
ch=str.charAt(0);//Inputs String
}while(ch=='y' || ch=='Y');
}
}
switch case

Used to select only one option from the n number of options available.

switch(expression)
{
case 1:
statement;
break;

case 2:
statement;
break;

case 3:
statement;
break;

:
:
:
:
default:
statement;
}

The statement under default will be executed when an invalid


switch is pressed,

import java.io.*;
class Test8
{
public static void main(String[]args) throws IOException
{
InputStreamReader I=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(I);
int i;
System.out.println("************************");
System.out.println("MENU");
System.out.println("************************");
System.out.println("1. Chocolate");
System.out.println("2. Vanilla");
System.out.println("3. ButterScotch");
System.out.println("4. Exit");
System.out.println("************************");
System.out.println("Enter Your Choice..(1-4)..:");
i=Integer.parseInt(br.readLine());
switch(i)
{
case 1:
System.out.println("Chocolate Selected");
break;

case 2:
System.out.println("Vanilla Selected");
break;

case 3:
System.out.println("ButterScotch Selected");
break;

case 4:
System.out.println("U Didn't Selected Any Thing");
break;

default:
System.out.println("No Item");
}
}
}

class Test1
{
public static void main(String[]args)
{
int i;
for(i=1;i<=20;i++)
{
if(i>15)
break;
System.out.println(i);
}
}
}

class Test10
{
public static void main(String[]args)
{
int i;
for(i=1;i<=10;i++)
{
if(i%2==0)
continue;
System.out.println(i);
}
}
}
There is no goto statement in java.

Java break statement with label example


/*

  Java break statement with label example.

  This example shows how to use java break statement to terminate the labeled loop.

  The following example uses break to terminate the labeled loop while searching two

  dimensional int array.

*/

public class JavaBreakWithLableExample {

  public static void main(String[] args) {

  

  

    int[][] intArray = new int[][]{{1,2,3,4,5},{10,20,30,40,50}};

    boolean blnFound = false;


  

    System.out.println("Searching 30 in two dimensional int array..");

  

    Outer:

    for(int intOuter=0; intOuter < intArray.length ; intOuter++)

  {

      Inner:

      for(int intInner=0; intInner < intArray[intOuter].length; intInner++)

   {

        if(intArray[intOuter][intInner] == 30)

    {

          blnFound = true;

          break Outer;

    } 

    

   }

  }

  

    if(blnFound == true)

      System.out.println("30 found in the array");

    else

      System.out.println("30 not found in the array");

 }
}

public class JavaContinueWithLabelExample {


 
  public static void main(String[] args) {
  
    int intArray[][] = new int[][]{{1,2},{2,3}};
  
    Outer:
    for(int i=0; i < intArray.length; i++)
  {
      for(int j=0; j < intArray[i].length ; j++)
   {
        if(intArray[i][j] == 3)
          continue Outer;
        System.out.println("Element is : " + intArray[i][j]);
   }
  }
   
 }
}

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

    OuterLoop: for (int i = 2;; i++) {
      for (int j = 2; j < i; j++) {
        if (i % j == 0) {
          continue OuterLoop;
        }
      }
      System.out.println(i);
      if (i == 37) {
        break OuterLoop;
      }
    }
  }
}

public class MainClass {
  public static void main(String[] args) {
    int limit = 20;
    int factorial = 1;

    OuterLoop: for (int i = 1; i <= limit; i++) {
      factorial = 1;
      for (int j = 2; j <= i; j++) {
        if (i > 10 && i % 2 == 1) {
          continue OuterLoop;
        }
        factorial *= j;
      }
      System.out.println(i + "! is " + factorial);
    }
  }
}

public class MainClass {
  public static void main(String[] args) {
    int nValues = 50;

    OuterLoop: for (int i = 2; i <= nValues; i++) {
      for (int j = 2; j < i; j++) {
        if (i % j == 0) {
          continue OuterLoop;
        }
      }
      System.out.println(i);
    }
  }
}

public class BreakContinueExample {


 
    public static void main(String args[]) {
   
        int[] numbers= new int[]{1,2,3,4,5,6,7,8,9,10};
     
        //calculate sum of all numbers till 5 appears
        int sum = 0;
        for(int i=0; i< numbers.length; i++){
            System.out.println("Executing for loop with iteration number: " + i);
            if(i == 5){
                System.out.println("calling break statement to break for loop");
                break;
            }
            if(i%2 != 0){
                sum = sum + i;
                System.out.println("calling continue statement to start new iteration");
                continue;
            }
            System.out.println("Last line of loop, not executing for odd numbers due
                               to continue statement i: " + i);
        }
        System.out.println("Outside of for loop, sum: " + sum);
    }
}

public class BreakContinueWithLabel {


 
    public static void main(String args[]) {
   
        int[] numbers= new int[]{100,18,21,30};
     
        //Outer loop checks if number is multiple of 2
        OUTER:  //outer label
        for(int i = 0; i<numbers.length; i++){
            if(i % 2 == 0){
                System.out.println("Odd number: " + i + ", continue from OUTER label");
                continue OUTER;
            }
         
            INNER:
            for(int j = 0; j<numbers.length; j++){
                System.out.println("Even number: " + i + ", break  from INNER label");
                break INNER;
            }
        }
     
    }
}

import java.util.Scanner;

class group{
public static void main(String arng[]){
int num, i,sum=0;
//go:
{
Scanner data = new Scanner(System.in);
System.out.println("Enter a number");
num=data.nextInt();
for(i=0;i<100;i++)
{
sum=sum+i;
//if(i==num)
//break go;
}
}
System.out.println("Sum of numbers:"+sum);
}
}

command Line Arguments


Command line arguments

If any input value is passed through command prompt at the time of running of program is known as command line
argument by default every command line argument will be treated as string value and those are stored in string
array of main().

Syntax:

Javac Mainclass.java
Java Mainclass value1 value2 value3 ....................
Example:

E:/>porter>java SumDemo 10 20

When the above statement is executing the following sequence of steps will take place.

1. Class loader sub-system loads SumDemo along with CMD line argument(10, 20) and in main memory.
2. JVM take the loaded class SumDemo along with CMD line arguments (10, 20) and place the number of
values in the length variable that is 2.
3. JVM looks for main() that is JVM will place the CMD in the main() in the form of string class that is.

Hence all the CMD line arguments of java are sending to main() method available in the form of array of
object of String class (every CMD are available or stored in main method in the form of array of object of
String class).

4. JVM calls the main() method with respect to loaded class SumDemo that is SumDemo.main().
Note:Sun Micro System has withdrawn the decision to providing 8 main() method by taking and fundamental
arrays (int i[], float[] etc) because of following reasons.

 Every time writing 8 main() methods in every java program is complex and time consuming.
 Java programming don’t want to treated the command line arguments as fundamental arrays byte they want
to treat every command line arguments as array of object of String class “main() takes the fundamental
arrays as array of object of String class”.

public class Ag{

public static void main(String args[])

int n1 = Integer.parseInt(args[0]);

int n2 = Integer.parseInt(args[1]);

int n3 = Integer.parseInt(args[2]);

int n4=n1+n2+n3;

double avg = ((double) (n1+n2+n3))/3.0;

System.out.println("The Total is:"+n4);

System.out.println("The average is: " + avg);

A java program which will accept command line arguments and display there values.

class CmdPrint
{
public static void main(String k[])
{
System.out.println("no of arguments ="+k.length);
for(int i=0;i< k.length;i++)
{
System.out.println(k[i]);
}
}
}

Note: Except + operator any numeric operation not allowed in command line arguments.

A java program to find square of a number by reading input value from command prompt.

class A
{
int no, result;
void square(String s)
{
int no=Integer.parseInt(s);
result=no*no;
System.out.println(result);
}
}
class M
{
public static void main(String args[])
{
System.out.println("no of arguments ="+args.length);
A oa=new A();
oa.square(args[0]);
}
}

class Test1
{
public static void main(String args[])
{
int a,b,c,d;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
d=a+b+c;
System.out.println("d="+d);
}
}

java Test1.java

java Test1 5 5 5
class Test1
{
public static void main(String args[])
{
int eno;
String ename;
double esal;
String egrade;
eno=Integer.parseInt(args[0]);
ename=(args[1]);
esal=Double.parseDouble(args[2]);
egrade=(args[3]);
System.out.println("eno="+eno);
System.out.println("ename="+ename);
System.out.println("esal="+esal);
System.out.println("egrade="+egrade);
}
}
Array:

Array In Java

Array is a collection of similar type of data. An array is an indexed collection of fixed number of homogeneous data

elements.

Advantage of Array

The main advantage of array is we can represent multiple value under the same name.

Code Optimization: No, need to declare a lot of variable of same type data, We can retrieve and short data easily.

Random access: We can retrieve any data from array with the help of index value.

Disadvantage of Array

The main limitation of array is Size Limit when once we declare array there is no chance to increase and decrease

the size of array according to our requirement, Hence memory point ofview array concept is not recommended to

use. To over come this limitation in java introduce collection concept.

Types of Array

There are two types of array in java.

 Single Dimensional Array


 Multidimensional Array

Array Declaration

Single dimension array declaration.

Syntax

1. int[] a;

2. int a[];

3. int []a;

Note: At the time of array declaration we can not specify the size of array. For Example int[5] a; this is wrong.

2D Array declaration.

Syntax

1. int[][] a;

2. int a[][];

3. int [][]a;

4. int[] a[];

5. int[] []a;

6. int []a[];

Array creation

Every array in a java is an object,Hence we can create array by using new keyword.

Note:

1) At the time of array creation we must be specify the size of array otherwise get an compile time error. For

Example 
int[] a=new int[]; Invalid.

int[] a=new int[5]; Valid

2) If we specify array size as negative int value, then we will get run-time error, NegativeArraySizeException.

3) To specify array size the allowed data types are byte, short, int, char If we use other data type then we will get an

Compile time error.

4) The maximum allowed size of array in java is 2147483647 (It is maximum value of int data type)

length vs length()

length: It is a final variable and only applicable for array. It represent size of array.
Example

int[] a=new int[10];


System.out.println(a.length); // 10
System.out.println(a.length()); // Compile time error

length(): It is final method applicable only for String objects. It represent number of character present in String.
Example

String s="Java";
System.out.println(s.length()); // 4
System.out.println(s.length); // Compile time error

Example of Array

public class ArrayEx


{
public static void main(String []args)
{
int arr[] = {10,20,30};
for (int i=0; i < arr.length; i++)
{
System.out.println(arr[i]);
}
}
}

Output

10

20

39

class Test1
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=70;
a[4]=90;
System.out.println(a[3]);
}
}

class Test1
{
public static void main(String args[])
{
int a[]=new int[5];
int i;
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=70;
a[4]=90;
for(i=0;i<5;i++)
{
System.out.println(a[i]);
}
}
}

II. datatype arrayname[]={array elements};

class Test1
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};
System.out.println(a[3]);
}
}

III

datatype arrayname[];
arrayname=new datatype[size];

class Test1
{
public static void main(String args[])
{
int a[];
a = new int[5];
a[0]=100;
a[1]=500;
a[2]=700;
a[3]=999;
a[4]=150;
System.out.println(a[3]);
}
}

import java.io.*;
class Test11
{
public static void main(String args[]) throws IOException
{
InputStreamReader I=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(I);
int a[],i,n;
a=new int[100];
System.out.print("enter limit..:");
n=Integer.parseInt(br.readLine());
System.out.println("enter Elements..:");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("entered Elements Are");
for(i=0;i<n;i++)
{
System.out.print("\t"+a[i]);
}
}
}

import java.io.*;
class Test11
{
public static void main(String args[]) throws IOException
{
InputStreamReader I=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(I);
int a[],i,n,sum=0;
a=new int[100];
System.out.print("enter limit..:");
n=Integer.parseInt(br.readLine());
System.out.println("enter Elements..:");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("entered Elements Are");
for(i=0;i<n;i++)
{
System.out.print("\t"+a[i]);
sum=sum+a[i];
}
System.out.println("\nSum Of Elements="+sum);
}
}

The foreach Loops:

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the
complete array sequentially without using an index variable.

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList) {
System.out.println(element);
}
}
}

Double Dimensional Array

Datatype arrayname[r][c]={array elements};


int a[][]={{10,20,30},{40,50,60},{70,80,90}};

class Test12
{
public static void main(String[]args)
{
int a[][]={{10,20,30},{40,50,60},{70,80,90}};
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print("\t"+a[i][j]);
System.out.println();
}

}
}

class Test12
{
public static void main(String[]args)
{
int a[][]={{10,20,30},{40,50,60},{70,80,90}};
int b[][]={{10,20,30},{40,50,60},{70,80,90}};
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print("\t"+a[i][j]);
System.out.println();
}
System.out.println();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print("\t"+b[i][j]);
System.out.println();
}
}
}

class Test12
{
public static void main(String[]args)
{
int a[][]={{10,20,30},{40,50,60},{70,80,90}};
int b[][]={{10,20,30},{40,50,60},{70,80,90}};
int i,j;
System.out.println("A Matrix");
System.out.println("********");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print("\t"+a[i][j]);
System.out.println();
}
System.out.println("B Matrix");
System.out.println("********");
System.out.println();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print("\t"+b[i][j]);
System.out.println();
}
System.out.println("Sum of A & B Matrix");
System.out.println("*******************");

System.out.println();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print("\t"+(a[i][j]+b[i][j]));
System.out.println();
}
}
}

String class

A string is a data type used in programming, such as an integer and floating point unit, but is used to
represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and
numbers. For example, the word "abhishek " and the phrase "I am abhishek kumar dubey software engineer "
are both strings. Even "12345" could be considered a string, if specified correctly. Typically, programmers
must enclose strings in quotation marks for the data to be recognized as a string and not a number or
variable name.
Strings

Java String Class is immutable, i.e. Strings in java, once


created and initialized, cannot be changed on the same
reference

Requirement of String Pool

String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string
already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and
returning its reference.

The following code will create only one string object in the heap.

1.String string1 = "abcd";


2.String string2 = "abcd";

Here is how it looks:

If string is not immutable, changing the string with one reference will lead to the wrong value for the other
references.

Immutable String in Java


In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

1. class Simple{  
2.  public static void main(String args[]){  
3.    String s="Sachin";  
4.    s.concat(" Tendulkar");//concat() method appends the string at the end  
5.    System.out.println(s);//will print Sachin because strings are immutable objects  
6.  }  
7. }  
Output:Sachin

Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with
sachintendulkar. That is why string is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to
"Sachin Tendulkar".

But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:

1. class Simple{  
2.  public static void main(String args[]){  
3.    String s="Sachin";  
4.    s=s.concat(" Tendulkar");  
5.    System.out.println(s);  
6.  }  
7. }  

Output:Sachin Tendulkar

In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.

Why string objects are immutable in java?


Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object
"sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables.
That is why string objects are immutable in java.

2. Allow String to Cache its Hashcode

The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that
hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need
to calculate hashcode every time it is used. This is more efficient.

3. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String
not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was
connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the
parameters are strings.

Here is a code example:

view source
print?
1.boolean connect(string s){
2.if (!isSecure(s)) {
3.throw new SecurityException();
4.}
5.//here will cause problem, if s is changed before this by using other references.   
6.causeProblem(s);
7.}

Method Details (String operation)


 charAt(int index)- returns the character at the specified location.
 
 int compareTo(String other)- returns a negative value if the string comes before another in dictionary
order, a positive value if the string comes after another in dictionary order,
 or 0 if the strings are equal.
 
 boolean endsWith(String suffix)- returns true if the string ends with suffix.
 
 equals(Object other)- returns true if the string equals other.

 equalsIgnoreCase(String other)- returns true if the string equals another, except for upper/lowercase
distinction.
 
 int indexOf(String str)-
 
 int indexOf(String str,int fromIndex)- return the start of the first substring equal to str, starting at
index 0 or at fromIndex.
 
 int lastIndexOf(String str)-
 
 int lastIndexOf(String str,int fromIndex)- return the start of the last substring equal to str, starting at
index 0 or at fromIndex.
 
 int length()- returns the length of the string.
 
 String replace(char oldChar,char newChar)- returns a new string that is obtained by replacing all
characters oldChar in the string with newChar.
 
 boolean startsWith(String prefix)-returns true if the string begins with prefix.
 
 String substring(int beginIndex)
 
 String substring(int beginIndex,int endIndex)- return a new string consisting of all characters from
beginIndex until the end of the string or until endIndex (exclusive).
 
 String toLowerCase()- returns a new string containing all characters in the original string, with
uppercase characters converted to lower case.
 
 String toUpperCase()- returns a new string containing all characters in the original string, with
lowercase characters converted to upper case.
 
 String trim()- returns a new string by eliminating all leading and trailing spaces in the original string.

Example

public class StringOperation


     {
      public static void main(String arg[]) {
            String s = " I am abhishek kumar dubey ";
            String s1 = new String("abhishek");
            System.out.println("the value charat(5)=" + s.charAt(5) + "\n");
            System.out.println("CompareTo method value=" + s.compareTo(s1) + "\n");
            System.out.println("is End with suffix =" + s.endsWith("dubey") + "\n");
            System.out.println("check equals=" + s.equals(s1) + "\n");
            System.out.println("check equals=" + s.equalsIgnoreCase(s1) + "\n");
            System.out.println("Index of dubey=" + s.indexOf("dubey") + "\n");
            System.out.println("Last Index of dubey=" + s.lastIndexOf("dubey")
                        + "\n");
            System.out.println("The length of String s=" + s.length() + "\n");
            System.out.println("Replace 'a' by 'A'=" + s.replace('a', 'A') + "\n");
            System.out.println("check prefix=" + s.startsWith("I") + "\n");
            System.out.println("Sub String1=" + s.substring(10) + "\n");
            System.out.println("Sub String2=" + s.substring(10, 15) + "\n");
            System.out.println("change String in lower Case=" + s.toLowerCase()
                        + "\n");
            System.out.println("change String in upper Case=" + s.toUpperCase()
                        + "\n");
            System.out.println("Remove the space end and last=" + s.trim() + "\n");
      }
}

Output

String comparison in Java

We can compare two given strings on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by ==
operator) etc.

There are three ways to compare String objects:

1. By equals() method
2. By = = operator
3. By compareTo() method

1) By equals() method
equals() method compares the original content of the string.It compares values of string for equality.String class
provides two methods:
 public boolean equals(Object another){} compares this string to the specified object.
 public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.

1. class Simple{  
2.  public static void main(String args[]){  
3.    
4.    String s1="Sachin";  
5.    String s2="Sachin";  
6.    String s3=new String("Sachin");  
7.    String s4="Saurav";  
8.   
9.    System.out.println(s1.equals(s2));//true  
10.    System.out.println(s1.equals(s3));//true  
11.    System.out.println(s1.equals(s4));//false  
12.  }  
13. }  

Output:true
true
false

1. //Example of equalsIgnoreCase(String) method  
2. class Simple{  
3.  public static void main(String args[]){  
4.    
5.    String s1="Sachin";  
6.    String s2="SACHIN";  
7.   
8.    System.out.println(s1.equals(s2));//false  
9.    System.out.println(s1.equalsIgnoreCase(s3));//true  
10.  }  
11. }  

Output:false
true

2) By == operator
The = = operator compares references not values.
1. //<b><i>Example of == operator</i></b>  
2.   
3. class Simple{  
4.  public static void main(String args[]){  
5.    
6.    String s1="Sachin";  
7.    String s2="Sachin";  
8.    String s3=new String("Sachin");  
9.   
10.    System.out.println(s1==s2);//true (because both refer to same instance)  
11.    System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  
12.  }  
13. }  

Output:true
false

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or
greater than.
Suppose s1 and s2 are two string variables.If:
 s1 == s2 :0
 s1 > s2   :positive value

 s1 < s2   :negative value

1. //<b><i>Example of compareTo() method:</i></b>  
2.   
3. class Simple{  
4.  public static void main(String args[]){  
5.    
6.    String s1="Sachin";  
7.    String s2="Sachin";  
8.    String s3="Ratan";  
9.   
10.    System.out.println(s1.compareTo(s2));//0  
11.    System.out.println(s1.compareTo(s3));//1(because s1>s3)  
12.    System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
13.  }  
14. }  

Output:0
1
-1
/*

        Java String Array Example.

        This Java String Array example how to create and use String array or array of Strings in Java.

 */

public class JavaStringArray {

        public static void main(String args[]){

        

                /*

                 * Java String array can be created in below given ways.

                 */

        

                /*

                 * Declare and initialize String array in single statement as given below.

                 * This method is particularly useful when we are dealing with very small size array.

                 */
                String[] myFirstStringArray = new String[]{"String 1", "String 2", "String 3"};

        

                /*

                 * Declaration and assignment can be done separately as given below.

                 */

        

                //first declare String array

                String[] mySecondStringArray = new String[3];

        

                //Observe that giving size is mandatory here. While there was no size given in the first method.

        

                //Now Assign individual String array elements

                mySecondStringArray[0] = "String 1";

                mySecondStringArray[1] = "String 2";

                mySecondStringArray[2] = "String 3";

        

                //Note that, like every other arrays, String array starts with index 0 and not index 1.

        

                /*

                 * Retrieve values from String Array:            *

                 * String array elements can be retrieved by directly accessing using index. You may also iterate

                 * String array using loop.

                 */
        

                //this will retrieve second element of first String array

                System.out.println(myFirstStringArray[1]);

        

                //iterate the String array using loop

                for(int i=0; i < mySecondStringArray.length; i++){

                        System.out.println(mySecondStringArray[i]);

        }

    }

/*

Output of the above Java String Array Example program would be

String 2

String 1

String 2

String 3

*/

public class Sort


{
public static void main(String[ ] args)
{
String[ ] names = {"joe", "apple","ed", "george"};
sortStringExchange (names);
for ( int k = 0; k < 4; k++ )
System.out.println( names [ k ] );
}

public static void sortStringExchange( String x [ ] )


{
int i, j;
String temp;

for ( i = 0; i < x.length - 1; i++ )


{
for ( j = i + 1; j < x.length; j++ )
{
if ( x [ i ].compareToIgnoreCase( x [ j ]) > 0 )
{ // ascending sort
temp = x [ i ];
x [ i ] = x [ j ]; // swapping
x [ j ] = temp;

}
}
}
}
}
-------------------------------------------------------------------------------------------------------

// A bubble sort for Strings.


0.class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};

public static void main(String args[]) {


for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}

public class BubbleSortString {

public static void main(String args []) {


String [] unsortedArray = {"M","F","B","E","Z","F","D","Q","R","S","H","A"};
printArray("Unsorted Array:", unsortedArray);

String [] sortedArray = bubbleSortAscending(unsortedArray);

printArray("Sorted Array (Ascending):", sortedArray);

sortedArray = bubbleSortDescending(unsortedArray);

printArray("Sorted Array (Descending):", sortedArray);

private static String[] bubbleSortDescending(String[] unsortedArray) {

for (int index = unsortedArray.length - 1; index > 0; index--) {


for (int bubbleIndex = 0; bubbleIndex < index; bubbleIndex++) {
/**
* using String's compareTo method to see if one element is
* bigger than the other.
*/
if (unsortedArray[index].compareTo(unsortedArray[bubbleIndex]) > 0) {
swap(unsortedArray, index, bubbleIndex);
}

}
}
return unsortedArray; // which is now sorted
}

private static String[] bubbleSortAscending(String[] unsortedArray) {

for (int index = unsortedArray.length - 1; index > 0; index--) {


for (int bubbleIndex = 0; bubbleIndex < index; bubbleIndex++) {
/**
* using String's compareTo method to see if one element is
* bigger than the other.
*/
if (unsortedArray[index].compareTo(unsortedArray[bubbleIndex]) < 0) {
swap(unsortedArray, index, bubbleIndex);
}

}
}

return unsortedArray; // which is now sorted


}

private static void swap(String[] unsortedArray, int firstIndex, int secondIndex) {


if(unsortedArray == null
|| firstIndex < 0
|| firstIndex > unsortedArray.length
|| secondIndex < 0
|| secondIndex > unsortedArray.length) {
return;
}
String tempString = unsortedArray[firstIndex];
unsortedArray[firstIndex] = unsortedArray[secondIndex];
unsortedArray[secondIndex] = tempString;

private static void printArray(String string, String[] unsortedArray) {

if (unsortedArray != null && unsortedArray.length > 0) {


System.out.print(string + " ");
for (int i = 0; i < unsortedArray.length; i++) {
System.out.print((i > 0 ? "," : "") + unsortedArray[i]);
}
}

System.out.println();
}
}

StringBuffer

StringBuffer class is a mutable class unlike the String class


which is immutable. Both the capacity and character string of
a StringBuffer Class. StringBuffer can be changed dynamically
.String buffers are preferred when heavy modification of
character strings is involved (appending, inserting, deleting,
modifying etc).
append()

This is the append() function used for the concatenate the string in string buffer. This is better to use for dynamic
string concatenation. This function works like a simple string concatenation such as : String str = str + "added
string";.

insert()

This is the insert() function used to insert any string or character at the specified position in the given string.

reverse()

This is the reverse() function used to reverse the string present in string buffer.

setCharAt()

This is the setCharAt() function which is used to set the specified character in buffered string at the specified
position of the string in which you have to set the given character.

charAt()

This is the charAt() function which is used to get the character at the specified position of the given string.

substring()

This is the substring() function which is used to get the sub string from the buffered string from the initial position
to end position (these are fixed by you in the program).
deleteCharAt()

This is the deleteCharAt() function which is used to delete the specific character from the buffered string by
mentioning that's position in the string.

length()

This is the length() function is used to finding the length of the buffered string.

delete()

This is the delete() function is used to delete multiple character at once from n position to m position (n and m are
will be fixed by you.) in the buffered string.

capacity()

This is the capacity() function is used to know about the current characters kept which is displayed like : number of
characters + 6.

class Test13
{
public static void main(String args[])
{
StringBuffer st1=new StringBuffer("BRILLIANT");
StringBuffer st2=new StringBuffer("ongole");
StringBuffer st3=new StringBuffer("BRILLIANT");
StringBuffer st4=new StringBuffer("brilliant");
StringBuffer st5=new StringBuffer(" guntur");
System.out.println("Length="+st1.length());
System.out.println("CharAt="+st1.charAt(3));
System.out.println("Equals="+st1.equals(st2));
System.out.println("Equals="+st1.equals(st4));
System.out.println("Reverse="+st5.reverse());
System.out.println("Insert="+st5.insert(3,"X"));
System.out.println("Append="+st5.append("Hyderabad"));
System.out.println("delete="+st5.delete(3,7));
}
}

StringBuilder
The java.lang.StringBuilder class is mutable sequence of
characters. This provides an API compatible with StringBuffer,
but with no guarantee of synchronization.

StringBuffer Functions
The following program explains the usage of the some of the basic StringBuffer methods like ;

1. capacity() Returns the current capacity of the String buffer.

2. length() Returns the length (character count) of this string buffer.

3. charAt(int index) The specified character of the sequence currently represented by the string buffer, as
indicated by the index argument, is returned.

4. setCharAt(int index, char ch) The character at the specified index of this string buffer is set to ch

5. toString() Converts to a string representing the data in this string buffer

6. insert(int offset, char c) Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the
application need.

7. delete(int start, int end) Removes the characters in a substring of this StringBuffer

8. replace(int start, int end, String str) Replaces the characters in a substring of this StringBuffer with characters in
the specified String.

9. reverse() The character sequence contained in this string buffer is replaced by the reverse of the sequence.

10. append(String str) Appends the string to this string buffer.


Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the
application need.

11. setLength(int newLength) Sets the length of this String buffer.

class Test13
{
public static void main(String args[])
{
StringBuilder st1=new StringBuilder("BRILLIANT");
StringBuilder st2=new StringBuilder("ongole");
StringBuilder st3=new StringBuilder("BRILLIANT");
StringBuilder st4=new StringBuilder("brilliant");
StringBuilder st5=new StringBuilder(" guntur");
System.out.println("Length="+st1.length());
System.out.println("CharAt="+st1.charAt(3));
System.out.println("Equals="+st1.equals(st2));
System.out.println("Equals="+st1.equals(st4));
System.out.println("Reverse="+st5.reverse());
System.out.println("Insert="+st5.insert(3,"X"));
System.out.println("Append="+st5.append("Hyderabad"));
System.out.println("delete="+st5.delete(3,7));
}
}

StringTokenizer

The StringTokenizer class allows us to break a string into tokens. The StringTokenizer method does not distinguish
among the identifiers quoted string, numbers, skip comment; and the StringTokenizer class implements the
Enumeration interfaceTo use a StringTokenizer that you specify in an input String which contains delimiters.

import java .io.*;


import java.util.*;
class MyStringTokenizer
{
public static void main(String arg[])throws IOException
{
String s="this ,is, the, example, of, StirgTokenizer";
/* creating the object of stringTokenizer Class by passing the object string type s and second object passing as
delimeter */
StringTokenizer st=new StringTokenizer(s,",");
/* hasMoreTokens() using for printing the return token it return the value true */
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

//split string example

String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";


String[] splits = asseltClasses.split(":");

System.out.println("splits.size: " + splits.length);

for(String asset: assetClasses){


System.out.println(asset);
}

OutPut
splits.size: 5
Gold
Stocks
Fixed Income
Commodity
Interest Rates
]

//string split example with limit

String places = "London.Switzerland.Europe.Australia";


String[] placeSplits = places.split("\\.",2);

System.out.println("placeSplits.size: " + placeSplits.length );

for(String contents: placeSplits){


System.out.println(contents);
}

Output:
placeSplits.size: 2
London
Switzerland.Europe.Australia

Read more: http://javarevisited.blogspot.com/2011/09/string-split-example-in-java-tutorial.html#ixzz36vsAq2kE

//string split on special character “|”

String assetTrading = "Gold Trading|Stocks Trading|Fixed Income Trading|Commodity Trading|FX trading";

String[] splits = assetTrading.split("\\|"); // two \\ is required because "\" itself require escaping

for(String trading: splits){


System.out.println(trading);
}

OutPut:
Gold Trading
Stocks Trading
Fixed Income Trading
Commodity Trading
FX trading

// split string on “.”

String smartPhones = "Apple IPhone.HTC Evo3D.Nokia N9.LG Optimus.Sony Xperia.Samsung Charge”;

String[] smartPhonesSplits = smartPhones.split("\\.");

for(String smartPhone: smartPhonesSplits){


System.out.println(smartPhone);
}

OutPut:
Apple IPhone
HTC Evo3D
Nokia N9
LG Optimus
Sony Xperia
Samsung Charge

import java.io.*;
class Test1
{
public static void main(String args[]) throws IOException
{
String Str[]=new String[20];
int n,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter limit..:");
n=Integer.parseInt(br.readLine());
System.out.println("Enter "+n+" Strings");
for(i=0;i<n;i++)
{
Str[i]=br.readLine();
}
System.out.println("Entered String Are..:");
for(i=0;i<n;i++)
{
System.out.print("\t"+Str[i]);
}
}
}

Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching or manipulating strings.

It is widely used to define constraint on strings such as password and email validation. After learning java
regex tutorial, you will be able to test your own regular expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.

java.util.regex package

It provides following classes and interface for regular expressions. The Matcher and Pattern classes are widely
used in java regular expression.

1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class

Matcher class
It implements MatchResult interface. It is a regex engine i.e. used to perform match operations on a character
sequence.

No. Method Description


1 boolean matches() test whether the regular expression matches the pattern.

2 boolean find() finds the next expression that matches the pattern.

3 boolean find(int start) finds the next expression that matches the pattern from the given start number.

Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.

No. Method Description

1 static Pattern compile(String regex) compiles the given regex and return the instance of pattern.

2 Matcher matcher(CharSequence creates a matcher that matches the given input with pattern.
input)

3 static boolean matches(String regex, It works as the combination of compile and matcher methods. It
CharSequence input) compiles the regular expression and matches the given input with
the pattern.

4 String[] split(CharSequence input) splits the given input string around matches of given pattern.

5 String pattern() returns the regex pattern.

Example of Java Regular Expressions


There are three ways to write the regex example in java.

1. import java.util.regex.*;  
2. public class RegexExample1{  
3. public static void main(String args[]){  
4. //1st way  
5. Pattern p = Pattern.compile(".s");//. represents single character  
6. Matcher m = p.matcher("as");  
7. boolean b = m.matches();  
8.   
9. //2nd way  
10. boolean b2=Pattern.compile(".s").matcher("as").matches();  
11.   
12. //3rd way  
13. boolean b3 = Pattern.matches(".s", "as");  
14.   
15. System.out.println(b+" "+b2+" "+b3);  
16. }}  
Test it Now

Output
true true true

Regular Expression . Example


The . (dot) represents a single character.

1. import java.util.regex.*;  
2. class RegexExample2{  
3. public static void main(String args[]){  
4. System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)  
5. System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)  
6. System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)  
7. System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)  
8. System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)  
9. }}  
Test it Now

Regex Character classes


No. Character Class Description

1 [abc] a, b, or c (simple class)

2 [^abc] Any character except a, b, or c (negation)

3 [a-zA-Z] a through z or A through Z, inclusive (range)

4 [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)

5 [a-z&&[def]] d, e, or f (intersection)

6 [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)

7 [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)

Regular Expression Character classes Example


1. import java.util.regex.*;  
2. class RegexExample3{  
3. public static void main(String args[]){  
4. System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)  
5. System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)  
6. System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more than 
once)  
7. }}  
Test it Now

Regex Quantifiers
The quantifiers specify the number of occurrences of a character.

Regex Description

X? X occurs once or not at all

X+ X occurs once or more times

X* X occurs zero or more times

X{n} X occurs n times only

X{n,} X occurs n or more times

X{y,z} X occurs at least y times but less than z times

Regular Expression Character classes and Quantifiers Example


1. import java.util.regex.*;  
2. class RegexExample4{  
3. public static void main(String args[]){  
4. System.out.println("? quantifier ....");  
5. System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)  
6. System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)  
7. System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more th
an one time)  
8. System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time) 
 
9. System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time
)  
10.   
11. System.out.println("+ quantifier ....");  
12. System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)  
13. System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)  
14. System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more t
han once)  
15. System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pat
tern)  
16.   
17. System.out.println("* quantifier ....");  
18. System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero 
or more times)  
19.   
20. }}  
Test it Now

Regex Metacharacters
The regular expression metacharacters work as a short codes.

Regex Description

. Any character (may or may not match terminator)

\d Any digits, short of [0-9]

\D Any non-digit, short for [^0-9]

\s Any whitespace character, short for [\t\n\x0B\f\r]

\S Any non-whitespace character, short for [^\s]

\w Any word character, short for [a-zA-Z_0-9]

\W Any non-word character, short for [^\w]

\b A word boundary

\B A non word boundary

Regular Expression Metacharacters Example


1. import java.util.regex.*;  
2. class RegexExample5{  
3. public static void main(String args[]){  
4. System.out.println("metacharacters d....");\\d means digit  
5.   
6. System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)  
7. System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)  
8. System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than once)  
9. System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)  
10.   
11. System.out.println("metacharacters D....");\\D means non-digit  
12.   
13. System.out.println(Pattern.matches("\\D", "abc"));//false (non-digit but comes more than onc
e)  
14. System.out.println(Pattern.matches("\\D", "1"));//false (digit)  
15. System.out.println(Pattern.matches("\\D", "4443"));//false (digit)  
16. System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)  
17. System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)  
18.   
19. System.out.println("metacharacters D with quantifier....");  
20. System.out.println(Pattern.matches("\\D*", "mak"));//true (non-digit and may come 0 or mor
e times)  
21.   
22. }}  
Test it Now

Regular Expression Question 1


1. /*Create a regular expression that accepts alpha numeric characters only. Its 
2. length must be 6 characters long only.*/  
3.   
4. import java.util.regex.*;  
5. class RegexExample6{  
6. public static void main(String args[]){  
7. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true  
8. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "kkvarun32"));//false (more than 6 char)  
9. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true  
10. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"));//false ($ is not matched)  
11. }}  

Test it Now

Regular Expression Question 2


1. /*Create a regular expression that accepts 10 digit numeric characters 
2.  starting with 7, 8 or 9 only.*/  
3.   
4. import java.util.regex.*;  
5. class RegexExample7{  
6. public static void main(String args[]){  
7. System.out.println("by character classes and quantifiers ...");  
8. System.out.println(Pattern.matches("[789]{1}[0-9]{9}", "9953038949"));//true  
9. System.out.println(Pattern.matches("[789][0-9]{9}", "9953038949"));//true  
10.   
11. System.out.println(Pattern.matches("[789][0-9]{9}", "99530389490"));//false (11 characters)  
12. System.out.println(Pattern.matches("[789][0-9]{9}", "6953038949"));//false (starts from 6)  
13. System.out.println(Pattern.matches("[789][0-9]{9}", "8853038949"));//true  
14.   
15. System.out.println("by metacharacters ...");  
16. System.out.println(Pattern.matches("[789]{1}\\d{9}", "8853038949"));//true  
17. System.out.println(Pattern.matches("[789]{1}\\d{9}", "3853038949"));//false (starts from 3)  
18.   
19. }}  

Object Oriented Programming

Object and Class

Object is the physical as well as logical entity where as class is the only logical entity.

Class: Class is a blue print which is containing only list of variables and method and no memory is allocated for
them. A class is a group of objects that has common properties.

A class in java contains:

 Data Member
 Method
 Constructor
 Block
 Class and Interface

Object: Object is a instance of class, object has state and behaviors.

An Object in java has three characteristics:

 State
 Behavior
 Identity

State: Represents data (value) of an object.

Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.

Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external
user. But,it is used internally by the JVM to identify each object uniquely.

Class is also can be used to achieve user defined data types.


In real world many examples of object and class like dog, cat, and cow are belong to animal’s class. Each object has
state and behaviors. For example a dog has state – color, name, height, age as well as behaviors – barking, eating,
and sleeping.

Vehicle class

Car, bike, truck these all are belongs to vehicle class. These Objects have also different different states and
behaviors. For Example car has state - color, name, model, speed, Mileage. as we;; as behaviors - distance travel
Simple example of class and object related to girls and boy's
Difference between Class and Object
Class Object
Class is a container which collection of
1 object is a instance of class
variables and methods.
No memory is allocated at the time of Sufficient memory space will be allocated for all the variables of
2
declaration class at the time of declaration.
One class definition should exist only once in
3 For one class multiple objects can be created.
the program.

Syntax to declare a Class


class Class_Name
{
data member;
method;
}
Simple Example of Object and Class

In this example, we have created a Employee class that have two data members eid and ename. We are creating the
object of the Employee class by new keyword and printing the objects value.

class Employee
{
int eid; //data member (also instance variable)
String ename; //data member(also instance variable)

public static void main(String args[])


{
Employee e=new Employee();//creating an object of Employee
System.out.println(e.eid+" "+e.ename);
}
}

Note: A new keyword is used to allocate memory at runtime, new keyword is used for create an object of class,
later we discuss all the way for create an object of class.

Encapsulation

Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation
is achieved in java language by class concept. The main advantage of using of encapsulation is to secure the data
from other methods, when we make a data private then these data only use within the class, but these data not
accessible outside the class.

Combining of state and behavior in a single container is known as encapsulation. In java language encapsulation
can be achieve using “class” keyword, state represents declaration of variables on attributes and behavior represents
operations in terms of method.
Benefits of encapsulation
1. Provides abstraction between an object and its clients.
2. Protects an object from unwanted access by clients.
3. Example: A bank application forbids a client to change an Account's balance.

Simple example of encapsulation in java

Let's see the simple example of encapsulation that has only one field with its setter and getter methods.

1. //save as Student.java  
2. package com.javatpoint;  
3. public class Student{  
4. private String name;  
5.    
6. public String getName(){  
7. return name;  
8. }  
9. public void setName(String name){  
10. this.name=name  
11. }  
12. }  

1. //save as Test.java  
2. package com.javatpoint;  
3. class Test{  
4. public static void main(String[] args){  
5. Student s=new Student();  
6. s.setname("vijay");  
7. System.out.println(s.getName());  
8. }  
9. }  

Compile By: javac -d . Test.java


Run By: java com.javatpoint.Test
Output: vijay

class IceCream
{
int price;
int quantity;
void mealt()
{
System.out.println("It Mealts At Heavy Temperatures");
}
public static void main(String args[])
{
IceCream Vanilla=new IceCream();
Vanilla.price=20;
Vanilla.quantity=100;
System.out.println("Vanilla Price="+Vanilla.price);
System.out.println("Vanilla quantity="+Vanilla.quantity);
Vanilla.mealt();
}
}

Array of Objects:

It is possible to create array of objects of user created class.

Example:

class Employee{
int id;
String name;
public void setData(int id, String name){
this.id = id;
this.name = name;
}
public void displayData(){
System.out.println("Employee ID : "+this.id);
System.out.println("Employee Name : "+this.name);
}
}
class Main{
public static void main(String args[]){
Employee[] emp = new Employee[2];
emp[0].setData(1,"ABC");
emp[1].setData(2,"XYZ");
emp[0].displayData();
emp[1].displayData();
}
}
Access Modifiers
1. private access modifier
2. Role of private constructor
3. default access modifier
4. protected access modifier
5. public access modifier
6. Applying access modifier with method overriding

There are two types of modifiers in java: access modifier and non-access modifier. The access modifiers specifies
accessibility (scope) of a datamember, method, constructor or class.

There are 4 types of access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we
will learn access modifiers.

1) private
The private access modifier is accessible only within class.

Simple example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is compile time error.

1. class A{  
2. private int data=40;  
3. private void msg(){System.out.println("Hello java");}  
4. }  
5.   
6. public class Simple{  
7.  public static void main(String args[]){  
8.    A obj=new A();  
9.    System.out.println(obj.data);//Compile Time Error  
10.    obj.msg();//Compile Time Error  
11.    }  
12. }  

Role of Private Constructor:


If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:

1. class A{  
2. private A(){}//private constructor  
3.   
4. void msg(){System.out.println("Hello java");}  
5. }  
6.   
7. public class Simple{  
8.  public static void main(String args[]){  
9.    A obj=new A();//Compile Time Error  
10.  }  
11. }  

Note: A class cannot be private or protected except nested class.

2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within
package.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.

1. //save by A.java  
2.   
3. package pack;  
4. class A{  
5.   void msg(){System.out.println("Hello");}  
6. }  

1. //save by B.java  
2.   
3. package mypack;  
4. import pack.*;  
5.   
6. class B{  
7.   public static void main(String args[]){  
8.    A obj = new A();//Compile Time Error  
9.    obj.msg();//Compile Time Error  
10.   }  
11. }  
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
package.

3) protected

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the
class.

Example of protected access modifier


In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can
be accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.

1. //save by A.java  
2.   
3. package pack;  
4. public class A{  
5. protected void msg(){System.out.println("Hello");}  
6. }  

1. //save by B.java  
2.   
3. package mypack;  
4. import pack.*;  
5.   
6. class B extends A{  
7.   public static void main(String args[]){  
8.    B obj = new B();  
9.    obj.msg();  
10.   }  
11. }  

Output:Hello

4) public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier

1. //save by A.java  
2.   
3. package pack;  
4. public class A{  
5. public void msg(){System.out.println("Hello");}  
6. }  

1. //save by B.java  
2.   
3. package mypack;  
4. import pack.*;  
5.   
6. class B{  
7.   public static void main(String args[]){  
8.    A obj = new A();  
9.    obj.msg();  
10.   }  
11. }  

Output:Hello

http://javaseguide.blogspot.in/2013/05/interfaces-in-java_3241.html

Access Modifiers in JAVA


The access to classes, constructors, methods and fields are regulated using access
modifiers i.e. a class can control what information or data can be accessible by other
classes. Access modifiers specifies who can access them. There are four access modifiers
used in java as follows: 
1. public
2. private 
3. protected
4. no modifer (declaring without an access modifer).

public access modifier: Fields, methods and constructors declared public (least


restrictive) within a public class are visible to any class in the Java program, whether these
classes are in the same package or in another package.

private access modifier: The private (most restrictive) fields or methods cannot be used
for classes and Interfaces. It also cannot be used for fields and methods within an
interface. Fields, methods or constructors declared private are strictly controlled, which
means they cannot be accesses by anywhere outside the enclosing class. A standard design
strategy is to make all fields private and provide public getter methods for them.
protected access modifier: The protected fields or methods cannot be used for classes
and Interfaces. It also cannot be used for fields and methods within an interface. Fields,
methods and constructors declared protected in a superclass can be accessed only by
subclasses in other packages. Classes in the same package can also access protected fields,
methods and constructors as well, even if they are not a subclass of the protected
member’s class.

default access modifier: Java provides a default specifier which is used when no access
modifier is present. Any class, field, method or constructor that has no declared access
modifier is accessible only by classes in the same package. The default modifier is not used
for fields and methods within an interface.

Usage of these access modifiers is restricted to following two levels:


1. class level access modifiers
2. member level access modifiers.

Class level access modifiers (java classes only):

Only two access modifiers is allowed, public and no modifier for classes in java.

If a class is ‘public’, then it can be accessed from anywhere.


If a class has ‘no modifer’, then it can only be accessed from ‘same package’.

Member level access modifiers (java variables and java methods)

All the four public, private, protected and no modifer is allowed.

public and no modifier – the same way as used in class level.


private – members can only access.
protected – can be accessed from ‘same package’ and a subclass existing in any package
can access.

For better understanding, member level access is formulated as a table:


Access Specifiers

Access specifiers are those which are applied before data members or methods of a class. These are used to

where to access and where not to access the data members or methods. In java programming we have four access

specifiers they are:

 Private

 Default (not a keyword)

 Protected

 Public
Note: protected is not a keyword (like public, private, protected are keyword)

If we are not using private protected and public keywords then JVM is by default taking as default access specifier.

Access specifiers are always used for how to reuse the features within the package and access the package

between class to class, interface to interface and interface to class. Access specifier provides features accessing

and controlling mechanism among the classes and interfaces.

Note: protected members of class is accessible within the same class and other class of same package and also

accessible in inherited class of other package.


Rules for access specifiers:

The following diagram gives rules for Access specifiers.

private: private members of class in not accessible any where in program these are only accessible within the class.

private are also called class level access specifier.


Example

class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}

public class Demo


{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a); //Compile Time Error, you can't access private data
obj.show(); //Compile Time Error, you can't access private methods
}
}

public: public members of any class is accessible any where in program inside the same class and outside of class,

within the same package and outside of the package. public are also called universal access specifier.
Example

class Hello
{
public int a=20;
public void show()
{
System.out.println("Hello java");
}
}

public class Demo


{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a);
obj.show();
}
}

Output

20

Hello Java
protected: protected members of class is accessible within the same class and other class of same package and

also accessible in inherited class of other package. protected are also called derived level access specifier.

In below example we have create two packages pack1 and pack2. In pack1, class A is public so we can access this

class outside of pack1 but method show is declared as a protected so it is only access outside of package pack1

only through inheritance.

Example

// save A.java
package pack1;
public class A
{
protected void show()
{
System.out.println("Hello Java");
}
}
//save B.java
package pack2;
import pack1.*;

class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.show();
}
}

Output

Hello Java

default: default members of class is accessible only within same class and other class of same package. default are

also called package level access specifier.


Example

//save by A.java
package pack;
class A
{
void show()
{
System.out.println("Hello Java");
}
}
//save by B.java
package pack2;
import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside the package
obj.show(); //Compile Time Error, can't access outside the package
}
}

Output

Hello Java

Note: private access specifier is also known as native access specifier, default access specifier is also known as

package access specifier, protected access specifier is also known as inherited access specifier, public access

specifier is also known as universal access specifier.

Access Control and Inheritance: Following are the rules for inherited methods are
enforced:
 Methods declared public in a superclass also must be public in all subclasses.

 Methods declared protected in a superclass must either be protected or public in


subclasses; they cannot be private.
 Methods declared without access control (no modifier was used) can be declared
more private in subclasses.

 Methods declared private are not inherited at all, so there is no rule for them.

Example:  The following figure shows the four classes in this example and how they are
related.

The following table shows where the members of the Class1 class are visible for each of the
access modifiers that can be applied to them.

We will look example in next post(please see Access Modifiers Example post).

Access Modifiers Example


Case1. SameClass, SamePckage : All fields are accessble
package com.sample.javase.testing;

public class AccessModifiersExample {

public int i = 10;


private int j = 9;
protected int k = 8;
int l = 7;

public void publicMethod() {


System.out.println("this is public method");
}

private void privateMethod() {


System.out.println("This is private method");
}

protected void protectedMethod() {


System.out.println("this is protected method");
}

void noSpecifierMethod() {
System.out.println("This is no specifier method");
}

/**
 * @param args
 */
public static void main(String[] args) {

/**
 * Here we are trying to access all methods and variables in the same
 * class. So we can access everything like private , public, nomodifier
 * and proteced variables and methods.So no problem here.
 */

AccessModifiersExample accessModifiersExample = new 


  AccessModifiersExample();
accessModifiersExample.privateMethod();
accessModifiersExample.publicMethod();
accessModifiersExample.protectedMethod();
accessModifiersExample.noSpecifierMethod();
System.out.println("Value of i is " + accessModifiersExample.i);
System.out.println("Value of j is " + accessModifiersExample.j);
System.out.println("Value of k is " + accessModifiersExample.k);
System.out.println("Value of l is " + accessModifiersExample.l);
}
}

***********************************************************
Case2. Subclass, SamePckage : public, protected and nomodifiers fields are
accessble and private fields are not accessble

package com.sample.javase.testing;
public class AceessModifiersExample1 extends AccessModifiersExample {

/**
 * @param args
 */
public static void main(String[] args) {

/**
 * This is subclass in the same package. So here we can
 * not access the private variabls and methods. Here we can access both
 * public, protected and nomodifier variables and methods.
 */
AccessModifiersExample1 accessModifiersExample = new 
  AccessModifiersExample1();
accessModifiersExample.protectedMethod();
accessModifiersExample.publicMethod();
accessModifiersExample.noSpecifierMethod();
// private method is not accessble out side the class
// accessModifiersExample.privateMethod();
System.out.println("value of i is " + accessModifiersExample.i);
System.out.println("value of k is " + accessModifiersExample.k);
System.out.println("value of l is " + accessModifiersExample.l);
}
}

***********************************************************

Case3. OtherClass, SamePckage : public, protected and nomodifiers fields are


accessble and private fields are not accessble

package com.sample.javase.testing;

public class AceessModifiersExample11 {

/**
 * @param args
 */
public static void main(String[] args) {

/**
 * This is another class in the same package. So here we can
 * not access the private variabls and methods. Here we can access both
 * public, protected and nomodifier variables and methods.
 */
AccessModifiersExample accessModifiersExample = new 
  AccessModifiersExample();
accessModifiersExample.protectedMethod();
accessModifiersExample.publicMethod();
accessModifiersExample.noSpecifierMethod();
// private method is not accessble out side the class
// accessModifiersExample.privateMethod();
System.out.println("value of i is " + accessModifiersExample.i);
System.out.println("value of k is " + accessModifiersExample.k);
System.out.println("value of l is " + accessModifiersExample.l);
}
}

***********************************************************

Case4. Subclass, OtherPckage : only public and protected fields are accessble and
private and nomodifier  fields are not accessble

package com.sample.javase.testing1;

import com.sample.javase.testing.AccessModifiersExample;

public class AccessModifiersExample2 extends AccessModifiersExample {

/**
 * @param args
 */
public static void main(String[] args) {

/**
 * This is subclass in the other package. So here we can
 * not access the private and nomodifier variabls and
 * methods. Here we can access only public and protected variables and   
   * methods.
 */
AccessModifiersExample2 accessModifiersExample = new 
  AccessModifiersExample2();
accessModifiersExample.publicMethod();
  accessModifiersExample.protectedMethod();
  // accessModifiersExample.noSpecifierMethod();
// private method is not accessble out side the class
// accessModifiersExample.privateMethod();
System.out.println("value of i is " + accessModifiersExample.i);
 // System.out.println("value of k is " + accessModifiersExample.k);
 // System.out.println("value of l is " + accessModifiersExample.l);
}
}

***********************************************************
Case5. OtherClass, OtherPckage : only public fields are accessible and private,
protectded and nomodifier  fields are not accessble

package com.sample.javase.testing1;

import com.sample.javase.testing.AccessModifiersExample;

public class AccessModifiersExample22 {

/**
 * @param args
 */
public static void main(String[] args) {

/**
 * This is another class in the other package. So here we can
 * not access the private, protected and nomodifier variables and
 * methods. Here we can access only public variables and methods.
 */
AccessModifiersExample accessModifiersExample = new 
  AccessModifiersExample();
accessModifiersExample.publicMethod();
  // accessModifiersExample.protectedMethod();
  // accessModifiersExample.noSpecifierMethod();
// private method is not accessble out side the class
// accessModifiersExample.privateMethod();
System.out.println("value of i is " + accessModifiersExample.i);
  // System.out.println("value of k is " + accessModifiersExample.k);
  // System.out.println("value of l is " + accessModifiersExample.l);
}
}
If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.

1. class A{  
2. protected void msg(){System.out.println("Hello java");}  
3. }  
4.   
5. public class Simple extends A{  
6. void msg(){System.out.println("Hello java");}//C.T.Error  
7.  public static void main(String args[]){  
8.    Simple obj=new Simple();  
9.    obj.msg();  
10.    }  
11. }  

The default modifier is more restrictive than protected. That is why there is compile time error.
class IceCream
{
int price;
int quantity;
void mealt()
{
System.out.println("It Mealts At Heavy Temperatures");
}
}
class Arun
{
public static void main(String args[])
{
IceCream Vanilla=new IceCream();
Vanilla.price=20;
Vanilla.quantity=100;
System.out.println("Vanilla Price="+Vanilla.price);
System.out.println("Vanilla quantity="+Vanilla.quantity);
Vanilla.mealt();
}
}

javac IceCream.java
java Arun
class IceCream
{
int price;
int quantity;
void mealt()
{
System.out.println("It Mealts At Heavy Temperatures");
}
}
class Arun
{
public static void main(String args[])
{
IceCream Vanilla=new IceCream();
Vanilla.price=20;
Vanilla.quantity=100;
System.out.println("Vanilla Price="+Vanilla.price);
System.out.println("Vanilla quantity="+Vanilla.quantity);
Vanilla.mealt();

System.out.println("**********************");
IceCream ButterScotch=new IceCream();
ButterScotch.price=20;
ButterScotch.quantity=100;
System.out.println("ButterScotch Price="+ButterScotch.price);
System.out.println("ButterScotch quantity="+ButterScotch.quantity);
ButterScotch.mealt();

}
}

class IceCream
{
int price;
int quantity;
void mealt()
{
System.out.println("It Mealts At Heavy Temperatures");
}
int billAmount()
{
return price*quantity;
}
}
class Arun
{
public static void main(String args[])
{
IceCream Vanilla=new IceCream();
Vanilla.price=20;
Vanilla.quantity=100;
System.out.println("Vanilla Price="+Vanilla.price);
System.out.println("Vanilla quantity="+Vanilla.quantity);
Vanilla.mealt();
System.out.println("Bill Amount="+Vanilla.billAmount());

System.out.println("**********************");
IceCream ButterScotch=new IceCream();
ButterScotch.price=20;
ButterScotch.quantity=100;
System.out.println("ButterScotch Price="+ButterScotch.price);
System.out.println("ButterScotch quantity="+ButterScotch.quantity);
ButterScotch.mealt();
System.out.println("Bill Amount="+ButterScotch.billAmount());
}
}

class MyCalc
{
int a;
int b;
int mySum()
{
return a+b;
}
int mySub()
{
return a-b;
}

public static void main(String[]args)


{
MyCalc MC=new MyCalc();
MC.a=30;
MC.b=10;
System.out.println("Sum="+MC.mySum());
System.out.println("Sub="+MC.mySub());
}
}

next>> << prev

Object Cloning in Java

The object cloning is a way to create exact copy of an object. For this
purpose, clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we
don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

1. protected Object clone() throws CloneNotSupportedException  

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by
using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)


Let's see the simple example of object cloning

class Student implements Cloneable{  

int rollno;  

String name;  

  

Student(int rollno,String name){  

this.rollno=rollno;  

this.name=name;  

}  

  

public Object clone()throws CloneNotSupportedException{  

return super.clone();  

}  

  

public static void main(String args[]){  

try{  

Student s1=new Student(101,"amit");  

  

Student s2=(Student)s1.clone();  

  

System.out.println(s1.rollno+" "+s1.name);  

System.out.println(s2.rollno+" "+s2.name);  
  

}catch(CloneNotSupportedException c){}  

  

}  

}  

Output:101 amit
101 amit

As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the
values of an object to another. So we don't need to write explicit code to copy the value of an object to another.

If we create another object by new keyword and assign the values of another object to this one, it will require a lot
of processing on this object. So to save the extra processing task we use clone() method.

class MyCalc //class


{
int a; //variables
int b;
MyCalc(int x,int y)
{
a=x;
b=y;
}
MyCalc(MyCalc m)
{
a=m.a;
b=m.b;
}
int mySum()
{
return a+b;
}
public static void main(String[]args)
{
MyCalc MC=new MyCalc(100,150);//object
MyCalc MC1=new MyCalc(MC); //object
System.out.println("Sum="+MC.mySum());
System.out.println("Sum="+MC1.mySum());
}
}

class MyCalc //class


{
int a; //variables
int b;
MyCalc(int x,int y)
{
a=x;
b=y;
}
MyCalc(){ }
int mySum()
{
return a+b;
}
public static void main(String[]args)
{
MyCalc MC=new MyCalc(100,150);//object
MyCalc MC1=new MyCalc(); //object
MC1.a=MC.a;
MC1.b=MC.b;
System.out.println("Sum="+MC.mySum());
System.out.println("Sum="+MC1.mySum());
}
}

class MyCalc implements Cloneable //class


{
int a; //variables
int b;
MyCalc(int x,int y) //constructor with parameters
{
a=x;
b=y;
}
MyCalc(MyCalc m)
{
a=m.a;
b=m.b;
}
int mySum()
{
return a+b;
}
public static void main(String[]args)throws CloneNotSupportedException
{
MyCalc MC=new MyCalc(100,150);//object
MyCalc MC1=(MyCalc)MC.clone();
System.out.println("Sum="+MC.mySum());
System.out.println("Sum="+MC1.mySum());
}
}

instanceof operator
1. The instanceof operator
2. Example of instanceof operator
3. Applying the instanceof operator with a variable the have null value
4. Downcasting with instanceof operator
5. Downcasting without instanceof operator

The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or
interface).

The instanceof operator is also known as type comparison operator because it compares the instance with type. It
returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns
false.

Simple example of instanceof operator

Let's see the simple example of instance operator where it tests the current class.

1. class Simple{  
2.  public static void main(String args[]){  
3.  Simple s=new Simple();  
4.  System.out.println(s instanceof Simple);//true  
5.  }  
6. }  

Output:true

An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog
can be referred by either Dog or Animal class.

Another example of instanceof operator

1. class Animal{}  
2. class Dog extends Animal{//Dog inherits Animal  
3.   
4.  public static void main(String args[]){  
5.  Dog d=new Dog();  
6.  System.out.println(d instanceof Animal);//true  
7.  }  
8. }  

Output:true

instanceof operator with a variable that have null value

If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given
below where we apply instanceof operator with the variable that have null value.

1. class Dog{  
2.  public static void main(String args[]){  
3.   Dog d=null;  
4.   System.out.println(d instanceof Dog);//false  
5.  }  
6. }  

Output:false

Downcasting with instanceof operator

When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly,
compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if
we use instanceof operator, downcasting is possible.
1. Dog d=new Animal();//Compilation error  

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

1. Dog d=(Dog)new Animal();  
2. //Compiles successfully but ClassCastException is thrown at runtime  

Possibility of downcasting with instanceof operator

Let's see the example, where downcasting is possible by instanceof operator.

1. class Animal { }  
2.   
3. class Dog extends Animal {  
4.   static void method(Animal a) {  
5.     if(a instanceof Dog){  
6.        Dog d=(Dog)a;//downcasting  
7.        System.out.println("ok downcasting performed");  
8.     }  
9.   }  
10.    
11.   public static void main (String [] args) {  
12.     Animal a=new Dog();  
13.     Dog.method(a);  
14.   }  
15.     
16.  }  

Output:ok downcasting performed

Downcasting without the use of instanceof operator

Downcasting can also be performed without the use of instanceof operator as displayed in the following example:

1. class Animal { }  
2. class Dog extends Animal {  
3.   static void method(Animal a) {  
4.        Dog d=(Dog)a;//downcasting  
5.        System.out.println("ok downcasting performed");  
6.   }  
7.    public static void main (String [] args) {  
8.     Animal a=new Dog();  
9.     Dog.method(a);  
10.   }  
11. }  

Output:ok downcasting performed

Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast it, it is
fine. But what will happen if we write:

1. Animal a=new Animal();  
2. Dog.method(a);  
3. //Now ClassCastException but not in case of instanceof operator  

Understanding Real use of instanceof operator

Let's see the real use of instanceof keyword by the example given below.

1. interface Printable{}  
2. class A implements Printable{  
3. public void a(){System.out.println("a method");}  
4. }  
5. class B implements Printable{  
6. public void b(){System.out.println("b method");}  
7. }  
8.   
9. class Call{  
10. void invoke(Printable p){//upcasting  
11. if(p instanceof A){  
12. A a=(A)p;//Downcasting   
13. a.a();  
14. }  
15. if(p instanceof B){  
16. B b=(B)p;//Downcasting   
17. b.b();  
18. }  
19.   
20. }  
21. }//end of Call class  
22.   
23. class Test{  
24. public static void main(String args[]){  
25. Printable p=new B();  
26. Call c=new Call();  
27. c.invoke(p);  
28. }  
29. }  

Output: b method

Constructor

A constructor is a special member method which will be called implicitly (automatically) by the JVM whenever an

object is created for placing user or programmer defined values in place of default values.

The purpose of constructor is to initialize an object called object initialization. Constructors are mainly create for

initializing the object. Initialization is a process of assigning user defined values at the time of allocation of memory

space.

Syntax

className()
{
.......
.......
}

Advantages of constructors:

 A constructor eliminates placing the default values.

 A constructor eliminates calling the normal or ordinary method implicitly.

How Constructor eliminate default values ?

Constructor are mainly used for eliminate default values by user defined values, whenever we create an object of

any class then its allocate memory for all the data members and initialize there default values. To eliminate these

default values by user defined values we use constructor.


Example

class Sum
{
int a,b;
Sum()
{
a=10;
b=20;
}
public static void main(String s[])
{
Sum s=new Sum();
c=a+b;
System.out.println("Sum: "+c);
}
}

Output

Sum: 30
In above example when we create an object of "Sum" class then constructor of this class call and initialize user

defined value in a=10 and b=20. if we can not create constructor of Sum class then it print " Sum: 0 " because

default values of integer is zero.

Rules or properties of a constructor

 Constructor will be called automatically when the object is created.

 Constructor name must be similar to name of the class.

 Constructor should not return any value even void also. Because basic aim is to place the value in
the object. (if we write the return type for the constructor then that constructor will be treated as
ordinary method).
 Constructor definitions should not be static. Because constructors will be called each and every
time, whenever an object is creating.

 Constructor should not be private provided an object of one class is created in another class
(Constructor can be private provided an object of one class created in the same class).

 Constructors will not be inherited from one class to another class (Because every class constructor is
create for initializing its own data members).

 The access specifier of the constructor may or may not be private.


1. If the access specifier of the constructor is private then an object of corresponding class can be
created in the context of the same class but not in the context of some other classes.
2. If the access specifier of the constructor is not private then an object of corresponding class can be
created both in the same class context and in other class context.

Difference between Method and Constructor

Method Constructor
1 Method can be any user defined name Constructor must be class name
2 Method should have return type It should not have any return type (even void)
Method should be called explicitly either with It will be called automatically whenever object is
3
object reference or class reference created
Method is not provided by compiler in any The java compiler provides a default
4
case. constructor if we do not have any constructor.
Types of constructors

Based on creating objects in Java constructor are classified in two types. They are

 Default or no argument Constructor

 Parameterized constructor.

Default Constructor: A constructor is said to be default constructor if and only if it never take any
parameters.

If any class does not contain at least one user defined constructor than the system will create a default constructor at

the time of compilation it is known as system defined default constructor.

Syntax

class className
{
..... // Call default constructor
clsname ()
{
Block of statements; // Initialization
}
.....
}

class MyCalc //class MyClac


{
int a; //variables
int b;
MyCalc() //constructor
{
a=20;
b=10;
}
int mySum() //Method 1
{
return a+b;
}
int mySub() //Metho2
{
return a-b;
}

public static void main(String[]args)


{
MyCalc MC=new MyCalc();
System.out.println("Sum="+MC.mySum());
System.out.println("Sub="+MC.mySub());
}
}

parameterized constructor

If any constructor contain list of variable in its signature is known as paremetrized constructor. A parameterized

constructor is one which takes some parameters.

Syntax

class ClassName
{
.......
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}

Syntax to call parametrized constructor

ClassName objref=new ClassName(value1, value2,.....);

OR

new ClassName(value1, value2,.....);

class MyCalc //class MyClac


{
int a; //variables
int b;
MyCalc(int x,int y) //constructor
{
a=x;
b=y;
}
int mySum() //Method 1
{
return a+b;
}
int mySub() //Metho2
{
return a-b;
}

public static void main(String[]args)


{
MyCalc MC=new MyCalc(20,10);
System.out.println("Sum="+MC.mySum());
System.out.println("Sub="+MC.mySub());
}
}

Important points Related to Parameterized Constructor

 Whenever we create an object using parameterized constructor, it must be define parameterized


constructor otherwise we will get compile time error. Whenever we define the objects with respect to
both parameterized constructor and default constructor, It must be define both the constructors.

 In any class maximum one default constructor but 'n' number of parameterized constructors.

class MyCalc //class MyClac


{
int a; //variables
int b;
MyCalc(int a,int b) //constructor
{
this.a=a;
this.b=b;
}
int mySum() //Method 1
{
return a+b;
}
int mySub() //Metho2
{
return a-b;
}

public static void main(String[]args)


{
MyCalc MC=new MyCalc(20,10);
System.out.println("Sum="+MC.mySum());
System.out.println("Sub="+MC.mySub());
}
}

class MyCalc //class MyClac


{
int a; //variables
int b;
int mySum(int x,int y) //Method 1
{
return x+y;
}
public static void main(String[]args)
{
MyCalc MC=new MyCalc();
System.out.println("Sum="+MC.mySum(150,100));
}
}

Polymorphism

In Greek the word poly means many and morphism means forms
or shapes. If the class has more than one method with the
same name but with different parameters then it is called
polymorphism which sometimes is also referred as method
overloading.

Overloading

Whenever same method name is exiting multiple times in the same class with different number of parameter or
different order of parameters or different types of parameters is known as method overloading.

Why method Overloading

Suppose we have to perform addition of given number but there can be any number of arguments, if we write
method such as a(int, int)for two arguments, b(int, int, int) for three arguments then it is very difficult for you and
other programmer to understand purpose or behaviors of method they can not identify purpose of method. So we
use method overloading to easily figure out the program. For example above two methods we can write sum(int,
int) and sum(int, int, int) using method overloading concept.

Syntax:

class class_Name
{
Returntype method()
{
...........
...........
}
Returntype method(datatype1 variable1)
{
...........
...........
}
Returntype method(datatype1 variable1, datatype2 variable2)
{
...........
...........
}
Returntype method(datatype2 variable2)
{
...........
...........
}
Returntype method(datatype2 variable2, datatype1 variable1)
{
..........
..........
}
}

Different ways to overload the method

There are two ways to overload the method in java

 By changing number of arguments or parameters


 By changing the data type

By changing number of arguments

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and
second sum method performs addition of three numbers.

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}

Output

30
60
By changing the data type

In this example, we have created two overloaded methods that differs in data type. The first sum method receives
two integer arguments and second sum method receives two float arguments.

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}

Output

30
25.25

Why Method Overloaing is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method because there may occur
ambiguity. Let's see how ambiguity may occur:

because there was problem:

class Addition
{
int sum(int a, int b)
{
System.out.println(a+b);
}
double sum(int a, int b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition obj=new Addition();
int result=obj.sum(20,20); //Compile Time Error
}
}
Explanation of Code
int result=obj.sum(20,20);

Here how can java determine which sum() method should be called

Note: The scope of overloading is within the class.

Any object reference of class can call any of overloaded method.

As for as real time application are concern overloaded method should exists with same name but with different
implementation part.

class MyCalc //class MyClac


{
int a; //variables
int b;
int c;
int mySum(int x,int y) //Method 1
{
return x+y;
}
int mySum(int x,int y,int z) //Method 1
{
return x+y+z;
}

public static void main(String[]args)


{
MyCalc MC=new MyCalc();
System.out.println("Sum="+MC.mySum(150,100));
System.out.println("Sum="+MC.mySum(150,100,200));
}
}

class MyVals
{
int a;
double b;
String c;
char d;

void disVals(int x,double y)


{
a=x;
b=y;
System.out.println(+x+" "+y);
}
void disVals(int x,double y,String z)
{
a=x;
b=y;
c=z;
System.out.println(+x+" "+y+" "+z);
}

void disVals(int x,double y,String z,char z1)


{
a=x;
b=y;
c=z;
d=z1;
System.out.println(+x+" "+y+" "+z+" "+z1);
}

public static void main(String[]args)


{
MyVals MV=new MyVals();
MV.disVals(100,45.9);
MV.disVals(100,45.9,"BRILLIANT");
MV.disVals(100,45.9,"ONGOLE",'B');
}
}

Constructor OverLoading

If the class has more than one constructor with the same
name but with different parameters then is called constructor
overloading.

Constructor overloading. 

In general constructor overloading can be used to initialized same or different objects with different values.
Syntax

class ClassName
{
ClassName()
{
..........
..........
}
ClassName(datatype1 value1)
{.......}
ClassName(datatype1 value1, datatype2 value2)
{.......}
ClassName(datatype2 variable2)
{.......}
ClassName(datatype2 value2, datatype1 value1)
{.......}
........
}

class MyCalc //class MyClac


{
int a; //variables
int b;
int c;
MyCalc(int x,int y)
{
a=x;
b=y;
}
int mySum() //Method 1
{
return a+b;
}
MyCalc(int x,int y,int z)
{
a=x;
b=y;
c=z;
}
int mySum1() //Method 1
{
return a+b+c;
}

public static void main(String[]args)


{
MyCalc MC=new MyCalc(1,2);
System.out.println("Sum="+MC.mySum());
MyCalc MC1=new MyCalc(1,2,3);
System.out.println("Sum="+MC1.mySum1());
}
}

class MyVals
{
int a;
double b;
String c;
char d;

MyVals(int x,double y)
{
a=x;
b=y;
}
void dispVals()
{
System.out.println(+a+" "+b);
}
MyVals(int x,double y,String z)
{
a=x;
b=y;
c=z;
}
void dispVals1()
{
System.out.println(+a+" "+b+" "+c);
}
MyVals(int x,double y,String z,char z1)
{
a=x;
b=y;
c=z;
d=z1;
}
void dispVals2()
{
System.out.println(+a+" "+b+" "+c+" "+d);
}

public static void main(String[]args)


{
MyVals MV=new MyVals(100,67.5);
MV.dispVals();

MyVals MV1=new MyVals(100,67.5,"ONGOLE");


MV1.dispVals1();

MyVals MV2=new MyVals(100,67.5,"ONGOLE",'P');


MV2.dispVals2();

}
}

Overriding

Whenever same method name is existing in both base class and derived class with same types of parameters or

same order of parameters is known as method Overriding.

Note: Without Inheritance method overriding is not possible.

Advantage of Java Method Overriding

 Method Overriding is used to provide specific implementation of a method that is already provided
by its super class.

 Method Overriding is used for Runtime Polymorphism


Rules for Method Overriding

 method must have same name as in the parent class.

 method must have same parameter as in the parent class.

 must be IS-A relationship (inheritance).

Understanding the problem without method overriding

Lets understand the problem that we may face in the program if we do not use method overriding.

Example

class Walking
{
void walk()
{
System.out.println("Man walking fastly");
}
}
class OverridingDemo
{
public static void main(String args[])
{
Man obj = new Man();
obj.walk();
}
}

Output

Man walking

Problem is that I have to provide a specific implementation of walk() method in subclass that is why we use method

overriding.
Example of method overriding

In this example, we have defined the walk method in the subclass as defined in the parent class but it has some

specific implementation. The name and parameter of the method is same and there is IS-A relationship between the

classes, so there is method overriding.

Example

class Walking
{
void walk()
{
System.out.println("Man walking fastly");
}
}
class Man extends walking
{
void walk()
{
System.out.println("Man walking slowly");
}
}

class OverridingDemo
{
public static void main(String args[])
{
Man obj = new Man();
obj.walk();
}
}

Output

Man walking slowly


Note: Whenever we are calling overridden method using derived class object reference the highest priority is given

to current class (derived class). We can see in the above example high priority is derived class.

Note: super. (super dot) can be used to call base class overridden method in the derived class.

Accessing properties of base class with respect to derived class object

class A
{
int x;
void f1()
{
x=10;
System.out.println(x);
}
void f4()
{
System.out.println("this is f4()");
System.out.println("-----------------");
}
};
class B extends A
{
int y;
void f1()
{
int y=20;
System.out.println(y);
System.out.println("this is f1()");
System.out.println("------------------");
}
};
class C extends A
{
int z;
void f1()
{
z=10;
System.out.println(z);
System.out.println("this is f1()");
}
};
class Overide
{
public static void main(String[] args)
{
A a1=new B();
a1.f1();
a1.f4();
A c1=new C();
c1.f1();
c1.f4();
}
}
Example of Implement overriding concept

class Person
{
String name;
void sleep(String name)
{
this.name=name;
System.out.println(this.name +"is sleeping+8hr/day");
}
void walk()
{
System.out.println("this is walk()");
System.out.println("-----------------");
}
};
class Student extends Person
{
void writExams()
{
System.out.println("only student write the exam");
}
void sleep(String name)
{
super.name=name;
System.out.println(super.name +"is sleeping 6hr/day");
System.out.println("------------------");
}
};
class Developer extends Person
{
public void designProj()
{
System.out.println("Design the project");
}
void sleep(String name)
{
super.name=name;
System.out.println(super.name +"is sleeping 4hr/day");
System.out.println("------------------");
}
};
class OverideDemo
{
public static void main(String[] args)
{
Student s1=new Student();
s1.writExams();
s1.sleep("student");
s1.walk();
Developer d1=new Developer();
d1.designProj();
d1.sleep("developer");
}
}

Difference between Overloading and Overriding

Overloading Overriding
Whenever same method or Constructor is Whenever same method name is existing
existing multiple times within a class either with multiple time in both base and derived class
1 different number of parameter or with different with same number of parameter or same
type of parameter or with different order of type of parameter or same order of
parameter is known as Overloading. parameters is known as Overriding.
Arguments of method must be different at least Argument of method must be same
2
arguments. including order.
3 Method signature must be different. Method signature must be same.
Private, static and final methods can be Private, static and final methods can not be
4
overloaded. override.
Access modifiers point of view not reduced
5 Access modifiers point of view no restriction.
scope of Access modifiers but increased.
Also known as compile time polymorphism or Also known as run time polymorphism or
6
static polymorphism or early binding. dynamic polymorphism or late binding.
7 Overloading can be exhibited both are method Overriding can be exhibited only at method
and constructor level. leve.
The scope of Overriding is base class and
8 The scope of overloading is within the class.
derived class.
Overloading can be done at both static and Overriding can be done only at non-static
9
non-static methods. method.
For overloading methods return type may or For overriding method return type should be
10
may not be same. same.

Note: In overloading we have to check only methods names (must be same) and arguments types (must be

different) except these the remaining like return type access modifiers etc. are not required to check 

But in overriding every things check like method names arguments types return types access modifiers etc.

polymorphism

Polymorphism is one of the distinct principal of Oops the process of representing one Form in multiple forms is
known as polymorphism here one form represent original form or original method always resides in base class and
multiple forms represents overridden method which resides in derived classes.

Polymorphism is not a programming concept but it is one of the principal of Oops for many objects oriented
programming language polymorphism principle is common but whose implementations are varying from one
objects oriented programming language to another object oriented programming language.

Real life example of polymorphism

Here Ben can transform in different-different aliens but their original form is Ben just change in other-other forms
due to this their behaviour also change
In below example sin chan act as a student in school, act as a friend with friends, act as a son at home.

Same condition apply on yourself when you are in class then behave like a student, in market act as a customer, in
home act as a son or daughter
In java programming the polymorphism principal is implemented with method overriding concept of java. We
know that method overriding is equal to method heading is some method body is different.

Polymorphism principal is divided into two sub principal they are:

1. Static / Compile time polymorphism


2. Dynamic / Runtime polymorphism

Java programming does not support static polymorphism because of its limitations and java always supports
dynamic polymorphism.

Let us consider the following diagram


In the above diagram the sum method which is present in BC class is called original form and the sum() method
which are present in DC1 and DC2 are called overriden form hence Sum() method is originally available in only
one form and it is further implemented in multiple forms. Hence Sum() method is one of the polymorphism method.

Dynamic Binding

Dynamic binging always says create an object of base class but do not create the object of derived classes.

The advantages of dynamic binding along with polymorphism with method overriding are.

1. Less memory space


2. Less execution time
3. More performance

Dynamic binding principal is always used for executing polymorphic applications.

Definition

The process of binding appropriate versions (overridden method) of derived classes which are inherited from base
class with base class object is known as dynamic binding.
When we are dynamic binding principal for executing polymorphism based application, internally JVM considers
the following two points.

1. What type of object?


2. What type of reference / address object contains?

In other words when we create an object indirectly, JVM internally considers the above two points.

Note: To create an object indirectly, there must exists super-sub base-derived parent-child relationship.

Faculty fo=new Sudent();


Parent p=new Child();>

Here fo objects is of type faculty class and fo object contains the reference of student class let us consider the
following set of executable statement for executing the program represented in figure 1.
In the above example bo1 is containing the references of BC, DC1, DC2 classes hence bo1 is known as
polymorphism object.

Here sum() method is actually available in one from and it is implemented in multiple forms. Hence sum() method
is known as polymorphism method.

The statement bo1.sum() is actually only one statement but it gives different sum() int, float, char, sum. This
statement is known as polymorphism statement. In real world applications a java program can be developed by
using the following cases.

Case 1: Business logic will be developed in independent class and execution logic class can be developed by using
plain old logic (direct object creation)

Case 2: Business logic will be developed in dependent classes contains the logics of polymorphic along with
method overriding and execution logic developed with plain old execution logic. If we develop any java application
by using the above two cases then that application will get the following limitations.
1. Application memory space is more (main memory)
2. Application execution time is more
3. Application performance is reduced

Case 3: Business logic will be developed in dependent classes contain (polymorphism + method overriding logic)
and execution logic will be developed by using dynamic binding principal. If we developed any java application by
using the above case 3 then such application will get the following advantages.

1. Application memory space is less (main memory)


2. Application execution time is less
3. Application performance is enhance(improve)

Static polymorphism

It is one of the sub principal of polymorphism one of the object oriented programming language supports even
static polymorphism.

The language C, C++ supports static polymorphism principal by using its C++ programming concepts called
function overloading and operator overloading as per as standalone mechanism are concerned there is no difference
in performance of static polymorphism and dynamic polymorphism application but there is a significant difference
in execution of there applications in busy environment like client server environment.

Definition

The process of finding the overloaded method within object at compile time is known as static polymorphism due
to static polymorphism utilization of resources (main memory space) is poor because for each and every overloaded
method a memory space is created at compile time when it binds with an object. In C++ environment the above
problem can be solve by using dynamic polymorphism by implementing with virtual and pure virtual function so
most of the C++ developer in real worlds follows only dynamic polymorphism.

Dynamic polymorphism

In dynamic polymorphism method of the program finds with an object at runtime the advantage of dynamic
polymorphism is allocating the memory space for the method (either for overloaded method or for override method)
at run time.

Conclusion

The advantage of dynamic polymorphism is effective utilization of the resources effectively java programming does
not support static polymorphism because of its limitation. It is always dynamic polymorphism because of its
advantages.
Inheritance

The process of obtaining the data members and methods from one class to another class is known as inheritance. It

is one of the fundamental features of object-oriented programming.

Important points

 In the inheritance the class which is give data members and methods is known as base or super or
parent class.

 The class which is taking the data members and methods is known as sub or derived or child class.

 The data members and methods of a class are known as features.


 The concept of inheritance is also known as re-usability or extendable classes or sub classing or
derivation.

Why use Inheritance ?

 For Method Overriding (used for Runtime Polymorphism).

 It's main uses are to enable polymorphism and to be able to reuse code for different classes by
putting it in a common super class

 For code Re-usability


Syntax of Inheritance

class Subclass-Name extends Superclass-Name


{
//methods and fields
}

The following diagram use view about inheritance.


In the above diagram data members and methods are represented in broken line are inherited from faculty class and

they are visible in student class logically.

Advantage of inheritance

If we develop any application using concept of Inheritance than that application have following advantages,

 Application development time is less.

 Application take less memory.

 Application execution time is less.

 Application performance is enhance (improved).

 Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and
less storage cost.
Note: In Inheritance the scope of access modifier increasing is allow but decreasing is not allow. Suppose in parent

class method access modifier is default then it's present in child class with default or public or protected access modifier

but not private(it decreased scope).


Tpyes of Inheritance

Based on number of ways inheriting the feature of base class into derived class we have five Inheritance type they

are:

 Single inheritance

 Multiple inheritance

 Hierarchical inheritance

 Multilevel inheritance

 Hybrid inheritance

Single inheritance

In single inheritance there exists single base class and single derived class.

Multilevel inheritances

In Multilevel inheritances there exists single base class, single derived class and multiple intermediate base classes.

Single base class + single derived class + multiple intermediate base classes.

Intermediate base classes

An intermediate base class is one in one context with access derived class and in another context same class

access base class.


Hence all the above three inheritance types are supported by both classes and interfaces.

Multiple inheritance

In multiple inheritance there exist multiple classes and singel derived class.

The concept of multiple inheritance is not supported in java through concept of classes but it can be supported

through the concept of interface.


Hybrid inheritance

Combination of any inheritance type

In the combination if one of the combination is multiple inheritance then the inherited combination is not supported by

java through the classes concept but it can be supported through the concept of interface.

Inheriting the feature from base class to derived class

In order to inherit the feature of base class into derived class we use the following syntax

Syntax

class ClassName-2 extends ClasssName-1


{
variable declaration;
Method declaration;
}
Explanation

1. ClassName-1 and ClassName-2 represents name of the base and derived classes respectively.
2. extends is one of the keyword used for inheriting the features of base class into derived class it
improves the functionality of derived class.

Important Points for Inheritance:

 In java programming one derived class can extends only one base class because java programming
does not support multiple inheritance through the concept of classes, but it can be supported through
the concept of Interface.

 Whenever we develop any inheritance application first create an object of bottom most derived class
but not for top most base class.

 When we create an object of bottom most derived class, first we get the memory space for the data
members of top most base class, and then we get the memory space for data member of other bottom
most derived class.

 Bottom most derived class contains logical appearance for the data members of all top most base
classes.
 If we do not want to give the features of base class to the derived class then thedefinition of the base
class must be preceded by final hence final base classes are not reusable or not inheritable.

 If we are do not want to give some of the features of base class to derived class than such features of
base class must be as private hence private features of base class are not inheritable or accessible in
derived class.
 Data members and methods of a base class can be inherited into the derived class but constructors
of base class can not be inherited because every constructor of a class is made for initializing its own
data members but not made for initializing the data members of other classes.

 An object of base class can contain details about features of same class but an object of base class
never contains the details about special features of its derived class (this concept is known as scope of
base class object).

 For each and every class in java there exists an implicit predefined super class called
java.lang.Object. because it providers garbage collection facilities to its sub classes for collecting un-
used memory space and improved the performance of java application.
Example of Inheritance

class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}
}

Output

Salary is: 30000.0

Bonous is: 2000.0

Why multiple inheritance is not supported in java?

Due to ambiguity problem java does not support mutiple inheritance at class level.
Example

class A
{
void disp()
{
System.out.println("Hello");
}
}
class B
{
void disp()
System.out.println("How are you ?");
}
}
class C extends A,B //suppose if it were
{
Public Static void main(String args[])
{
C obj=new C();
obj.disp();//Now which disp() method would be invoked?
}
}

In above code we call both class A and class B disp() method then it confusion which class method is call. So due to

this ambiguity problem in java do not use multiple inheritance at class level, but it support at interface level.

Inheritance can be classified to 5 types.

1. Single Inheritance
2. Hierarchical Inheritance
3. Multi Level Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance

1. Single Inheritance

when a single derived class is created from a single base class then the inheritance is called as single inheritance.
2. Hierarchical Inheritance

when more than one derived class are created from a single base class, then that inheritance is called as hierarchical
inheritance.

3. Multi Level Inheritance

when a derived class is created from another derived class, then that inheritance is called as multi level inheritance.
4. Hybrid Inheritance

Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.

5. Multiple Inheritance

when a derived class is created from more than one base class then that inheritance is called as multiple inheritance.
But multiple inheritance is not supported by .net using classes and can be done using interfaces.
Handling the complexity that causes due to multiple inheritance is very complex. Hence it was not supported in
dotnet with class and it can be done with interfaces

class A
{
int x;
int y;
}
class B extends A
{
int z;
public int mySum()
{
return x+y+z;
}
public static void main(String[]args)
{
B B1=new B();
B1.x=20;
B1.y=10;
Bl.z=30;
System.out.println(B1.mySum());
}
}

class A
{
int x;
int y;
}
class B extends A
{
int z;
public int mySum()
{
return x+y+z;
}
}
class C extends B
{
int z1;
public int mySum()
{
return x+y+z+z1;
}

public static void main(String[]args)


{
B B1=new B();
B1.x=20;
B1.y=10;
B1.z=30;
System.out.println(B1.mySum());

C C1=new C();
C1.x=20;
C1.y=10;
C1.z=90;
C1.z1=100;
System.out.println(C1.mySum());

}
}

class A
{
int x;
int y;
}
class B extends A
{
int z;
public int mySum()
{
return x+y+z;
}
}
class C extends A
{
int z1;
public int mySum()
{
return x+y+z1;
}

public static void main(String[]args)


{
B B1=new B();
B1.x=20;
B1.y=10;
B1.z=30;
System.out.println(B1.mySum());

C C1=new C();
C1.x=20;
C1.y=10;
C1.z1=100;
System.out.println(C1.mySum());
}
}

class A
{
int x;
int y;
}
class B extends A
{
int z;
public int mySum()
{
return x+y+z;
}
}
class C extends A
{
int z1;
public int mySum()
{
return x+y+z1;
}
}
class D extends B
{
int z2;
public int mySum()
{
return x+y+z+z2;
}

public static void main(String[]args)


{
B B1=new B();
B1.x=20;
B1.y=10;
B1.z=30;
System.out.println(B1.mySum());

C C1=new C();
C1.x=20;
C1.y=10;
C1.z1=100;
System.out.println(C1.mySum());

D D1=new D();
D1.x=20;
D1.y=10;
D1.z=100;
D1.z2=100;
System.out.println(D1.mySum());
}
}
use of super keyword for constructors in java

Class can not only be determined by state and behavior of class but also by each of its
superclasses. Due to that reason it is not sufficient to execute a constructor of that class but
also need to initialize each constructor of superclasses.

A superclass constructor must execute before a subclass constructor. So that the state
and behavior defined by the superclass may be correctly and completely initialized before a
subclass constructor executes.

Java compiler assumes that the first line of every constructor is an implicit call to the
default superclass constructor unless you explicitly use super() or this().

Note that Super keyword is used to explicitly invoke a superclass constructor. If you
use this form, it must appear as the first statement of the constructor to ensure that
the superclass constructor executes before the subclass constructor in java.

Syntax to call Superclass Constructor


super(args);  

args is an optional list of arguments of the superclass constructor.

Note that you cannot use both super() and this() at the same time in same constructor
because both must appear as the first statement of the constructor.

Example of Constructor Inheritance and use of Super keyword to


call Constructor of super class

Example 1 : Program that shows the default execution of constructor when classes are inherited
class Person
{
     Person()
     {
              System.out.println("Constructor of person class");
      }

class Employee extends Person


{
     Employee()
     {
              System.out.println("Constructor of employee class");
      }
}
 
class PermanentEmployee extends Employee
{
     PermanentEmployee()
     {
              System.out.println("Constructor of permanent employee class");
      }
}
 
class ConstructorInheritanceDemo
{
      public static void main(String args())
      {
               PermanentEmployee pObj = new PermanentEmployee();
       }
}
 
 
Output
 
Constructor of person class
Constructor of employee class
Constructor of permanent employee class
 

Note that the superclass person and Employee constructors executes before the subclass
PermanentEmployee.

Example 2 : Program that illustrates the explicit use of super() in an inheritance hierarchy.
class Person
{
     String FirstName;
     String LastName;
 
     Person(String fName, String lName)
     {
              FirstName = fName;
              LastName = lName;
      }

class Student extends Person
{
     int id;
     String standard;
     String instructor;
 
     Student(String fName, String lName, int nId, String stnd, String instr)
     {
          super(fName,lName);
          id = nId;
          standard = stnd;
          instructor = instr;         
      }
}

class SuperKeywordForConstructorDemo
{
       public static void main(String args[])
       {
               Student sObj = new Student("Jacob","Smith",1,"1 - B","Roma");
 
               System.out.println("Student :");
               System.out.println("First Name : " + sObj.FirstName);
               System.out.println("Last Name : " + sObj.LastName);
               System.out.println("ID : " + sObj.id);
               System.out.println("Standard : " + sObj.standard);
               System.out.println("Instructor : " + sObj.instructor);
        }
}
 

Output
 
Student :
First Name : Jacob
Last Name : Smith
ID : 1
Standard : 1 - B
Instructor : Roma

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and
non-abstract methods (method with body).

Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only important things to the user and hides the internal details for example sending
sms, you just type the text and send the message. You don't know the internal processing about the message
delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class that is declared as abstract is known as abstract class. It needs to be extended and its method
implemented. It cannot be instantiated.

Example abstract class


1. abstract class A{}  

abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method


1. abstract void printStatus();//no body and abstract  

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It implementation is
provided by the Honda class.
1. abstract class Bike{  
2.   abstract void run();  
3. }  
4.   
5. class Honda4 extends Bike{  
6. void run(){System.out.println("running safely..");}  
7.   
8. public static void main(String args[]){  
9.  Bike obj = new Honda4();  
10.  obj.run();  
11. }  
12. }  
Test it Now
running safely..

Understanding the real scenario of abstract class


In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle
classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the
implementation class is provided by the factory method.

A factory method is the method that returns the instance of the class. We will learn about the factory
method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.

File: TestAbstraction1.java

1. abstract class Shape{  
2. abstract void draw();  
3. }  
4. //In real scenario, implementation is provided by others i.e. unknown by end user  
5. class Rectangle extends Shape{  
6. void draw(){System.out.println("drawing rectangle");}  
7. }  
8.   
9. class Circle1 extends Shape{  
10. void draw(){System.out.println("drawing circle");}  
11. }  
12.   
13. //In real scenario, method is called by programmer or user  
14. class TestAbstraction1{  
15. public static void main(String args[]){  
16. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method  
17. s.draw();  
18. }  
19. }  
Test it Now
drawing circle

Another example of abstract class in java


File: TestBank.java

1.  abstract class Bank{    
2. abstract int getRateOfInterest();    
3. }    
4.     
5. class SBI extends Bank{    
6. int getRateOfInterest(){return 7;}    
7. }    
8. class PNB extends Bank{    
9. int getRateOfInterest(){return 7;}    
10. }    
11.     
12. class TestBank{    
13. public static void main(String args[]){    
14. Bank b=new SBI();//if object is PNB, method of PNB will be invoked    
15. int interest=b.getRateOfInterest();    
16. System.out.println("Rate of Interest is: "+interest+" %");    
17. }}    
Test it Now
Rate of Interest is: 7 %

Abstract class having constructor, data member, methods etc.


An abstract class can have data member, abstract method, method body, constructor and even main()
method.

File: TestAbstraction2.java

1. //example of abstract class that have method body  
2.  abstract class Bike{  
3.    Bike(){System.out.println("bike is created");}  
4.    abstract void run();  
5.    void changeGear(){System.out.println("gear changed");}  
6.  }  
7.   
8.  class Honda extends Bike{  
9.  void run(){System.out.println("running safely..");}  
10.  }  
11.  class TestAbstraction2{  
12.  public static void main(String args[]){  
13.   Bike obj = new Honda();  
14.   obj.run();  
15.   obj.changeGear();  
16.  }  
17. }  
Test it Now
bike is created
running safely..
gear changed

Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{  
2. abstract void run();  
3. }  
Test it Now
compile time error

Rule: If you are extending any abstract class that have abstract method, you must either provide the
implementation of the method or make this class abstract.

Another real scenario of abstract class


The abstract class can also be used to provide some implementation of the interface. In such case, the end
user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{  
2. void a();  
3. void b();  
4. void c();  
5. void d();  
6. }  
7.   
8. abstract class B implements A{  
9. public void c(){System.out.println("I am C");}  
10. }  
11.   
12. class M extends B{  
13. public void a(){System.out.println("I am a");}  
14. public void b(){System.out.println("I am b");}  
15. public void d(){System.out.println("I am d");}  
16. }  
17.   
18. class Test5{  
19. public static void main(String args[]){  
20. A a=new M();  
21. a.a();  
22. a.b();  
23. a.c();  
24. a.d();  
25. }}  
Test it Now
Output:I am a
I am b
I am c
I am d

Interface

Interface is similar to class which is collection of public static final variables (constants) and abstract methods.

The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the

interface. It is used to achieve fully abstraction and multiple inheritance in Java.

Why we use Interface ?

 It is used to achieve fully abstraction.

 By interface, we can support the functionality of multiple inheritance.

 It can be used to achieve loose coupling.

properties of Interface

 An interface is implicitly abstract. So we no need to use the abstract keyword when declaring an
interface.

 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

 Methods in an interface are implicitly public.


 All the data members of interface are implicitly public static final.

How interface is similar to class ?

Whenever we compile any Interface program it generate .class file. That means the bytecode of an interface appears

in a .class file.

How interface is different from class ?

 You can not instantiate an interface.

 Interface does not contain any constructors.

 All methods in an interface are abstract.

 Interface can not contain instance fields. Interface only contains public static final variables.

 Interface is can not extended by a class; it is implemented by a class.

 Interface can extend multiple interfaces. It means interface support multiple inheritance
Behavior of compiler with Interface program

In the above image when we compile any interface program, by default compiler added public static final before any

variable and public abstract before any method. Because Interface is design for fulfill universal requirements and to

achieve fully abstraction.

Declaring Interfaces:

The interface keyword is used to declare an interface.


Example

interface Person
{
datatype variablename=value;
//Any number of final, static fields
returntype methodname(list of parameters or no parameters)
//Any number of abstract method declarations
}

Explanations

In the above syntax Interface is a keyword interface name can be user defined name the default signature of

variable is public static final and for method is public abstract. JVM will be added implicitly public static final before

data members and public abstract before method.


Example

public static final datatype variable name=value; ----> for data member

public abstract returntype methodname(parameters)---> for method

Implementing Interfaces:

A class uses the implements keyword to implement an interface. The implements keyword appears in the class

declaration following the extends portion of the declaration.

Example

interface Person
{
void run();
}
class Employee implements Person
{
public void run()
{
System.out.println("Run fast");
}
}
When we use abstract and when Interface

If we do not know about any things about implementation just we have requirement specification then we should be

go for Interface

If we are talking about implementation but not completely (partially implemented) then we should be go for abstract

Rules for implementation interface

 A class can implement more than one interface at a time.

 A class can extend only one class, but implement many interfaces.

 An interface can extend another interface, similarly to the way that a class can extend another class.

Relationship between class and Interface

 Any class can extends another class

 Any Interface can extends another Interface.

 Any class can Implements another Interface


 Any Interface can not extend or Implements any class.

Difference between Abstract class and Interface

Abstract class Interface


It is collection of abstract method and
1 It is collection of abstract method.
concrete methods.
There properties can be reused There properties commonly usable in any
2
commonly in a specific application. application of java environment.
3 It does not support multiple inheritance. It support multiple inheritance.
Abstract class is preceded by abstract
4 It is preceded by Interface keyword.
keyword.
Which may contain either variable or
5 Which should contains only constants.
constants.
The default access specifier of abstract There default access specifier of interface
6
class methods are default. method are public.
These class properties can be reused in These properties can be reused in any other
7
other class using extend keyword. class using implements keyword.
Inside abstract class we can take
8 Inside interface we can not take any constructor.
constructor.
For the abstract class there is no For the interface it should be compulsory to
9 restriction like initialization of variable at initialization of variable at the time of variable
the time of variable declaration. declaration.
Inside interface we can take instance and Inside interface we can not take instance and
10
static block. static block.
There are no any restriction for abstract For the interface variable can not declare
11
class variable. variable as private, protected, transient, volatile.
There are no any restriction for abstract For the interface method can not declare method
12 class method modifier that means we can as strictfp, protected, static, native, private,
use any modifiers. final, synchronized.
Example of Interface

interface Person
{
void run(); // abstract method
}
class A implements Person
{
public void run()
{
System.out.println("Run fast");
}
public static void main(String args[])
{
A obj = new A();
obj.run();
}
}

Output

Run fast
Multiple Inheritance using interface
Example

interface Developer
{
void disp();
}
interface Manager
{
void show();
}

class Employee implements Developer, Manager


{
public void disp()
{
System.out.println("Hello Good Morning");
}
public void show()
{
System.out.println("How are you ?");
}
public static void main(String args[])
{
Employee obj=new Employee();
obj.disp();
obj.show();
}
}

Output

Hello Good Morning


How are you ?
Marker or tagged interface

An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable,

Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful

operation.

Example

//Way of writing Serializable interface


public interface Serializable
{
}

Why interface have no constructor ?

Because, constructor are used for eliminate the default values by user defined values, but in case of interface all the

data members are public static final that means all are constant so no need to eliminate these values.

Other reason because constructor is like a method and it is concrete method and interface does not have concrete

method it have only abstract methods that's why interface have no constructor.

Abstraction

Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a

context.

Hiding of data is known as data abstraction. In object oriented programming language this is implemented

automatically while writing the code in the form of class and object.

Real life example

Abstraction shows only important things to the user and hides the internal details for example when we ride a bike,

we only know about how to ride bike but can not know about how it work ? and also we do not know internal

functionality of bike.

Note: Data abstraction can be used to provide security for the data from the unauthorized methods.
Note: In java language data abstraction can be achieve using class.
Example of Abstraction

class Customer
{
int account_no;
float balance_Amt;
String name;
int age;
String address;
void balance_inquiry()
{
/* to perform balance inquiry only account number
is required that means remaining properties
are hidden for balance inquiry method */
}
void fund_Transfer()
{
/* To transfer the fund account number and
balance is required and remaining properties
are hidden for fund transfer method */
}

How to achieve Abstraction ?

There are two ways to achieve abstraction in java

 Abstract class (0 to 100%)

 Interface (Achieve 100% abstraction)

Read more about Interface and Abstract class in previous section.

Difference between Encapsulation and Abstraction

Encapsulation is not provides fully security because we can access private member of the class using reflation API,

but in case of Abstraction we can't access static, abstract data member of class.
Interface in Java
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported in case of class.
5. Marker Interface
6. Nested Interface

An interface in java is a blueprint of a class. It has static constants and abstract methods only.

The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in
the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

 It is used to achieve fully abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and public, static and final
keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but
a class implements an interface.
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the A class.
1. interface printable{  
2. void print();  
3. }  
4.   
5. class A6 implements printable{  
6. public void print(){System.out.println("Hello");}  
7.   
8. public static void main(String args[]){  
9. A6 obj = new A6();  
10. obj.print();  
11.  }  
12. }  
Test it Now
Output:Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple
inheritance.
1. interface Printable{  
2. void print();  
3. }  
4.   
5. interface Showable{  
6. void show();  
7. }  
8.   
9. class A7 implements Printable,Showable{  
10.   
11. public void print(){System.out.println("Hello");}  
12. public void show(){System.out.println("Welcome");}  
13.   
14. public static void main(String args[]){  
15. A7 obj = new A7();  
16. obj.print();  
17. obj.show();  
18.  }  
19. }  
Test it Now
Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in java but it is possible by


interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But
it is supported in case of interface because there is no ambiguity as implementation is provided by the
implementation class. For example:
1. interface Printable{  
2. void print();  
3. }  
4.   
5. interface Showable{  
6. void print();  
7. }  
8.   
9. class testinterface1 implements Printable,Showable{  
10.   
11. public void print(){System.out.println("Hello");}  
12.   
13. public static void main(String args[]){  
14. testinterface1 obj = new testinterface1();  
15. obj.print();  
16.  }  
17. }  
Test it Now
Hello

As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class A, so there is no ambiguity.

Interface inheritance
A class implements interface but one interface extends another interface .

1. interface Printable{  
2. void print();  
3. }  
4. interface Showable extends Printable{  
5. void show();  
6. }  
7. class Testinterface2 implements Showable{  
8.   
9. public void print(){System.out.println("Hello");}  
10. public void show(){System.out.println("Welcome");}  
11.   
12. public static void main(String args[]){  
13. Testinterface2 obj = new Testinterface2();  
14. obj.print();  
15. obj.show();  
16.  }  
17. }  
Test it Now
Hello
Welcome
Q) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example: Serializable,
Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may
perform some useful operation.

1. //How Serializable interface is written?  
2. public interface Serializable{  
3. }  

Nested Interface in Java


Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the
nested classes chapter. For example:

1. interface printable{  
2.  void print();  
3.  interface MessagePrintable{  
4.    void msg();  
5.  }  
6. }  

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

1. //Creating interface that has 4 methods  
2. interface A{  
3. void a();//bydefault, public and abstract  
4. void b();  
5. void c();  
6. void d();  
7. }  
8.   
9. //Creating abstract class that provides the implementation of one method of A interface  
10. abstract class B implements A{  
11. public void c(){System.out.println("I am C");}  
12. }  
13.   
14. //Creating subclass of abstract class, now we need to provide the implementation of rest of the metho
ds  
15. class M extends B{  
16. public void a(){System.out.println("I am a");}  
17. public void b(){System.out.println("I am b");}  
18. public void d(){System.out.println("I am d");}  
19. }  
20.   
21. //Creating a test class that calls the methods of A interface  
22. class Test5{  
23. public static void main(String args[]){  
24. A a=new M();  
25. a.a();  
26. a.b();  
27. a.c();  
28. a.d();  
29. }}  
Test it Now

Output:

I am a
I am b
I am c
I am d

Static and Non-Static Method

Method of a class can be declared in two different ways

1. Non-static methods
2. Static methods

Difference between non-static and static Method


Non-Static method Static method
These method never be preceded by static keyword These method always preceded by static keyword
Example: Example:
void fun1() static void fun2()
1{ {
...... ......
...... ......
} }
Memory is allocated multiple time whenever
2 Memory is allocated only once at the time of loading.
method is calling.
It is specific to an object so that these are also These are common to every object so that it is also known as
3
known as instance method. member method or class method.
These methods always access with object reference These property always access with class reference
Syntax: Syntax:
4
Objref.methodname(); className.methodname();
If any method wants to be execute multiple time that If any method wants to be execute only once in the program
5
can be declare as non static. that can be declare as static .

In some cases static methods not only can access with class reference but also can access with object reference.

Example of Static and non-Static Method

import java.util.scanner;
class A
{
String name;
void f1()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter name: ");
Name=s.next();
System.out.println("Hello"+name);
}
static void f2()
{
System.out.println("You are a student");
}
}
class Persion
{
public static void main(String args[])
{
A oa1=new A();
oa1.f1();
A.f2();
A oa2=new A();
oa2.f1();
A.f2();
}
}

Output

Enter name: abcd


Hello abcd
You are a student
Enter name: xyz
Hello xyz
You are a student

Write a java program to achieve static and non-static variable.

class Student
{
int roll_no;
float marks;
String name;
static String College_Name=”ITM”;
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.marks=65.8f;
s1.name="abcd";
System.out.println(S1.roll_no);
System.out.println(S1.marks);
System.out.println(S1.name);
System.out.println(Student.College_Name);
//or System.out.println(S1. College_Name); but first is use in real time.
Student S2=new Student();
s2.roll_no=200;
s2.marks=75.8f;
s2.name="zyx";
System.out.println(S2.roll_no);
System.out.println(S2.marks);
System.out.println(S2.name);
System.out.println(Student.College_Name);
}
}

Note: Without creating object reference properties of class can be access or program can be executed by declaring
static properties.

Static block

Which will be executed by the JVM before execution of main method?

Syntax

static
{
........
........
}

Note: In real time application static block can be used whenever we want to execute any instructions or statements
before execution of main method.

class staticDemo
{
static
{
System.out.println(“Execution of program is going to started”);
}
public static void main(String args[])
{
System.out.println(“This is main()”);
}
}

Output

Execution of program is going to be started


This is main()
class StaticDemo
{
static
{
System.out.println("Execution of program is going to started");
}
}

Output

Execution of program is going to started


Exception is thread “main” java.lang.no-suchmethodError:Main

Following table represent how the static and non-static properties are accessed in the different static or non-static
method of same class or other class.

Write a java program to represent accessing static and non-static properties.


class A
{
int y;
void f2()
{
System.out.println("Hello f2()");
}
}
class B
{
int z;
void f3()
{
System.out.println("Hello f3()");
A a1=new A();
a1.f2();
}
}
class Sdemo
{
static int x;
static void f1()
{
System.out.println("Hello f1()");
}
public static void main(String[] args)
{
x=10;
System.out.println("x="+x);
f1();
System.out.println("Hello main");
B b1=new B();
b1.f3();
}
}

Static and Non-Static Variable

The variable of any class are classified into two types

1. Non-static or instance variable


2. Static or class variable

Difference between non-static and static variable


Non-static variable Static variable
These variable should not be preceded by any static
These variables are preceded by static keyword. Example:
keyword Example: class A
1 class A {
{ static int b;
int a; }
}
Memory is allocated for these variable whenever an Memory is allocated for these variable at the time of loading
2
object is created of the calss.
Memory is allocated multiple time whenever a new Memory is allocated for these variable only once in the
3
object is created. program.
4 Non-static variable also known as instance variable Memory is allocated at the time of loading of class so that
while because memory is allocated whenever these are also known as class variable.
instance is created.
Static variable are common for every object that means there
5 Non-static variable are specific to an object memory location can be sharable by every object reference
or same class.
Non-static variable can access with object reference.
6 Syntax Static variable can access with class reference. Syntax:
Class_name.var_name
Obj_ref.var_name

Note: static variable not only can be access with class reference but also some time it can be accessed with object
reference.

Write a java program to achieve static and non-static variable.

class Student
{
int roll_no;
float marks;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.marks=65.8f;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.marks);
System.out.println(s1.name);
System.out.println(Student.College_Name);
//or System.out.println(s1. College_Name); but first is use in real time.
Student s2=new Student();
s2.roll_no=200;
s2.marks=75.8f;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.marks);
System.out.println(s2.name);
System.out.println(Student.College_Name);
}
}
Output:
100
65.8
abcd
ITM
200
75.8
zyx
ITM
Note: In the above example College_Name variable is commonly sharable by both S1 and S2 objects.

Abstract classes

We know that every java program must start with a concept of class that is without classes concept there is no java
program perfect.

In java programming we have two types of classes they are

1. Concrete classes
2. Abstract class
Concrete class

A concrete class is one which is containing fully defined methods. Fully defined methods or implemented method

Example:

class Test
{
void show()
{
---------
---------
}
void display()
{
---------
---------
}
}

Here test class is containing two defined method and object can be created directly.

Test t1=new Test();


t1.disp();
t1.show();

all the concrete classes of java contains specific feature and always deals with specific requirement which are
suitable for individual programmers.

It is not recommended to close concrete classes for dealing with common requirements which are suitable for
multiple programmers. If we choose concrete classes concept for dealing with common requirements than such
application will get the following limitations.

1. Application will take more amount of memory space (main memory).


2. Application execution time is more.
3. Application performance is decreased.

Hence to avoid there problem of concrete classes in dealing with common requirements it is recommended to java
programmer to use abstract classes.

Abstract classes

An abstract class is one which is containing some defined method + some undefined method. In java programming
undefined methods are known as unimplemented or abstract methods.
Definition of an abstract method

An abstract method is one which contains only declaration or prototype but it never contains body or definition. In
order to make any undefined method as abstract whose declaration is must be predefined by abstract.

abstract ReturnType methodName (List of formal parameter type if any)

example:

abstract void sum();


abstract void op(int, int);

Here abstract keyword always makes the jvm to understand the following points.

1. What a method can do, but it can’t understand


2. How a method can be done?

We know that every method of java belongs to a class including abstract methods.

If any class of java contains abstract method then the class is known as abstract class.

To make the class as abstract class, whose definition must be preceded by a keyword abstract.

Syntax for abstract class

abstract class ClassName


{
------------
------------
}
abstract ReturnType methodName
(List of formal parameter type if any);
{
------------
------------
}
abstract class Operation
{
--------------
--------------
abstract void sum();
abstract void op(int, int);
-----------
-----------
}

Here operation is one of the abstract class whose object can’t be created directly but it can be created indirectly.

Operation op=new operation(); // error

In general once the class is abstract whose object can’t be created directly but it can be created indirectly.

Write a java program which listed the concept of abstract classes or write a java program which will
compute sum of two integer and float.

//Adddemo.java
abstract class Aop
{
abstract void Sum();
} // Aop – abstract class
class Isum extends Aop
{
Int a,b,c;
void sum()
{
a=10;
b=20;
c=a+b;
System.out.println("int sum="+c);
}
} // Sum – Derived class
class Fsum extends Aop
{
float a,b,c;
void sum()
{
a=10.75f;
b=20.23f;
c=a+b;
System.out.println("float sum="+c);
}
} // fsum -- derived class
class AddDemo
{
public static void main(String args[])
{
// Aop ao=new Aop(); // invalid because Aop is abstract
Aop ao=new iSum(); //indirect object
ao.Sum();
ao=new Fsum();// indirect object
ao.Sum();
}
}

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class. Before learning
abstract class, let's understand the abstraction first.
Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality
to the user.

Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction

There are two ways to achieve abstraction in java

Abstract class (0 to 100%)


Interface (100%)

Abstract class

A class that is declared as abstract is known as abstract class. It needs to be extended and
its method implemented. It cannot be instantiated.
Syntax to declare the abstract class

abstract class <class_name>{}

abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Syntax to define the abstract method

abstract return_type <method_name>();//no braces{}

Example of abstract class that have abstract method

In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}

public static void main(String args[]){


Bike obj = new Honda();
obj.run();
}
}

Output:running safely..

Understanding the real scenario of abstract class

In this example, Shape is the abstract class, its implementation is provided by the Rectangle
and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the
end user) and object of the implementation class is provided by the factory method.

A factory method is the method that returns the instance of the class. We will learn about
the factory method later.

In this example, if you create the instance of Rectangle class, draw method of Rectangle
class will be invoked.

abstract class Shape{


abstract void draw();
}

class Rectangle extends Shape{


void draw(){System.out.println("drawing rectangle");}
}

class Circle extends Shape{


void draw(){System.out.println("drawing circle");}
}

class Test{
public static void main(String args[]){
Shape s=new Circle();
//In real scenario, Object is provided through factory method
s.draw();
}
}

Output:drawing circle

Abstract class having constructor, data member, methods etc.


Note: An abstract class can have data member, abstract method, method body, constructor and
even main() method.

//example of abstract class that have method body


abstract class Bike{
abstract void run();
void changeGear(){System.out.println("gear changed");}
}

class Honda extends Bike{


void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Output:running safely..
gear changed

//example of abstract class having constructor, field and method


abstract class Bike
{
int limit=30;
Bike(){System.out.println("constructor is invoked");}
void getDetails(){System.out.println("it has two wheels");}
abstract void run();
}

class Honda extends Bike{


void run(){System.out.println("running safely..");}

public static void main(String args[]){


Bike obj = new Honda();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
}

Output:constructor is invoked
running safely..
it has two wheels
30

Rule: If there is any abstract method in a class, that class must be abstract.

class Bike{
abstract void run();
}

Output:compile time error

Rule: If you are extending any abstact class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.

interface A{
void a();
void b();
void c();
void d();
}

abstract class B implements A{


public void c(){System.out.println("I am C");}
}

class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

class Test{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

Output:I am a
I am b
I am c
I am d

abstract class Shape{


abstract void draw();
}

class Rectangle extends Shape{


void draw(){System.out.println("drawing rectangle");}
}

class Circle extends Shape{


void draw(){System.out.println("drawing circle");}
}

class Test{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
}
}

Points to be remember about abstract class

1. Abstract class of java always contains common features


2. Every abstract class participate in interface
3. Abstract classes definitions should not be made as final because abstract classes always participate in
inheritance classes.
4. An object of abstract class can’t be created directly but it can be created indirectly.

 An object of abstract class = An object of its sub class


 An b=object of abstract class = An object of that class which extends the abstract class
 An object of sub class of abstract class = an object of abstract class.

All the abstract classes of java makes use of polymorphism along with method overriding for business logic
development and makes use of dynamic binding for execution logic.

The advantage of abstract classes are:


1. Less memory space for the application
2. Less execution time
3. More performance

In abstract classes we have only abstract instance method but not containing abstract static methods because every
instance method is ment for performing repeated operation where as static method is ment for performing one time
operations in other word every abstract method is instance but not static.

It is not recommended to the java programmer to write any programmer defined parameterized constructor and
default constructor because direct referencing is not possible.

An object of an abstract class can be declared but it can’t be referenced directly and it can be referenced indirectly
with respect to concrete sub class of abstract class.

Example:

Ac Ao1; // valid because it is Declaration


Ao1=new Ac(); // invalid because it is direct referencing of Ac
Ao1=new Isum(); // valid because it is indirect referencing of
//concrete sub class of abstract class the class which
//contains main() method may or may not be abstract.

Abstract base class and abstract derived class

Definition of abstract base class

An abstract base class is one which is containing physical representation of abstract methods which are inherited by
various sub classes.

Definition of abstract derived class

An abstract derived class is one which is containing logic representation of abstract methods which are inherited
from abstract base class with respect to both abstract base class and abstract derived class one can’t create object s
directly but we can create there objects indirectly both abstract base class and abstract derived class are always
reusable by various sub classes.
When the derived class inherits multiple abstract method from abstract base class and if the derived class is not
defining at least one abstract method then the derived class is known as abstract derived class and whose definition
must be made as abstract by using abstract keyword. (When the derived class become an abstract derived class).

If the derived class defined all the abstract methods which are inherited form abstract Base class then the derived
class is known as concrete derived class.

Inner Classes

If one class is existing within another class is known as inner class or nested class

class Outerclass_name
{
......
......

class Innerclass_name1
{
.......
.......
}
class Innerclass_name1
{
......
......
}
......
}

The main purpose of using inner class


1. To provide more security by making those inner class properties specific to only outer class but not for
external classes.
2. To make more than one property of classes private properties.

Private is a keyword in java language, it is preceded by any variable that property can be access only within the
class but not outside of it (provides more security).

If more than one property of class wants to make as private properties than all can capped under private inner class.

class Outerclass_name
{
private class Innerclass_name
{
........
........ //private properties
}
}

Note:No outer class made as private class otherwise this is not available for JVM at the time of execution.

Rules to access properties of inner classes


 Inner class properties can be accessed in the outer class with the object reference but not directly.
 Outer class properties can be access directly within the inner class.
 Inner class properties can’t be accessed directly or by creating directly object.

Note: In special situation inner class property can be accessed in the external class by creating special objects with
the reference of its outer class.

class A //outer class


{
void fun1()
{
System.out.println("Hello fun1()"); // inner class properties should be access using
//object reference in outer class.
B ob=new B();
ob.x=10
System.out.println("x= "+ob.x);
ob.fun2();
}
void fun3() // outer class fun3()
{
System.out.println("Hello fun3()");
}
class B // inner class
{
int x; // inner class variable
void fun2() //inner class fun2()
{
System.out.println("Hello fun2()");
fun3(); //outer class properties can be access directly
}
}
}

class C // external class


{
void fun3()
{
System.out.println("Hello fun3()");
}
}

class IncDemo
{
public static void main(String args[])
{
A oa=new A();
oa.fun1();
C oc=new C();
oc.fun3();
}
}

Output

Hello fun1()
X=10
Hello fun2()
Hello fun3()

Accessing inner class properties in the external class

1. If inner class in non static the object can be created with the following syntax

class Outer_class
{
class Inner_class
{
.......
.......
}
.......
.......
}
class External_class
{
Outer_class.Inner_Class objectrefernce=new Outer_Class.External_Class();
}

2. If inner class is static the object reference can be created with the following syntax

class Outer_class
{
static class Inner_Class
{
.......
.......
}
}
class External_Class
{
Outer_class.Inner_Class objectrefernce=new Outer_Class.External_Class();
}
}

Example:

class A //Outer class


{
class B // non-static inner class
{
int x; //inner class variable
void fun1() //inner class fun1()
{
System.out.println("Hello fun1()");
}
}
static class C //static inner class
{
int y=20; // inner class variable
void fun2()
{
System.out.println("Hello fun2()");
}
}
}

class IncDemo
{
public static void main(String args[])
{
A.B ob=new A().new.B();
System.out.println(ob.x);
ob.fun1();
A.C oc=new A.C();
System.out.println(oc.y);
oc.fun2();
}
}
Relationship in Java

Type of relationship always makes to understand how to reuse the feature from one class to another class. In java
programming we have three types of relationship they are.

1. Is-A Relationship
2. Has-A Relationship
3. Uses-A Relationship

Is-A relationship

In Is-A relationship one class is obtaining the features of another class by using inheritance concept with extends
keywords.

In a IS-A relationship there exists logical memory space.

Example of Is-A Relation


class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}
}
Output:
Salary is: 30000.0
Bonous is: 2000.0

Has-A relationship

In Has-A relationship an object of one class is created as data member in another class the relationship between
these two classes is Has-A.

In Has-A relationship there existed physical memory space and it is also known as part of or kind of relationship.

Example of Has-A Relation


class Employee
{
float salary=30000;
}
class Developer extends Employee
{
float bonous=2000;
public static void main(String args[])
{
Employee obj=new Employee();
System.out.println("Salary is:"+obj.salary);
}
}
Output:
Salary is: 30000.0

Uses-A relationship

A method of one class is using an object of another class the relationship between these two classes is known as
Uses-A relationship.

As long as the method is execution the object space (o1) exists and once the method execution is completed
automatically object memory space will be destroyed.

Example of Has-A Relation


class Employee
{
float salary=30000;
}
class Salary extends Employee
{
void disp()
{
float bonous=1000;
Employee obj=new Employee();
float Total=obj.salary+bonous;
System.out.println("Total Salary is:"+Total);
}
}
class Developer
{
public static void main(String args[])
{
Salary s=new Salary();
s.disp();
}
}
Output:
Total Salary is: 31000.0

Note 1: The default relationship in java is Is-A because for each and every class in java there exist an implicit
predefined super class is java.lang.Object.

Note 2: The universal example for Has-A relationship is System.out (in System.out statement, out is an object of
printStream class created as static data member in another system class and printStream class is known as Has-A
relationship).

Note 3: Every execution logic method (main() ) of execution logic is making use of an object of business logic
class and business logic class is known as Uses-A relationship.

Static Variables & Static Methods

static method
• It is a method which belongs to the class and not to the object(instance)
• A static method can access only static data. It can not access non-static data (instance variables)
• A static method can call only other static methods and can not call a non-static method from it.
• A static method can be accessed directly by the class name and doesn’t need any object
• Syntax : <class-name>.<method-name>
• A static method cannot refer to “this” or “super” keywords in anyway

• main method is static , since it must be be accessible for an application to run , before any instantiation takes
place.

class Bird
{
int age;
int wings;
void fly()
{
System.out.println("They fly to full fill natural activities");
}
static void sing()
{
System.out.println("Only Some Birds will Sing");
}
}
class MyBird
{
public static void main(String args[])
{
Bird Pigeon=new Bird();
Pigeon.age=5;
Pigeon.wings=2;
System.out.println("Pigeon's Age="+Pigeon.age);
System.out.println("Pigeon's wings="+Pigeon.wings);
Pigeon.fly();
Bird.sing();
}
}

class Bird1
{
int age;
int wings;
static int count;
Bird1()
{
count=5;
}
void fly()
{
System.out.println("They fly to full fill natural activities");
}
static void sing()
{
System.out.println("Only Some Birds will Sing");
}
}
class MyBird
{
public static void main(String args[])
{
Bird1 Pigeon=new Bird1();
Pigeon.age=5;
Pigeon.wings=2;
System.out.println("Pigeon's Age="+Pigeon.age);
System.out.println("Pigeon's wings="+Pigeon.wings);
System.out.println("Count of Birds="+Bird1.count);
Pigeon.fly();
Bird1.sing();

}
}

static variable
• It is a variable which belongs to the class and not to
object(instance)
• Static variables are initialized only once , at the start of the execution . These variables will be initialized
first, before the initialization of any instance variables
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and doesn’t need any object
• Syntax : <class-name>.<variable-name>

How Access Specifiers effect Inheritance


There are four Access Specifiers in Java
1. Public: When a member of a class is modified by public specifier, it can be accessed by any other code.
2. Protected: Protected is only applicable in case of Inheritance. When a member of a class is modified by
protected, it can only be accessed by the members of its class or subclass.
3. Private: A member of a class which is modified by private specifier, can only be accessed by the member of its
class.
4. Default: When you don't specify a access specifier to a member, Java automatically specifies a default. And the
members modified by default can only be accessed by any other code in the package, but can't be accessed outside
of a package.
Restricting Inheritance
I hope you have learned how to implement various types of inheritance in Java. Now, what to do if you want that no
other classes can extends a desired one, which means restricting inheritance.
You just need to use the "final" keyword as follows:
final class myclass{
// Insert code here
}
Now, "myclass" can't be extended by any other class.
Polymorphism refers to "having many forms" or more than one form. In OOPs, it is the ability to create a variable,
function or object which has many form. In the Java Programming Language, two types of Polymorphism are there:
1. Compile Time Polymorphism
Also known as Early Binding or Static Binding. In this case, compiler identifies that which polymorphic form is to
be executed at compile time. Method overloading and Operator overloading are good example of Compile Time
Polymorphism. The following written program demonstrates Compile Time Polymorphism.
Method Overloading
When a class contains methods of the same name but of different number of parameters, is called Method
Overloading.
Code
public class MehodOverloading {

public static void main(String[] args) {


MyClass obj = new MyClass();
int sum = obj.Add(4, 5);
System.out.println(sum);
sum = obj.Add(4, 5, 7);
System.out.println(sum);
sum = obj.Add(4, 5, 7, 9);
System.out.println(sum);
}
}

class MyClass {

public int Add(int a, int b) {


return a + b;
}

public int Add(int a, int b, int c) {


return a + b + c;
}

public int Add(int a, int b, int c, int d) {


return a + b + c + d;
}
}
Output
9
16
25
2. Runtime Polymorphism
Also known as Late Binding or Virtual Method Invocation or Dynamic Binding. In Runtime Polymorphism, the
compiler identifies which polymorphic form is to be executed at runtime but not in compile time, is called Runtime
Polymorphism. Method overriding is a well known example of Runtime Polymorphism.
Method Overriding
Method Overriding takes place, if Inheritance exists and a super class and subclass have the method of same
signature. Signature refers to access specifier, return type, name, parameters(number, type & order) & throws
clause of the method. Then, the method of the subclass overrides the method of the superclass. As demonstrated in
the following written program.
Code
public class MethodOverriding {

public static void main(String[] args) {


ClassB obj = new ClassB();
obj.Display(10, 15);
}
}

class ClassA {

public void Display(int a, int b) {


a += 5;
b += 7;
System.out.println("Sum is " + (a + b));
}
}

class ClassB extends ClassA {

public void Display(int a, int b) {


System.out.println("Sum is " + (a + b));
}
}
Output
Sum is 25
In this case, the method of ClassB overrides the method of ClassA. The method of ClassA is said to be Overridden.
To call the overridden method, you need to use the super keyword as demonstrated in the following program.
Code
public class MethodOverriding {

public static void main(String[] args) {


ClassB obj = new ClassB();
obj.Display(10, 15);
}
}

class ClassA {

public void Display(int a, int b) {


a += 5;
b += 7;
System.out.println("Sum is " + (a + b));
}
}

class ClassB extends ClassA {

public void Display(int a, int b) {


System.out.println("Sum is " + (a + b));
super.Display(a, b);
}
}
Output
Sum is 25
Sum is 37

In the above program, the "super" keyword is used to call the member of the super class. The "super" keyword is
also used to call the constructor of the super class, demonstrated in the following program.

Using "super" keyword to call the constructor of super class


Code
public class SuperKeyword {

public static void main(String[] args) {


ClassC obj = new ClassC();
obj.show();
}
}

class ClassA {

static int a;
static int b;

ClassA() {
a = 7;
b = 8;
}
}

class ClassB extends ClassA {

ClassB() {
super();
}
}

class ClassC extends ClassB {


ClassC() {
super();
}

public void show() {


System.out.println("Sum is " + (a + b));
}
}
Output
Sum is 15
Note: Call to super must be first statement in constructor.

Hidden Method

Consider the case of method overriding, the method of the superclass is the overridden method. In the case of
Method hiding, the concept is the same but methods in both classes are static. Now, the method of the subclass
hides the method of the superclass. So the method of the superclass is called a Hidden Method. To call the hidden
method, you need to provide the 'class reference', instead of using the super keyword. For example:

Code
public class MethodOverriding {

public static void main(String[] args) {


ClassB obj = new ClassB();
obj.Display(10, 15);
}
}

class ClassA {

public static void Display(int a, int b) {


a += 5;
b += 7;
System.out.println("Sum is " + (a + b));
}
}

class ClassB extends ClassA {

public static void Display(int a, int b) {


System.out.println("Sum is " + (a + b));
ClassA.Display(a, b);
}
}
Output
Sum is 25
Sum is 37

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains
one more object named address, which contains its own informations such as city, state, country, zipcode etc.
as given below.

1. class Employee{  
2. int id;  
3. String name;  
4. Address address;//Address is a class  
5. ...  
6. }  

In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Why use Aggregation?


 For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

1. class Operation{  
2.  int square(int n){  
3.   return n*n;  
4.  }  
5. }  
6.   
7. class Circle{  
8.  Operation op;//aggregation  
9.  double pi=3.14;  
10.     
11.  double area(int radius){  
12.    op=new Operation();  
13.    int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).  
14.    return pi*rsquare;  
15.  }  
16.   
17.      
18.     
19.  public static void main(String args[]){  
20.    Circle c=new Circle();  
21.    double result=c.area(5);  
22.    System.out.println(result);  
23.  }  
24. }  
Test it Now
Output:78.5

When use Aggregation?


 Code reuse is also best achieved by aggregation when there is no is-a relationship.
 Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the
objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation

In this example, Employee has an object of Address, address object contains its own informations such as
city, state, country etc. In such case relationship is Employee HAS-A address.

Address.java
1. public class Address {  
2. String city,state,country;  
3.   
4. public Address(String city, String state, String country) {  
5.     this.city = city;  
6.     this.state = state;  
7.     this.country = country;  
8. }  
9.   
10. }  

Emp.java
1. public class Emp {  
2. int id;  
3. String name;  
4. Address address;  
5.   
6. public Emp(int id, String name,Address address) {  
7.     this.id = id;  
8.     this.name = name;  
9.     this.address=address;  
10. }  
11.   
12. void display(){  
13. System.out.println(id+" "+name);  
14. System.out.println(address.city+" "+address.state+" "+address.country);  
15. }  
16.   
17. public static void main(String[] args) {  
18. Address address1=new Address("gzb","UP","india");  
19. Address address2=new Address("gno","UP","india");  
20.   
21. Emp e=new Emp(111,"varun",address1);  
22. Emp e2=new Emp(112,"arun",address2);  
23.       
24. e.display();  
25. e2.display();  
26.       
27. }  
28. }  
Test it Now
Output:111 varun
gzb UP india
112 arun
gno UP india
download this example

Exception Handing

Exceptions are the error messages


which are displayed when an error occurs which
interrupts the normal flow of execution of the code.
1. Checked Exceptions - These are the exceptions which occur during the compile time of the program. The
compiler checks at the compile time that whether the program contains handlers for checked exceptions or not.

Here is the list of checked exceptions.


NoSuchFieldException
InstantiationException
IllegalAccessException
ClassNotFoundException
NoSuchMethodException
CloneNotSupportedException
InterruptedException

2. Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the runtime of the
program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is
inherited from java.lang.Exception class. Here is the list of unchecked exceptions.
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
ClassCastException
ArithmeticException
NullPointerException
IllegalStateException
SecurityException

4. Error - The errors in java are external to the application. These are the exceptional conditions that could not
be usually anticipated by the application and also could not be recovered from. Error exceptions belong to Error and
its subclasses are not subject to the catch or Specify requirement.

Suppose a file is successfully opened by an application for input but due to some system malfunction could not be
able to read that file then the java.io.IOError would be thrown. This error will cause the program to terminate but if
an application wants then the error might be caught. An Error indicates serious problems that a reasonable
application should not try to catch. Most such errors are abnormal conditions.

Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions.

class Test9
{
public static void main(String[]args)
{
int a=100;
int b=0;
int c=a/b;
System.out.println("How Are U ToDay");
System.out.println("c="+c);
System.out.println("This Will Not Be Printed");
}
}

Exception handling in java is possible through Five keywords


try,catch,thow,throws,finally

try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed after try block ends
}

try:
The code that has to be executed will be present
in try block

try
{
code
}

try-catch

try
{

}
catch (ExceptionType name)
{

A catch block encloses code that will be executed when an exception is thrown in try block. A catch block must
immediately follow try block. The try and catch block are bonded together and we must not separate them by
putting statement between two blocks. We can’t have just a try block by itself. If a try block throws several
exceptions we can put several catch block after try block to handle them.

class Test9
{
public static void main(String[]args)
{
int a=100;
int b=0;
try
{
System.out.println("How Are U ToDay");
int c=a/b;
System.out.println("c="+c);
System.out.println("This Will Not Be Printed");
}catch(ArithmeticException e)
{
System.out.println("Not possible");
}
}
}

try-catch-finally

try
{

}
catch (ExceptionType name)
{

}
finally
{

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an
unexpected exception occurs. But finally is useful for more than just exception handling — it allows the
programmer to avoid having clean up code accidentally bypassed by a return, continue, or break. Putting clean up
code in a finally block is always a good practice, even when no exceptions are anticipated.

Each try block must always be followed by at least one block that is either catch or finally block.

class Test9
{
public static void main(String[]args)
{
int a=100;
int b=0;
try
{
int c=a/b;
System.out.println("How Are U ToDay");
System.out.println("c="+c);
System.out.println("This Will Not Be Printed");
}
finally
{
System.out.println("Its Not possible");
}
}
}
class Test9
{
public static void main(String[]args)
{
int a=100;
int b=0;
try
{
int c=a/b;
System.out.println("How Are U ToDay");
System.out.println("c="+c);
System.out.println("This Will Not Be Printed");
}catch(ArithmeticException e)
{
System.out.println("Not Able To Divide");
}
finally
{
System.out.println("Its Not possible");
}
}
}

throw: Throws the exceptions explicitly

throws: Specifies the list of exceptions that can be thrown by a method

User Defined Exceptions:

User defined exceptions are those which are defined by the programmer for his own purpose.All excpetions
are
derived from the base class called Exception which is present
in java.lang package.

User defined Exception in java


In this post, we'll see how to defined custom exceptions in java. We'll also see an example of user
defined exception that elaborate more detail or how it is helpful in giving user friendly message to the
user.

Java has built-in support for exceptions. 


The Java language supports exception handling in the form of following keywords

 throw
 throws
 try
 catch
 finally

In most situations or cases, it will be sufficient to throws exception that are already provided in the
Java library. For example, if you’re checking for the validity of the arguments passed to a public
function, and you find them to be null or out of expected range, you can throw an
IllegalArgumentException. 
However, for most non-trivial applications, it will be necessary for you to develop your own exception
classes (custom exceptions) to indicate exceptional conditions.

Basic Exception hierarchy 
The basic syntax of exception handling-related keywords
How do you define a custom exception?
There are two options: you can extend

 Exception
 RuntimeException

If you want to force the users of your custom exception to handle the exception, then you can extend
your exception class from the Exception class, which will make your custom exception a checked
exception.

If you want to give flexibility to the users of your custom exception, and leave it to the users of your
exception to decide if they want to handle the exception or not, you can derive your exception from
the RuntimeException class.

So it is a design choice that you make to choose the base class of your custom exception.

How about extending the Throwable or Error class for custom exceptions?
 The Throwable class is too generic to make it the base class of your exception, so it is not
recommended.
 The Error class is reserved for fatal exceptions that the JVM can throw (such as
StackOverflowError), so it is not advisable to make this the base class of your exception

For extending from a base class, you need to see what methods the base class provides.
In this case, you want to create a custom exception by extending the Exception or RuntimeException
classes. Since the Exception class is the base class of the RuntimeException class, it is sufficient to
know the members of the Exception class.

Member Short description


Exception() Default constructor of the Exception class with no additional
information on the exception.
Exception(String) Constructor that takes a detailed information string about the constructor as
an argument.
Exception(String, In addition to a detailed information string as an argument, this exception
Throwable) constructor takes the cause of the exception (which is another exception) as
an argument.
Exception(Throwable) Constructor that takes the cause of the exception as an argument
String getMessage() Returns the detailed message
Throwable getCause() Returns the cause of the exception
Throwable[] Returns the list of suppressed exceptions as an array.
getSuppressed()
void printStackTrace() Prints the stack trace (i.e., the list of method calls with relevant line
numbers) to the console (standard error stream). If the cause of an
exception (which is another exception object) is available in the exception,then that information will
also be printed. Further, if there are any suppressed exceptions, they are also printed.

For illustrating how to create your own exception classes,we'll create a custom exception
InvalidUserInputException.
ample Output
Type an integer on the console
asdsa
Wrapping exception and throwing

Exception is of type:InvalidUserInputException: Invalid integer value entered


Original caught exception is of type java.util.InputMismatchException

In this InvalidUserInputException class, you did not introduce any new fields but you can add any fields
if necessary. This is also a simple custom exception where the constructors simply call the base class
versions of the same constructor type.

In this code, we use InvalidUserInputException just like any other exception already defined in the
Java library. You are catching the InvalidUserInputException thrown from the readIntFromConsole()
method in the main() method.
Since the cause of InvalidUserInputException is InputMismatchException, this exception name is
printed in the console as a fully qualified name, java.util.InputMismatchException. You can think of
InputMismatchException causing InvalidUserInputException; these two exceptions are known as
chained exceptions.

One point to remember is here that as we have extended RuntimeException we are giving flexibility to


the users of your custom exception, and leave it to the users of your exception to decide if they want
to handle the exception or no.

I want you to try to create the same exception class by extending Exception class and see how it differ
from the above exception .

If you know anyone who has started learning java, why not help them out! Just share this post with
them. 
Thanks for studying today!...

//user defined exception

class MyException extends Exception


{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a);
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)


{
try
{
sum(11, 10);
}
catch(MyException me)
{
System.out.println(me);
}
}
}

import java.io.*;
import java.util.*;
class MyException extends Exception
{
private String nm="";
public String getMessage(String s)
{

nm=s;
return ("you are not permitted to enter inside "+nm);
}
}

public class ExcepDemo


{
public static void main(String args[])throws MyException,IOException
{

String temp="";

try
{
String str="amit";
System.out.println("Enter the your name");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
temp=br.readLine();

if(!temp.equals(str))
throw new MyException();
else
System.out.println("Welcome to Rose India");
}
catch(MyException e)
{
System.err.println(e.getMessage(temp));
}
catch(Exception e){
System.err.println(e);
}
}
}

Example:
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount


{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce following result:
Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
/* Exception handling Multiple catch block*/
class excep1
{
public static void main(String args[])
{
try
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a/b;
System.out.println(a+" / "+b+"="+c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero error occurred");
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Supply two arguments from the command line");
System.out.println(e);
}
catch(NumberFormatException e)
{
System.out.println("Not valid Integers");
System.out.println(e);
}
}
}

Output 1:

D:\java>javac excep1.java
D:\java>java excep1 6 2
6 / 2=3

Output 2:

D:\java>java excep1 6
Supply two arguments from the command line
java.lang.ArrayIndexOutOfBoundsException

Output 3:
D:\java>java excep1 2.5 3
Not valid Integers
java.lang.NumberFormatException: 2.5
D:\java>

-------------------------------------------------------------------------------------------------------------------------------------------

package com.hubberspot.exception.example;

class InvalidMonthException extends Exception


{
public String toString()
{
return "Invalid Month given";
}
}
class InvalidDayException extends Exception
{
public String toString()
{
return "Invalid Date given";
}
}
class UserExceptionDemo
{
public static void main(String[] args)
{
try
{
if(args.length < 3)
throw new NullPointerException();
else
{
int dd = Integer.parseInt(args[0]);
int mm = Integer.parseInt(args[1]);
int yy = Integer.parseInt(args[2]);
if(dd < 1 || dd > 31)
throw new InvalidDayException();
if(mm < 1 || mm > 12)
throw new InvalidMonthException();
System.out.println("Valid Input");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output 1: java UserExceptionDemo


java.lang.NullPointerException

Output 2: java UserExceptionDemo 24 6 2011


Valid Input

Output 3: java UserExceptionDemo 24 16 2012


Invalid Month given

Output 4: java UserExceptionDemo 31 2 2012


Invalid Date is given

-------------------------------------------------------------------------------------------------------------------------------------------
-

User Defined Exceptions

Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our
own exceptions in order to handle the various application specific errors that we might encounter. While defining
an user defined exception, we need to take care of the following aspects:

The user defined exception class should extend from Exception class.

The toString() method should be overridden in the user defined exception class in order to display meaningful
information about the exception.

Syntax:

class exceptionclassname extends Exception


{
exceptionclassname(parameter)
{

//statements
}

public String toString()


{
return String
}

The user defined exceptions must be explicitly thrown using the throw statement whose syntax is

throw ThrowableInstance

ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

Example:

For example the below program creates an user defined exception when the second argument is less than or
equal to zero

/* User defined exception class */


class myexception extends Exception
{
myexception(String mg)
{
super(mg);
}
}
class userexcep
{
public static void main(String args[])
{
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
try
{
if(b=0)
throw new myexception("Invalid Number");
float c=a/b;
System.out.println(a+" / "+b+"="+c);
}
catch(myexception e)
{
System.out.println("The second number should be greater than 0");
System.out.println(e.getMessage());
}
}
}

Output 1: (No exception)


D:\java>javac userexcep.java
D:\java>java userexcep 6 3
6 / 3=2.0

Output 2: (With Exception)

D:\java>java userexcep 6 0
The second number should be greater than 0
Invalid Number
D:\java>

---------------------------------------------------------------------------------------------------------------------

public class MyException extends Exception{

public MyException(){
super();
}
public MyException(String expSrt){
super(expSrt);
}
public String toString(){
return "Exception: Age should be 18 to 35 years only";
}
}

public class MyApplication {


public static void main(String[] args) {
int age = 15;
try{
if(age < 18 || age > 35){
throw new MyException(); // Line 8
}else{
System.out.println("Valid to access the application");
}
}catch (Exception e) {
e.printStackTrace();
}

}
}

-------------------------------------------------------------------------------------------------------------------------------------------
import java.io.*;
class myException extends Exception
{ myException()
{ System.out.println("Error:Password too short");
}
myException(int n)
{ System.out.println("Error:Only adults can join");
}
}
class user_exception
{ public static void main(String s[])throws IOException,myException
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{ System.out.print("Enter user name : ");
String n=br.readLine();
System.out.print("Enter your password : ");
String m=br.readLine();
if(m.length() <6)
throw new myException();
System.out.print("Enter your age : ");
int o=Integer.parseInt(br.readLine());
if(o<18)
throw new myException(o);
}
catch(Exception e)
{ }
}
}

-------------------------------------------------------------------------------------------

NegativeAgeException.java

public class NegativeAgeException extends Exception {

private int age;

public NegativeAgeException(int age){


this.age = age;
}

public String toString(){


return "Age cannot be negative" + " " +age ;
}
}
public class CustomExceptionTest {

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

int age = getAge();

if (age < 0){


throw new NegativeAgeException(age);
}else{
System.out.println("Age entered is " + age);
}
}

static int getAge(){


return -10;
}
}

In the CustomExceptionTest class, the age is expected to be a positive number. It would throw the user defined
exception NegativeAgeException if the age is assigned a negative number.

At runtime, we get the following exception since the age is a negative number.

Exception in thread "main" Age cannot be negative -10


at tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)
import java.io.*;
import java.util.*;

class MyException extends Exception


{
private String nm="";
public String getMessage(String s)
{

nm=s;
return ("you are not permitted to enter inside "+nm);
}
}

public class ExcepDemo


{
public static void main(String args[])throws MyException,IOException
{

String temp="";

try
{
String str="amit";
System.out.println("Enter the your name");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
temp=br.readLine();

if(!temp.equals(str))
throw new MyException();
else
System.out.println("Welcome to Rose India");
}
catch(MyException e)
{
System.err.println(e.getMessage(temp));
}
catch(Exception e){
System.err.println(e);
}
}
}
Applet

Applet is a predefined class in java.applet package used to design distributed application. It is a client side

technology. Applets are run on web browser.

Advantage of Applet

 Applets are supported by most web browsers.

 Applets works at client side so less response time.


 Secured: No access to the local machine and can only access the server it came from.

 Easy to develop applet, just extends applet class.

 To run applets, it requires the Java plug-in at client side.

 Android, do not run Java applets.

 Some applets require a specific JRE. If it required new JRE then it take more time to download new
JRE.

Life cycle of applet

 init()

 start()

 stop

 destroy
init(): Which will be executed whenever an applet program start loading, it contains the logic to initiate the applet

properties.

start(): It will be executed whenever applet program starts running.

stop(): Which will be executed whenever applet window or browser is minimized.

destroy(): It will be executed whenever applet window or browser is going to be closed (at the time of destroying the

applet program permanently).

Design applet program

We can design our own applet program by extending applet class in the user defined class.

Syntax

class className extends Applet


{
......
// override lifecycle methods
......
}

Note: Whenever an applet program is running inti() and start() will be executed one after another but stop() and

destroy() will be executed if the browser is minimized and closed by the end user respectively.

Note: Applet program may or may not contain life cycle methods.


Running of applet programs

Applet program can run in two ways.

 Using html (in the web browser)

 Using appletviewer tool (in applet window)

Running of applet using html

In general no java program can directly execute on the web browser except markup language like html, xml etc.

Html support a predefined tag called <applet> to load the applet program on the browser window.

Syntax

<applet code="udc.class">
height="100px"
width="100px"
</applet>

Example of applet program to run applet using html


Java code, JavaApp.java

import java.applet.*;
import java.awt.*;
public class JavaApp extends Applet
{
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,30);
g.setFont(f);
setForeground(Color.red);
setBackground(Color.white);
g.drawString("Student",200,200);
}
}
Html code, myapplet.html

<html>
<title> AppletEx</Title>
<body>
<applet code="JavaApp.class"
height="70%"
width="80%">
</applet>
</body>
</html>

If applet code not run on browser then allow blocked contents.

Running of applet using appletviewer

Some browser does not support <applet> tag so that Sun MicroSystem was introduced a special tool

called appletviewer to run the applet program.

In this Scenario java program should contains <applet> tag in the commented lines so that appletviewer tools can

run the current applet program.


Example of Applet

import java.applet.*;
import java.awt.*;

/*<applet code="LifeApp.class" height="500",width="800">


</applet>*/

public class LifeApp extends Applet


{
String s= " ";
public void init()
{
s=s+ " int ";
}
public void start()
{
s=s+ "start ";
}
public void stop()
{
s=s+ "stop ";
}
public void destroy()
{
s=s+ " destory ";
}
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,30);
setBackgroundColor(Color."red");
g.setFont(f);
g.drawString(s,200,250);
}
}
Execution of applet program

javac LifeApp.java

appletviewer LifeApp.java

Note: init() always execute only once at the time of loading applet window and also it will be executed if applet is

restarted.

AWT

Graphical User Interface

Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying
Operating System also offers GUI via window,frame,Panel, Button, Textfield, TextArea, Listbox, Combobox,
Label, Checkbox etc. These all are known as components. Using these components we can create an interactive
user interface for an application.

GUI provides result to end user in response to raised events.GUI is entirely based events. For example clicking over
a button, closing a window, opening a window, typing something in a textarea etc. These activities are known as
events.GUI makes it easier for the end user to use an application. It also makes them interesting.

Basic Terminologies
Term Description
Component is an object having a graphical representation that
Component
can be displayed on the screen and that can interact with the
user. For examples buttons, checkboxes, list and scrollbars of
a graphical user interface.
Container object is a component that can contain other components.Components added to a container
are tracked in a list. The order of the list will define the components' front-to-back stacking order within
Container
the container. If no index is specified when adding a component to a container, it will be added to the
end of the list.
Panel Panel provides space in which an application can attach any other components, including other panels.
Window Window is a rectangular area which is displayed on the screen. In different window we can execute
different program and display different data. Window provide us with multitasking environment. A
window must have either a frame, dialog, or another window defined as its owner when it's constructed.
A Frame is a top-level window with a title and a border. The size of the frame includes any area
Frame designated for the border. Frame encapsulates window. It and has a title bar, menu bar, borders, and
resizing corners.
Canvas component represents a blank rectangular area of the screen onto which the application can
Canvas
draw. Application can also trap input events from the use from that blank area of Canvas component.

Examples of GUI based Applications

Following are some of the examples for GUI based applications.

 Automated Teller Machine (ATM)


 Airline Ticketing System

 Information Kiosks at railway stations

 Mobile Applications

 Navigation Systems

Advantages of GUI over CUI

 GUI provides graphical icons to interact while the CUI (Character User Interface) offers the simple text-
based interfaces.
 GUI makes the application more entertaining and interesting on the other hand CUI does not.

 GUI offers click and execute environment while in CUI every time we have to enter the command for a
task.

 New user can easily interact with graphical user interface by the visual indicators but it is difficult in
Character user interface.

 GUI offers a lot of controls of file system and the operating system while in CUI you have to use commands
which is difficult to remember.

 Windows concept in GUI allow the user to view, manipulate and control the multiple applications at once
while in CUI user can control one task at a time.

 GUI provides multitasking environment so as the CUI also does but CUI does not provide same ease as the
GUI do.

 Using GUI it is easier to control and navigate the operating system which becomes very slow in command
user interface. GUI can be easily customized.
Every user interface considers the following three main aspects:

 UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT provides a
huge list of widely used and common elements varying from basic to complex which we will cover in this
tutorial.
 Layouts: They define how UI elements should be organized on the screen and provide a final look and feel
to the GUI (Graphical User Interface). This part will be covered in Layout chapter.

 Behavior: These are events which occur when the user interacts with UI elements. This part will be covered
in Event Handling chapter.

Every AWT controls inherits properties from Component class.

AWT classes.
Class Description

AWTEvent Encapsulates AWT events.

AWTEventMulticaster Dispatches events to multiple listeners.


The border layout manager. Border layouts use five
BorderLayout
components: North, South, East West, and Center.
Button Creates a push button control.

Canvas A blank, semantics-free window.


The card layout manager. Card layouts emulate index
CardLayout
cards. Only the one on top is showing.
Checkbox Creates a checkbox control.

CheckboxGroup Creates a group of check box controls.

CheckboxMenuItem Creates an on/off menu item.

Choice Creates a pop-up list.


Manages colors in a portable, platform-independent
Color
fashion.
Component An abstract superclass for various AWT components.
A subclass of Component that can hold other
Container
components.
Cursor Encapsulates events.

Dialog Creates a dialog window.


Specifies the dimentions of an object. The width is
Dimension
stored in width, and the height is stored in height.
Event Encapsulates events.

EventQueue Queues events.

FileDialog Creates a window from which a file can be selected.


The flow layout manager. Flow layout positions
FlowLayout
components left to right, top to bottom.
Font Encapsulates a type font.

FontMetrics Encapsulates various information related to a font. This


information helps you display text in a window.
Creates a standard window that has t title bar, resize
Frame
corners, and a menu bar.
Encapsulates the graphics context. This context is used
Graphics by the various output methods to display output in a
window.
GraphicsDevice Describes a graphics device such as a screen printer.
Describes the collection of a available Font and
GraphicsEnvironment
GraphicsDevice objects.
Defines various constraints relating to the
GridBagConstraints
GridBagLayout class.
The grid layout manager. Grid layout displays
GridLayout
components in a two-dimensional grid.
The grid bag layout manager. Grid bag layout displays
GridBagLayout components subject to the constraints specified by
GridBagConstraints.
Image Encapsulates graphical images.

Insets Encapsulates th borders of a container.

Label Creates a label that displays a string.


Creates a list from which the user can choose. Similar
List
to the standard Windows list box.
MediaTracker Manages media objects.

Menu Creates a pull-down menu.

MenuBar Creates a menu bar.


An abstract class implemented by various menu
MenuComponent
classes.
MenuItem Creates a menu item.

MenuShortcut Encapsulates a keyboard shortcut for a menu item.

Panel The simplest concrete subclass of Container.


Encapsulates a Cartesian co-ordinate pair, stored in x
Point
and y.
Polygon Encapsulates a polygon.

PopupMenu Encapsulates a pop-up menu.


PrintJob An abstract class that represents a print job.

Rectangle Encapsulates a rectangle.


Supports automated testing of AWT-based applications.
Robot
(Added by Java 2, v1.3)
Scrollbar Creates a scroll bar control.
A container that provides horizontal and/or vertical scroll
ScrollPane
bars for another component.
Contains the colors of GUI widgets such as windows,
SystemColor
scroll bars, text, and others.
TextArea Creates a multiline edit control.

TextComponent A superclass for TextArea and TextField.

TextField Creates a single-line edit control.

Toolkit Abstract class implemented by the AWT.


Creates a window with no frame, no menu bar, and no
Window
title.
Applet

Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web
browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are
some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the
web site more dynamic and entertaining. 

Advantages of Applet:

 Applets are cross platform and can run on Windows, Mac OS and Linux platform
 Applets can work all the version of Java Plugin
 Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security
approval
 Applets are supported by most web browsers
 Applets are cached in most web browsers, so will be quick to load when returning to a web page
 User can also have full access to the machine if user allows

Disadvantages of Java Applet:

 Java plug-in is required to run applet


 Java applet requires JVM so first time it takes significant startup time
 If applet is not already cached in the machine, it will be downloaded from internet and will take time
 Its difficult to desing and build good user interface in applets compared to HTML technology

Life Cycle of Applet: Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and
destroyed. Here are the lifecycle methods of an Applet: 

init(): This method is called to initialized an applet

start(): This method is called after the initialization of the applet.

stop(): This method can be called multiple times in the life cycle of an Applet.

destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.

init () method: The life cycle of an applet begins when the applet is first loaded into the browser and called the
init() method. The init() method is called only one time in the life cycle on an applet. The init() method is basically
called to read the PARAM tag in the html file. The init () method retrieve the passed parameter through the
PARAM tag of html file using get Parameter() method All the initialization such as initialization of variables and
the objects like image, sound file are loaded in the init () method .After the initialization of the init() method user
can interact  with the Applet and mostly applet contains the init() method.

Start () method: The start method of an applet is called after the initialization method init(). This method may be
called multiple times when the Applet needs to be started or restarted. For Example if the user wants to return to the
Applet, in this situation the start Method() of an Applet will be called by the web browser and the user will be back
on the applet. In the start method user can interact within the applet.

Stop () method:  The stop() method can be called multiple times in the life cycle of applet like the start () method.
Or should be called at least one time. There is only miner difference between the start() method and stop () method.
For example the stop() method is called by the web browser on that time When the user leaves one applet to go
another applet and the start() method is called on that time when the user wants to go back into the first program or
Applet.

destroy() method: The destroy() method is called  only one time in the life cycle of Applet like init() method. This
method is called only on that time when the browser needs to Shut down.

Creating First Applet Example: First of all we will know about the applet. An applet is a program written in java
programming language and embedded within HTML page. It runs on the java enabled web browser such as
Netscape navigator or Internet Explorer.

In this example you will see, how to write an applet program. Java source of applet is then compiled into java class
file and we specify the name of class in the applet tag of html page. The java enabled browser loads class file of
applet and run in its sandbox.

Here is the java code of program :


import java.applet.*;
import java.awt.*;

public class FirstApplet extends Applet{
  public void paint(Graphics g){
  g.drawString("Welcome in Java Applet.",40,20);
  }
}

Here i the HTML code of the program:

<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800" HEIGHT="500"></APPLET>
</BODY>
</HTML>

Applet Code

<applet code=ima1.class width=200 height=400></applet>

The App let's Canvas

Every applet has an area of the screen, called the canvas, in which it can create its display. The size of an
applet's canvas depends on the size of the applet.

Using the Coordinate System

You draw graphical images on the canvas by using coordinates that identify pixel locations.supports a
number of different mapping modes that determines how coordinates are calculated in a window.
Java is a fully machine independent language. Java program code can be embedded into the hypertext code
of any web page to add sound, animation, multimedia effects and much more to the page.

Html read only à .html file and .class files.

Applet viewer read only à .class file and .html file

Graphics

Package : Java.awt

Class: java.awt.Graphics
Note :The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto
components that are realized on various devices, as well as onto off-screen images.

Constructors of Graphics Class


Name Description
Graphics() This constructor creates instance of Graphics class .

Methods of Panel Class


Method Description
create()
This method create the object of Graphics class which is
the copy of another Graphics object.
draw3DRect(int x, int y, int width,
int height, boolean raised) This method draw a 3-D outline of the rectangle.
drawArc(int x, int y, int width, This method draw outline of circular and elliptical
int height, int startAngle, int arcAngle) rectangle.
drawBytes(byte[] data, int offset, This method draw the specified String at the specified
int length, int x, int y) position.
drawChars(char[] data, int offset,
int length, int x, int y) This method draw the character at specific position.
drawImage(Image img, int x, int y,
Color bgcolor, ImageObserver observer) This method draw image at specific position.
drawLine(int x1, int y1, int x2,
int y2) This method draw line with specified width and height.
drawOval(int x, int y, int width,
int height) This method draw Oval with specified width and height.
drawPolygon(int[] xPoints,
int[] yPoints, int nPoints) This method draw Polygon .
drawRect(int x, int y, int width, This method draw Rectangle with specified width and
int height) height.
drawRoundRect(int x, int y, int width, This method draw Round Rectangle with specified width
int height, int arcWidth, int arcHeight) and height.
drawString (AttributedCharacterIterator This method draw String with specified width and
iterator, int x, int y) height.
fill3DRect(int x, int y, int width, This method draw a filled rectangle with specified width
int height, boolean raised) and height.
fillOval(int x, int y, int width, This method draw a filled Oval with specified width and
int height) height.
setColor(Color c) This method sets the color.
setFont(Font font) This method sets the font.

Example :
view plaincopy to clipboardprint?
1. mport java.applet.Applet;  
2. import java.awt.*;  
3.   
4. public class GraphicsDemo extends Applet{  
5.   
6. public void paint(Graphics g){  
7. g.setColor(Color.red);  
8. g.drawString("Welcome",50, 50);  
9. g.drawLine(20,30,20,300);  
10. g.drawRect(70,100,30,30);  
11. g.fillRect(170,100,30,30);  
12. g.drawOval(70,200,30,30);  
13.   
14. g.setColor(Color.pink);  
15. g.fillOval(170,200,30,30);  
16. g.drawArc(90,150,30,30,30,270);  
17. g.fillArc(270,150,30,30,0,180);  
18.   
19. }  
20. }  

1. import java.awt.*;  
2. import java.applet.*;  
3.   
4.   
5. public class DisplayImage extends Applet {  
6.   
7.   Image picture;  
8.   
9.   public void init() {  
10.     picture = getImage(getDocumentBase(),"sonoo.jpg");  
11.   }  
12.     
13.   public void paint(Graphics g) {  
14.     g.drawImage(picture, 30,30, this);  
15.   }  
16.       
17.   }

1. import java.awt.*;  
2. import java.applet.*;  
3. public class AnimationExample extends Applet {  
4.   
5.   Image picture;  
6.   
7.   public void init() {  
8.     picture =getImage(getDocumentBase(),"bike_1.gif");  
9.   }  
10.     
11.   public void paint(Graphics g) {  
12.     for(int i=0;i<500;i++){  
13.       g.drawImage(picture, i,30, this);  
14.   
15.       try{Thread.sleep(100);}catch(Exception e){}  
16.     }  
17.   }  
18. }  

1. import java.applet.*;  
2. import javax.swing.*;  
3. import java.awt.event.*;  
4. public class EventJApplet extends JApplet implements ActionListener{  
5. JButton b;  
6. JTextField tf;  
7. public void init(){  
8.   
9. tf=new JTextField();  
10. tf.setBounds(30,40,150,20);  
11.   
12. b=new JButton("Click");  
13. b.setBounds(80,150,70,40);  
14.   
15. add(b);add(tf);  
16. b.addActionListener(this);  
17.   
18. setLayout(null);  
19. }  
20.   
21. public void actionPerformed(ActionEvent e){  
22. tf.setText("Welcome");  
23. }  
24. }  
In the above example, we have created all the controls in init() method because it is invoked only once.

myapplet.html
1. <html>  
2. <body>  
3. <applet code="EventJApplet.class" width="300" height="300">  
4. </applet>  
5. </body>  
6. </html>  

1. import java.awt.*;  
2. import java.awt.event.*;  
3. import java.applet.*;  
4. public class MouseDrag extends Applet implements MouseMotionListener{  
5.   
6. public void init(){  
7. addMouseMotionListener(this);  
8. setBackground(Color.red);  
9. }  
10.   
11. public void mouseDragged(MouseEvent me){  
12. Graphics g=getGraphics();  
13. g.setColor(Color.white);  
14. g.fillOval(me.getX(),me.getY(),5,5);  
15. }  
16. public void mouseMoved(MouseEvent me){}  
17.   
18. }  
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-
axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html
1. <html>  
2. <body>  
3. <applet code="MouseDrag.class" width="300" height="300">  
4. </applet>  
5. </body>  
6. </html>  

1. import java.applet.*;  
2. import java.awt.*;  
3. import java.util.*;  
4. import java.text.*;  
5.   
6. public class DigitalClock extends Applet implements Runnable {  
7.   
8.    Thread t = null;  
9.    int hours=0, minutes=0, seconds=0;  
10.    String timeString = "";  
11.   
12.    public void init() {  
13.       setBackground( Color.green);  
14.    }  
15.   
16.    public void start() {  
17.         t = new Thread( this );  
18.         t.start();  
19.    }  
20.   
21.     
22.    public void run() {  
23.       try {  
24.          while (true) {  
25.   
26.             Calendar cal = Calendar.getInstance();  
27.             hours = cal.get( Calendar.HOUR_OF_DAY );  
28.             if ( hours > 12 ) hours -= 12;  
29.             minutes = cal.get( Calendar.MINUTE );  
30.             seconds = cal.get( Calendar.SECOND );  
31.   
32.             SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");  
33.             Date date = cal.getTime();  
34.             timeString = formatter.format( date );  
35.   
36.             repaint();  
37.             t.sleep( 1000 );  // interval given in milliseconds  
38.          }  
39.       }  
40.       catch (Exception e) { }  
41.    }  
42.   
43.     
44.   public void paint( Graphics g ) {  
45.       g.setColor( Color.blue );  
46.       g.drawString( timeString, 50, 50 );  
47.    }  
48. }  
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-
axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html
1. <html>  
2. <body>  
3. <applet code="DigitalClock.class" width="300" height="300">  
4. </applet>  
5. </body>  
6. </html>  

1. import java.applet.*;  
2. import java.awt.*;  
3. import java.util.*;  
4. import java.text.*;  
5.   
6. public class MyClock extends Applet implements Runnable {  
7.   
8.    int width, height;  
9.    Thread t = null;  
10.    boolean threadSuspended;  
11.    int hours=0, minutes=0, seconds=0;  
12.    String timeString = "";  
13.   
14.    public void init() {  
15.       width = getSize().width;  
16.       height = getSize().height;  
17.       setBackground( Color.black );  
18.    }  
19.   
20.    public void start() {  
21.       if ( t == null ) {  
22.          t = new Thread( this );  
23.          t.setPriority( Thread.MIN_PRIORITY );  
24.          threadSuspended = false;  
25.          t.start();  
26.       }  
27.       else {  
28.          if ( threadSuspended ) {  
29.             threadSuspended = false;  
30.             synchronized( this ) {  
31.                notify();  
32.             }  
33.          }  
34.       }  
35.    }  
36.   
37.    public void stop() {  
38.       threadSuspended = true;  
39.    }  
40.   
41.    public void run() {  
42.       try {  
43.          while (true) {  
44.   
45.             Calendar cal = Calendar.getInstance();  
46.             hours = cal.get( Calendar.HOUR_OF_DAY );  
47.             if ( hours > 12 ) hours -= 12;  
48.             minutes = cal.get( Calendar.MINUTE );  
49.             seconds = cal.get( Calendar.SECOND );  
50.   
51.             SimpleDateFormat formatter  
52.                = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );  
53.             Date date = cal.getTime();  
54.             timeString = formatter.format( date );  
55.   
56.             // Now the thread checks to see if it should suspend itself  
57.             if ( threadSuspended ) {  
58.                synchronized( this ) {  
59.                   while ( threadSuspended ) {  
60.                      wait();  
61.                   }  
62.                }  
63.             }  
64.             repaint();  
65.             t.sleep( 1000 );  // interval specified in milliseconds  
66.          }  
67.       }  
68.       catch (Exception e) { }  
69.    }  
70.   
71.    void drawHand( double angle, int radius, Graphics g ) {  
72.       angle -= 0.5 * Math.PI;  
73.       int x = (int)( radius*Math.cos(angle) );  
74.       int y = (int)( radius*Math.sin(angle) );  
75.       g.drawLine( width/2, height/2, width/2 + x, height/2 + y );  
76.    }  
77.   
78.    void drawWedge( double angle, int radius, Graphics g ) {  
79.       angle -= 0.5 * Math.PI;  
80.       int x = (int)( radius*Math.cos(angle) );  
81.       int y = (int)( radius*Math.sin(angle) );  
82.       angle += 2*Math.PI/3;  
83.       int x2 = (int)( 5*Math.cos(angle) );  
84.       int y2 = (int)( 5*Math.sin(angle) );  
85.       angle += 2*Math.PI/3;  
86.       int x3 = (int)( 5*Math.cos(angle) );  
87.       int y3 = (int)( 5*Math.sin(angle) );  
88.       g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );  
89.       g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );  
90.       g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );  
91.    }  
92.   
93.    public void paint( Graphics g ) {  
94.       g.setColor( Color.gray );  
95.       drawWedge( 2*Math.PI * hours / 12, width/5, g );  
96.       drawWedge( 2*Math.PI * minutes / 60, width/3, g );  
97.       drawHand( 2*Math.PI * seconds / 60, width/2, g );  
98.       g.setColor( Color.white );  
99.       g.drawString( timeString, 10, height-10 );  
100.    }  
101. }  

myapplet.html
1. <html>  
2. <body>  
3. <applet code="MyClock.class" width="300" height="300">  
4. </applet>  
5. </body>  
6. </html>  

1. import java.applet.Applet;  
2. import java.awt.Graphics;  
3.   
4. public class UseParam extends Applet{  
5.   
6. public void paint(Graphics g){  
7. String str=getParameter("msg");  
8. g.drawString(str,50, 50);  
9. }  
10.   
11. }  

myapplet.html
1. <html>  
2. <body>  
3. <applet code="UseParam.class" width="300" height="300">  
4. <param name="msg" value="Welcome to applet">  
5. </applet>  
6. </body>  
7. </html>  

1. import java.applet.*;  
2. import java.awt.*;  
3. import java.awt.event.*;  
4. public class ContextApplet extends Applet implements ActionListener{  
5. Button b;  
6.   
7. public void init(){  
8. b=new Button("Click");  
9. b.setBounds(50,50,60,50);  
10.   
11. add(b);  
12. b.addActionListener(this);  
13. }  
14.   
15. public void actionPerformed(ActionEvent e){  
16.   
17. AppletContext ctx=getAppletContext();  
18. Applet a=ctx.getApplet("app2");  
19. a.setBackground(Color.yellow);  
20. }  
21. }  

myapplet.html
1. <html>  
2. <body>  
3. <applet code="ContextApplet.class" width="150" height="150" name="app1">  
4. </applet>  
5.   
6. <applet code="First.class" width="150" height="150" name="app2">  
7. </applet>  
8. </body>  
9. </html>  

1. package com.techknow.graphics;  
2.   
3. import java.awt.Color;  
4. import java.awt.Dimension;  
5. import java.awt.Frame;  
6. import java.awt.Graphics;  
7. import java.awt.SystemColor;  
8. import java.awt.event.WindowAdapter;  
9. import java.awt.event.WindowEvent;  
10.   
11. public class GraphicsDemo extends Frame  
12. {  
13.     public GraphicsDemo()  
14.     {  
15.         try  
16.         {  
17.             jbInit();  
18.         }  
19.         catch (Exception e)  
20.         {  
21.             e.printStackTrace();  
22.         }  
23.     }  
24.     private void jbInit() throws Exception  
25.     {  
26.         this.setLayout( null );  
27.         this.setSize(new Dimension(390, 232));  
28.         this.setBackground( SystemColor.control );  
29.         this.setVisible(true);  
30.         this.setTitle("Graphics Class Demo");  
31.         this.addWindowListener(new WindowAdapter()  
32.         {  
33.             public void windowClosing(WindowEvent e)  
34.             {  
35.                 this_windowClosing(e);  
36.             }  
37.         });  
38.         this.setLocation(250,200);  
39.     }  
40.     public void paint(Graphics g)  
41.     {  
42.         g.drawRect(10,50,50,50);  
43.         g.drawString("Techknow Heights ",70,70);  
44.         g.fillRect(100,100,50,50);  
45.         g.setColor(Color.RED);  
46.         g.fillOval(150,150,50,50);  
47.     }  
48.     public static void main(String args[])  
49.     {  
50.         new GraphicsDemo();  
51.     }  
52.     private void this_windowClosing(WindowEvent e)  
53.     {  
54.         System.exit(0);  
55.     }  
56. }  

The class includes the constructor font () that can be used to specify the font settings required
Syntax:
Font(String name,int style,int size)
Font name is the name of the font.
Style may be BOLD,ITALIC, or PLAIN Text
Size is an integer value representing the font size.
The font setting specified with font method can be implemented using the setFont()method of the graphics class.

Void setFont(Font font)

import java.awt.*;
import java.applet.*;
import java.awt.Graphics;
import java.awt.Color;
public class fontoval extends Applet
{
public void paint(Graphics g)
{
g.setFont(new Font("Arial",Font.BOLD,20));
g.setColor(Color.red);
g.drawString("Welcome",20, 100);
}
}

Get Image
import java.awt.*;
import java.applet.*;

public class ima1 extends Applet


{
Image img;
public void init()
{

img=getImage(getDocumentBase(),"rose06.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
}
The class includes the constructor font () that can be used to specify the font
settings required

Syntax:

Font(String name,int style,int size)

Font name is the name of the font.

Style may be BOLD,ITALIC, or PLAIN Text

Size is an integer value representing the font size.

The font setting specified with font method can be implemented using the
setFont()method of the graphics class.

Void setFont(Font font)


BorderLayout (LayoutManagers):

LayoutManagers:

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface
that is implemented by all the classes of layout managers. There are following classes that represents the
layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

BorderLayout:

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center.
Each region (area) may contain one component only. It is the default layout of frame or window. The
BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


 BorderLayout(): creates a border layout but with no gaps between the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical
gaps between the components.
Example of BorderLayout class:

1. import java.awt.*;  
2. import javax.swing.*;  
3.   
4. public class Border {  
5. JFrame f;  
6. Border(){  
7.     f=new JFrame();  
8.       
9.     JButton b1=new JButton("NORTH");;  
10.     JButton b2=new JButton("SOUTH");;  
11.     JButton b3=new JButton("EAST");;  
12.     JButton b4=new JButton("WEST");;  
13.     JButton b5=new JButton("CENTER");;  
14.       
15.     f.add(b1,BorderLayout.NORTH);  
16.     f.add(b2,BorderLayout.SOUTH);  
17.     f.add(b3,BorderLayout.EAST);  
18.     f.add(b4,BorderLayout.WEST);  
19.     f.add(b5,BorderLayout.CENTER);  
20.       
21.     f.setSize(300,300);  
22.     f.setVisible(true);  
23. }  
24. public static void main(String[] args) {  
25.     new Border();  
26. }  
27. }  
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle.

Constructors of GridLayout class:


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.

3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class:

1. import java.awt.*;  
2. import javax.swing.*;  
3.   
4. public class MyGridLayout{  
5. JFrame f;  
6. MyGridLayout(){  
7.     f=new JFrame();  
8.       
9.     JButton b1=new JButton("1");  
10.     JButton b2=new JButton("2");  
11.     JButton b3=new JButton("3");  
12.     JButton b4=new JButton("4");  
13.     JButton b5=new JButton("5");  
14.         JButton b6=new JButton("6");  
15.         JButton b7=new JButton("7");  
16.     JButton b8=new JButton("8");  
17.         JButton b9=new JButton("9");  
18.           
19.     f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
20.     f.add(b6);f.add(b7);f.add(b8);f.add(b9);  
21.   
22.     f.setLayout(new GridLayout(3,3));  
23.     //setting grid layout of 3 rows and 3 columns  
24.   
25.     f.setSize(300,300);  
26.     f.setVisible(true);  
27. }  
28. public static void main(String[] args) {  
29.     new MyGridLayout();  
30. }  
31. }  

FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default
layout of applet or panel.

Fields of FlowLayout class:


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING

5. public static final int TRAILING

Constructors of FlowLayout class:


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.

3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and
the given horizontal and vertical gap.
Example of FlowLayout class:

1. import java.awt.*;  
2. import javax.swing.*;  
3.   
4. public class MyFlowLayout{  
5. JFrame f;  
6. MyFlowLayout(){  
7.     f=new JFrame();  
8.       
9.     JButton b1=new JButton("1");  
10.     JButton b2=new JButton("2");  
11.     JButton b3=new JButton("3");  
12.     JButton b4=new JButton("4");  
13.     JButton b5=new JButton("5");  
14.               
15.     f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
16.       
17.     f.setLayout(new FlowLayout(FlowLayout.RIGHT));  
18.     //setting flow layout of right alignment  
19.   
20.     f.setSize(300,300);  
21.     f.setVisible(true);  
22. }  
23. public static void main(String[] args) {  
24.     new MyFlowLayout();  
25. }  
26. }  

BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose,
BoxLayout provides four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class:


1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS

4. public static final int PAGE_AXIS

Constructor of BoxLayout class:


1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the
given axis.

Example of BoxLayout class with Y-AXIS:

1. import java.awt.*;  
2. import javax.swing.*;  
3.   
4. public class BoxLayoutExample1 extends Frame {  
5.  Button buttons[];  
6.   
7.  public BoxLayoutExample1 () {  
8.    buttons = new Button [5];  
9.     
10.    for (int i = 0;i<5;i++) {  
11.       buttons[i] = new Button ("Button " + (i + 1));  
12.       add (buttons[i]);  
13.     }  
14.   
15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));  
16. setSize(400,400);  
17. setVisible(true);  
18. }  
19.   
20. public static void main(String args[]){  
21. BoxLayoutExample1 b=new BoxLayoutExample1();  
22. }  
23. }  
download this example

Example of BoxLayout class with X-AXIS:

1. import java.awt.*;  
2. import javax.swing.*;  
3.   
4. public class BoxLayoutExample2 extends Frame {  
5.  Button buttons[];  
6.   
7.  public BoxLayoutExample2() {  
8.    buttons = new Button [5];  
9.     
10.    for (int i = 0;i<5;i++) {  
11.       buttons[i] = new Button ("Button " + (i + 1));  
12.       add (buttons[i]);  
13.     }  
14.   
15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));  
16. setSize(400,400);  
17. setVisible(true);  
18. }  
19.   
20. public static void main(String args[]){  
21. BoxLayoutExample2 b=new BoxLayoutExample2();  
22. }  
23. }  

CardLayout class
The CardLayout class manages the components in such a manner that only one component is visible at a
time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class:


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.

2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class:


 public void next(Container parent): is used to flip to the next card of the given container.
 public void previous(Container parent): is used to flip to the previous card of the given
container.
 public void first(Container parent): is used to flip to the first card of the given container.
 public void last(Container parent): is used to flip to the last card of the given container.

 public void show(Container parent, String name): is used to flip to the specified card with the
given name.
Example of CardLayout class:

1. import java.awt.*;  
2. import java.awt.event.*;  
3.   
4. import javax.swing.*;  
5.   
6. public class CardLayoutExample extends JFrame implements ActionListener{  
7. CardLayout card;  
8. JButton b1,b2,b3;  
9. Container c;  
10.     CardLayoutExample(){  
11.           
12.         c=getContentPane();  
13.         card=new CardLayout(40,30);  
14. //create CardLayout object with 40 hor space and 30 ver space  
15.         c.setLayout(card);  
16.           
17.         b1=new JButton("Apple");  
18.         b2=new JButton("Boy");  
19.         b3=new JButton("Cat");  
20.         b1.addActionListener(this);  
21.         b2.addActionListener(this);  
22.         b3.addActionListener(this);  
23.               
24.         c.add("a",b1);c.add("b",b2);c.add("c",b3);  
25.                           
26.     }  
27.     public void actionPerformed(ActionEvent e) {  
28.     card.next(c);  
29.     }  
30.   
31.     public static void main(String[] args) {  
32.         CardLayoutExample cl=new CardLayoutExample();  
33.         cl.setSize(400,400);  
34.         cl.setVisible(true);  
35.         cl.setDefaultCloseOperation(EXIT_ON_CLOSE);  
36.     }  
37. }  

What is an Event?

Change in the state of an object is known as event i.e. event describes the change in state of source. Events are
generated as result of user interaction with the graphical user interface components. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page are
the activities that causes an event to happen.

Types of Event

The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of user.They are generated as
consequences of a person interacting with the graphical components in Graphical User Interface. For
example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item
from list, scrolling the page etc.

 Background Events - Those events that require the interaction of end user are known as background
events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are
the example of background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This
mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the
Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle
the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible for providing information of
the occurred event to it's handler. Java provide as with classes for source object.

 Listener - It is also known as event handler.Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object. Listener waits until it receives an
event. Once the event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the
event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this
model ,Listener needs to be registered with the source object so that the listener can receive the event notification.
This is an efficient way of handling the event because the event notifications are sent only to those listener that
want to receive them.

Steps involved in event handling

 The User clicks the button and the event is generated.


 Now the object of concerned event class is created automatically and information about the source and the
event get populated with in same object.

 Event object is forwarded to the method of registered listener class.

 the method is now get executed and returns.

Points to remember about listener

 In order to design a listener class we have to develop some listener interfaces.These Listener interfaces
forecast some public abstract callback methods which must be implemented by the listener class.

 If you do not implement the any if the predefined interfaces then your class can not act as a listener class for
a source object.

Callback Methods

These are the methods that are provided by API provider and are defined by the application programmer and
invoked by the application developer. Here the callback methods represents an event method. In response to an
event java jre will fire callback method. All such callback methods are provided in listener interfaces.

If a component wants some listener will listen to it's events the the source must register itself to the listener.

Event and Listener (Event Handling):


Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The
java.awt.event package provides many event classes and Listener interfaces for event handling.
Event classes and Listener interfaces:
Event Classes Listener Interfaces
ActionListener
ActionEvent
void actionPerformed(ActionEvent e)
MouseListener and MouseMotionListener
void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released) on a component. 2void
mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
MouseEvent
3void mouseExited(MouseEvent e)
Invoked when the mouse exits a component. 4void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component. 5void
mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.
MouseWheelListener
void mouseDragged(MouseEvent e)
MouseWheelEvent Invoked when a mouse button is pressed on a component and then dragged. 2void
mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
KeyListener
1. void keyPressed(KeyEvent e) Invoked when a key has been pressed.
KeyEvent
2 void keyReleased(KeyEvent e) Invoked when a key has been released.
3 void keyTyped(KeyEvent e) Invoked when a key has been typed.
ItemListener
ItemEvent void itemStateChanged(ItemEvent e)
Invoked when an item has been selected or deselected by the user.
TextListener
TextEvent void textValueChanged(TextEvent e)
Invoked when the value of the text has changed.
AdjustmentListener
AdjustmentEvent void adjustmentValueChanged(AdjustmentEvent e)
Invoked when the value of the adjustable has changed.
WindowEvent WindowListener
void windowActivated(WindowEvent e)
Invoked when the Window is set to be the active Window.
void windowClosed(WindowEvent e)
Invoked when a window has been closed as the result of calling dispose on the window.
void windowClosing(WindowEvent e)
Invoked when the user attempts to close the window from the window's system menu.
void windowDeactivated(WindowEvent e)
Invoked when a Window is no longer the active Window.
void windowDeiconified(WindowEvent e)
Invoked when a window is changed from a minimized to a normal state.
void windowIconified(WindowEvent e)
Invoked when a window is changed from a normal to a minimized state.
void windowOpened(WindowEvent e)
Invoked the first time a window is made visible.
ComponentListener

void componentHidden(ComponentEvent e) Invoked when the component has been made


ComponentEvent invisible.
void componentMoved(ComponentEvent e) Invoked when the component's position changes.
void componentResized(ComponentEvent e) Invoked when the component's size changes.
void componentShown(ComponentEvent e) Invoked when the component has been made visible.
ContainerListener
void componentAdded(ContainerEvent e)
ContainerEvent Invoked when a component has been added to the container. 2void
componentRemoved(ContainerEvent e)
Invoked when a component has been removed from the container.
FocusListener
void focusGained(FocusEvent e)
FocusEvent Invoked when a component gains the keyboard focus.
void focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.

Steps to perform EventHandling:


Following steps are required to perform event handling :
1. Implement the Listener interface and overrides its methods

2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods. For example:
 Button
o public void addActionListener(ActionListener a){}
 MenuItem
o public void addActionListener(ActionListener a){}
 TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
 TextArea
o public void addTextListener(TextListener a){}
 Checkbox
o public void addItemListener(ItemListener a){}
 Choice
o public void addItemListener(ItemListener a){}
 List
o public void addActionListener(ActionListener a){}

o public void addItemListener(ItemListener a){}


Introduction
Label is a passive control because it does not create any event when accessed by the user. The label control is an object of Label. A label
displays a single line of read-only text. However the text can be changed by the application programmer but cannot be changed by the end
user in any way.

Class declaration
Following is the declaration for java.awt.Label class:

public class Label


extends Component
implements Accessible

Field
Following are the fields for java.awt.Component class:

 static int CENTER -- Indicates that the label should be centered.

 static int LEFT -- Indicates that the label should be left justified.

 static int RIGHT -- Indicates that the label should be right justified.

Class constructors
S.N. Constructor & Description

Label()
1
Constructs an empty label.

Label(String text)
2
Constructs a new label with the specified string of text, left justified.

3 Label(String text, int alignment)


Constructs a new label that presents the specified string of text with the specified alignment.

Class methods
S.N. Method & Description

void addNotify()
1
Creates the peer for this label.

AccessibleContext getAccessibleContext()
2
Gets the AccessibleContext associated with this Label.

int getAlignment()
3
Gets the current alignment of this label.

String getText()
4
Gets the text of this label.

protected String paramString()


5
Returns a string representing the state of this Label.

void setAlignment(int alignment)


6
Sets the alignment for this label to the specified alignment.

void setText(String text)


7
Sets the text for this label to the specified text.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Component

 java.lang.Object

Introduction
Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends
an instance of ActionEvent to the button, by calling processEvent on the button. The button's processEvent method receives all events for
the button; it passes an action event along by calling its own processActionEvent method. The latter method passes the action event on to
any action listeners that have registered an interest in action events generated by this button.

If an application wants to perform some action based on a button being pressed and released, it should implement ActionListener and
register the new listener to receive events from this button, by calling the button's addActionListener method. The application can make use
of the button's action command as a messaging protocol.
Class declaration
Following is the declaration for java.awt.Button class:

public class Button


extends Component
implements Accessible

Class constructors
S.N. Constructor & Description

Button()
1
Constructs a button with an empty string for its label.

Button(String text)
2
Constructs a new button with specified label.

Class methods
S.N. Method & Description

void addActionListener(ActionListener l)
1
Adds the specified action listener to receive action events from this button.

void addNotify()
2
Creates the peer of the button.

AccessibleContext getAccessibleContext()
3
Gets the AccessibleContext associated with this Button.

String getActionCommand()
4
Returns the command name of the action event fired by this button.

ActionListener[] getActionListeners()
5
Returns an array of all the action listeners registered on this button.

String getLabel()
6
Gets the label of this button.

<T extends EventListener> T[] getListeners(Class<T> listenerType)


7
Returns an array of all the objects currently registered as FooListeners upon this Button.

protected String paramString()


8
Returns a string representing the state of this Button.
protected void processActionEvent(ActionEvent e)
9
Processes action events occurring on this button by dispatching them to any registered ActionListener objects.

protected void processEvent(AWTEvent e)


10
Processes events on this button.

void removeActionListener(ActionListener l)
11
Removes the specified action listener so that it no longer receives action events from this button.

void setActionCommand(String command)


12
Sets the command name for the action event fired by this button.

void setLabel(String label)


13
Sets the button's label to be the specified string.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Component

 java.lang.Object

Introduction
Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The
state of a checkbox can be changed by clicking on it.

Class declaration
Following is the declaration for java.awt.Checkbox class:

public class Checkbox


extends Component
implements ItemSelectable,Accessible

Class constructors
S.N. Constructor & Description

Checkbox()
1
Creates a check box with an empty string for its label.
Checkbox(String label)
2
Creates a check box with the specified label.

Checkbox(String label, boolean state)


3
Creates a check box with the specified label and sets the specified state.

Checkbox(String label, boolean state, CheckboxGroup group)


4
Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group.

Checkbox(String label, CheckboxGroup group, boolean state)


5
Creates a check box with the specified label, in the specified check box group, and set to the specified state.

Class methods
S.N. Method & Description

void addItemListener(ItemListener l)
1
Adds the specified item listener to receive item events from this check box.

void addNotify()
2
Creates the peer of the Checkbox.

AccessibleContext getAccessibleContext()
3
Gets the AccessibleContext associated with this Checkbox.

CheckboxGroup getCheckboxGroup()
4
Determines this check box's group.

ItemListener[] getItemListeners()
5
Returns an array of all the item listeners registered on this checkbox.

String getLabel()
6
Gets the label of this check box.

<T extends EventListener>T[] getListeners(Class<T> listenerType)


7
Returns an array of all the objects currently registered as FooListeners upon this Checkbox.

Object[] getSelectedObjects()
8
Returns an array (length 1) containing the checkbox label or null if the checkbox is not selected.

boolean getState()
9
Determines whether this check box is in the on or off state.

protected String paramString()


10
Returns a string representing the state of this Checkbox.
protected void processEvent(AWTEvent e)
11
Processes events on this check box.

protected void processItemEvent(ItemEvent e)


12
Processes item events occurring on this check box by dispatching them to any registered ItemListener objects.

void removeItemListener(ItemListener l)
13
Removes the specified item listener so that the item listener no longer receives item events from this check box.

void setCheckboxGroup(CheckboxGroup g)
14
Sets this check box's group to the specified check box group.

void setLabel(String label)


15
Sets this check box's label to be the string argument.

void setState(boolean state)


16
Sets the state of this check box to the specified state.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Component

 java.lang.Object

Introduction
The CheckboxGroup class is used to group the set of checkbox.

Class declaration
Following is the declaration for java.awt.CheckboxGroup class:

public class CheckboxGroup


extends Object
implements Serializable

Class constructors
S.N. Constructor & Description

1 CheckboxGroup() ()
Creates a new instance of CheckboxGroup.

Class methods
S.N. Method & Description

Checkbox getCurrent()
1
Deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox().

Checkbox getSelectedCheckbox()
2
Gets the current choice from this check box group.

void setCurrent(Checkbox box)


3
Deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox).

void setSelectedCheckbox(Checkbox box)


4
Sets the currently selected check box in this group to be the specified check box.

String toString()
5
Returns a string representation of this check box group, including the value of its current selection.

Methods inherited
This class inherits methods from the following classes:

 java.lang.Object

Introduction
The List represents a list of text items. The list can be configured to that user can choose either one item or multiple items.

Class declaration
Following is the declaration for java.awt.List class:

public class List


extends Component
implements ItemSelectable, Accessible

Class constructors
S.N. Constructor & Description
List()
1
Creates a new scrolling list.

List(int rows)
2
Creates a new scrolling list initialized with the specified number of visible lines.

List(int rows, boolean multipleMode)


3
Creates a new scrolling list initialized to display the specified number of rows.

Class methods
S.N. Method & Description

void add(String item)


1
Adds the specified item to the end of scrolling list.

void add(String item, int index)


2
Adds the specified item to the the scrolling list at the position indicated by the index.

void addActionListener(ActionListener l)
3
Adds the specified action listener to receive action events from this list.

void addItem(String item)


4
Deprecated. replaced by add(String).

void addItem(String item, int index)


5
Deprecated. replaced by add(String, int).

void addItemListener(ItemListener l)
6
Adds the specified item listener to receive item events from this list.

void addNotify()
7
Creates the peer for the list.

boolean allowsMultipleSelections()
8
Deprecated. As of JDK version 1.1, replaced by isMultipleMode().

void clear()
9
Deprecated. As of JDK version 1.1, replaced by removeAll().

int countItems()
10
Deprecated. As of JDK version 1.1, replaced by getItemCount().

void delItem(int position)


11
Deprecated. replaced by remove(String) and remove(int).
void delItems(int start, int end)
12 Deprecated. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package
private method.

void deselect(int index)


13
Deselects the item at the specified index.

AccessibleContext getAccessibleContext()
14
Gets the AccessibleContext associated with this List.

ActionListener[] getActionListeners()
15
Returns an array of all the action listeners registered on this list.

String getItem(int index)


16
Gets the item associated with the specified index.

int getItemCount()
17
Gets the number of items in the list.

ItemListener[] getItemListeners()
18
Returns an array of all the item listeners registered on this list.

String[] getItems()
19 Gets the items in the list.<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this List.

Dimension getMinimumSize()
20
Determines the minimum size of this scrolling list.

Dimension getMinimumSize(int rows)


21
Gets the minumum dimensions for a list with the specified number of rows.

Dimension getPreferredSize()
22
Gets the preferred size of this scrolling list.

Dimension getPreferredSize(int rows)


23
Gets the preferred dimensions for a list with the specified number of rows.

int getRows()
24
Gets the number of visible lines in this list.

int getSelectedIndex()
25
Gets the index of the selected item on the list,

int[] getSelectedIndexes()
26
Gets the selected indexes on the list.
String getSelectedItem()
27
Gets the selected item on this scrolling list.

String[] getSelectedItems()
28
Gets the selected items on this scrolling list.

Object[] getSelectedObjects()
29
Gets the selected items on this scrolling list in an array of Objects.

int getVisibleIndex()
30
Gets the index of the item that was last made visible by the method makeVisible.

boolean isIndexSelected(int index)


31
Determines if the specified item in this scrolling list is selected.

boolean isMultipleMode()
32
Determines whether this list allows multiple selections.

boolean isSelected(int index)


33
Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int).

void makeVisible(int index)


34
Makes the item at the specified index visible.

Dimension minimumSize()
35
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().

Dimension minimumSize(int rows)


36
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).

protected String paramString()


37
Returns the parameter string representing the state of this scrolling list.

Dimension preferredSize()
38
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Dimension preferredSize(int rows)


39
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).

protected void processActionEvent(ActionEvent e)


40
Processes action events occurring on this component by dispatching them to any registered ActionListener objects.

protected void processEvent(AWTEvent e)


41
Processes events on this scrolling list.

42 protected void processItemEvent(ItemEvent e)


Processes item events occurring on this list by dispatching them to any registered ItemListener objects.

void remove(int position)


43
Removes the item at the specified position from this scrolling list.

void remove(String item)


44
Removes the first occurrence of an item from the list.

void removeActionListener(ActionListener l)
45
Removes the specified action listener so that it no longer receives action events from this list.

void removeAll()
46
Removes all items from this list.

void removeItemListener(ItemListener l)
47
Removes the specified item listener so that it no longer receives item events from this list.

void removeNotify()
48
Removes the peer for this list.

void replaceItem(String newValue, int index)


49
Replaces the item at the specified index in the scrolling list with the new string.

void select(int index)


50
Selects the item at the specified index in the scrolling list.

void setMultipleMode(boolean b)
51
Sets the flag that determines whether this list allows multiple selections.

void setMultipleSelections(boolean b)
52
Deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean).

Methods inherited
This class inherits methods from the following classes:

 java.awt.Component

 java.lang.Object
Introduction
The textField component allows the user to edit single line of text.When the user types a key in the text field the event is sent to the
TextField. The key event may be key pressed, Key released or key typed. The key event is passed to the registered KeyListener. It is also
possible to for an ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by pressing the return key.

Class declaration
Following is the declaration for java.awt.TextField class:

public class TextField


extends TextComponent

Class constructors
S.N. Constructor & Description

TextField()
1
Constructs a new text field.

TextField(int columns)
2
Constructs a new empty text field with the specified number of columns.

TextField(String text)
3
Constructs a new text field initialized with the specified text.
TextField(String text, int columns)
4 Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of
columns.

Class methods
S.N. Method & Description

void addActionListener(ActionListener l)
1
Adds the specified action listener to receive action events from this text field.

void addNotify()
2
Creates the TextField's peer.

boolean echoCharIsSet()
3
Indicates whether or not this text field has a character set for echoing.

AccessibleContext getAccessibleContext()
4
Gets the AccessibleContext associated with this TextField.

ActionListener[] getActionListeners()
5
Returns an array of all the action listeners registered on this textfield.

int getColumns()
6
Gets the number of columns in this text field.

char getEchoChar()
7
Gets the character that is to be used for echoing.

<T extends EventListener> T[] getListeners(Class<T> listenerType)


8
Returns an array of all the objects currently registered as FooListeners upon this TextField.

Dimension getMinimumSize()
9
Gets the minumum dimensions for this text field.

Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text field with the specified number of
10
columns.

Dimension getPreferredSize()
11
Gets the preferred size of this text field.

Dimension getPreferredSize(int columns)


12
Gets the preferred size of this text field with the specified number of columns.

Dimension minimumSize()
13
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
Dimension minimumSize(int columns)
14
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).

protected String paramString()


15
Returns a string representing the state of this TextField.

Dimension preferredSize()
16
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Dimension preferredSize(int columns)


17
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).

protected void processActionEvent(ActionEvent e)


18
Processes action events occurring on this text field by dispatching them to any registered ActionListener objects.

protected void processEvent(AWTEvent e)


19
Processes events on this text field.

void removeActionListener(ActionListener l)
20
Removes the specified action listener so that it no longer receives action events from this text field.

void setColumns(int columns)


21
Sets the number of columns in this text field.

void setEchoChar(char c)
22
Sets the echo character for this text field.

void setEchoCharacter(char c)
23
Deprecated. As of JDK version 1.1, replaced by setEchoChar(char).

void setText(String t)
24
Sets the text that is presented by this text component to be the specified text.

Methods inherited
This class inherits methods from the following classes:

 java.awt.TextComponent

 java.awt.Component

 java.lang.Object
Introduction
The TextArea control in AWT provide us multiline editor area. The user can type here as much as he wants. When the text in the text area
become larger than the viewable area the scroll bar is automatically appears which help us to scroll the text up & down and right & left.

Class declaration
Following is the declaration for java.awt.TextArea class:

public class TextArea


extends TextComponent

Field
Following are the fields for java.awt.TextArea class:

 static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal scrollbars.

 static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal scrollbar only.

 static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text area.

 static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar only.

Class constructors
S.N. Constructor & Description

TextArea()
1
Constructs a new text area with the empty string as text.

TextArea(int rows, int columns)


2
Constructs a new text area with the specified number of rows and columns and the empty string as text.

TextArea(String text)
3
Constructs a new text area with the specified text.

TextArea(String text, int rows, int columns)


4
Constructs a new text area with the specified text, and with the specified number of rows and columns.

TextArea(String text, int rows, int columns, int scrollbars)


5
Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.
Class methods
S.N. Method & Description

void addNotify()
1
Creates the TextArea's peer.

void append(String str)


2
Appends the given text to the text area's current text.

void appendText(String str)


3
Deprecated. As of JDK version 1.1, replaced by append(String).

AccessibleContext getAccessibleContext()
4
Returns the AccessibleContext associated with this TextArea.

int getColumns()
5
Returns the number of columns in this text area.

Dimension getMinimumSize()
6
Determines the minimum size of this text area.

Dimension getMinimumSize(int rows, int columns)


7
Determines the minimum size of a text area with the specified number of rows and columns.

Dimension getPreferredSize()
8
Determines the preferred size of this text area.

Dimension getPreferredSize(int rows, int columns)


9
Determines the preferred size of a text area with the specified number of rows and columns.

int getRows()
10
Returns the number of rows in the text area.

int getScrollbarVisibility()
11
Returns an enumerated value that indicates which scroll bars the text area uses.

void insert(String str, int pos)


12
Inserts the specified text at the specified position in this text area.

void insertText(String str, int pos)


13
Deprecated. As of JDK version 1.1, replaced by insert(String, int).

Dimension minimumSize()
14
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
Dimension minimumSize(int rows, int columns)
15
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int).

protected String paramString()


16
Returns a string representing the state of this TextArea.

Dimension preferredSize()
17
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Dimension preferredSize(int rows, int columns)


18
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int).

void replaceRange(String str, int start, int end)


19
Replaces text between the indicated start and end positions with the specified replacement text.

void replaceText(String str, int start, int end)


20
Deprecated. As of JDK version 1.1, replaced by replaceRange(String, int, int).

void setColumns(int columns)


21
Sets the number of columns for this text area.

void setRows(int rows)


22
Sets the number of rows for this text area.

Methods inherited
This class inherits methods from the following classes:

 java.awt.TextComponent

 java.awt.Component

 java.lang.Object

Introduction
Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu.
Class declaration
Following is the declaration for java.awt.Choice class:

public class Choice


extends Component
implements ItemSelectable, Accessible

Class constructors
S.N. Constructor & Description

Choice() ()
1
Creates a new choice menu.

Class methods
S.N. Method & Description

void add(String item)


1
Adds an item to this Choice menu.

void addItem(String item)


2
Obsolete as of Java 2 platform v1.1.

void addItemListener(ItemListener l)
3
Adds the specified item listener to receive item events from this Choice menu.

void addNotify()
4
Creates the Choice's peer.

int countItems()
5
Deprecated. As of JDK version 1.1, replaced by getItemCount().

AccessibleContext getAccessibleContext()
6
Gets the AccessibleContext associated with this Choice.

String getItem(int index)


7
Gets the string at the specified index in this Choice menu.

int getItemCount()
8
Returns the number of items in this Choice menu.

ItemListener[] getItemListeners()
9
Returns an array of all the item listeners registered on this choice.
<T extends EventListener> T[] getListeners(Class<T> listenerType)
10
Returns an array of all the objects currently registered as FooListeners upon this Choice.

int getSelectedIndex()
11
Returns the index of the currently selected item.

String getSelectedItem()
12
Gets a representation of the current choice as a string.

Object[] getSelectedObjects()
13
Returns an array (length 1) containing the currently selected item.

void insert(String item, int index)


14
Inserts the item into this choice at the specified position.

protected String paramString()


15
Returns a string representing the state of this Choice menu.

protected void processEvent(AWTEvent e)


16
Processes events on this choice.

protected void processItemEvent(ItemEvent e)


17
Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.

void remove(int position)


18
Removes an item from the choice menu at the specified position.

void remove(String item)


19
Removes the first occurrence of item from the Choice menu.

void removeAll()
20
Removes all items from the choice menu.

void removeItemListener(ItemListener l)
21
Removes the specified item listener so that it no longer receives item events from this Choice menu.

void select(int pos)


22
Sets the selected item in this Choice menu to be the item at the specified position.

void select(String str)


23
Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.

Methods inherited
This class inherits methods from the following classes:
 java.awt.Component

 java.lang.Object

Introduction
Canvas control represents a rectangular area where application can draw something or can receive inputs created by user.

Class declaration
Following is the declaration for java.awt.Canvas class:

public class Canvas


extends Component
implements Accessible

Class constructors
S.N. Constructor & Description

Canvas()
1
Constructs a new Canvas.

Canvas(GraphicsConfiguration config)
2
Constructs a new Canvas given a GraphicsConfiguration object.

Class methods
S.N. Method & Description

void addNotify()
1
Creates the peer of the canvas.

void createBufferStrategy(int numBuffers)


2
Creates a new strategy for multi-buffering on this component.

void createBufferStrategy(int numBuffers, BufferCapabilities caps)


3
Creates a new strategy for multi-buffering on this component with the required buffer capabilities.

AccessibleContext getAccessibleContext()
4
Gets the AccessibleContext associated with this Canvas.

BufferStrategy getBufferStrategy()
5
Returns the BufferStrategy used by this component.
void paint(Graphics g)
6
Paints this canvas.

void pdate(Graphics g)
7
Updates this canvas.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Component

 java.lang.Object

Canvas Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCanvasDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showCanvasDemo(){


headerLabel.setText("Control in action: Canvas");

controlPanel.add(new MyCanvas());
mainFrame.setVisible(true);
}

class MyCanvas extends Canvas {

public MyCanvas () {
setBackground (Color.GRAY);
setSize(300, 300);
}

public void paint (Graphics g) {


Graphics2D g2;
g2 = (Graphics2D) g;
g2.drawString ("It is a custom canvas area", 70, 70);
}
}
}

Introduction
Image control is superclass for all image classes representing graphical images.

Class declaration
Following is the declaration for java.awt.Image class:

public abstract class Image


extends Object

Field
Following are the fields for java.awt.Image class:

 protected float accelerationPriority -- Priority for accelerating this image.

 static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling algorithm.

 static int SCALE_DEFAULT -- Use the default image-scaling algorithm.


 static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the
scaled image.

 static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the ReplicateScaleFilter class.

 static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling
speed.

 static Object UndefinedProperty -- The UndefinedProperty object should be returned whenever a property which was not defined
for a particular image is fetched.

Class constructors
S.N. Constructor & Description

1 Image()

Class methods
S.N. Method & Description

void flush()
1
Flushes all reconstructable resources being used by this Image object.

float getAccelerationPriority()
2
Returns the current value of the acceleration priority hint.

ImageCapabilities getCapabilities(GraphicsConfiguration gc)


3 Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image on the specified
GraphicsConfiguration.

abstract Graphics getGraphics()


4
Creates a graphics context for drawing to an off-screen image.

abstract int getHeight(ImageObserver observer)


5
Determines the height of the image.

abstract Object getProperty(String name, ImageObserver observer)


6
Gets a property of this image by name.

Image getScaledInstance(int width, int height, int hints)


7
Creates a scaled version of this image.

abstract ImageProducer getSource()


8
Gets the object that produces the pixels for the image.

9 abstract int getWidth(ImageObserver observer)


Determines the width of the image.

void setAccelerationPriority(float priority)


10
Sets a hint for this image about how important acceleration is.

Methods inherited
This class inherits methods from the following classes:

 java.lang.Object

Image Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showImageDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showImageDemo(){


headerLabel.setText("Control in action: Image");

controlPanel.add(new ImageComponent("resources/java.jpg"));
mainFrame.setVisible(true);
}

class ImageComponent extends Component {

BufferedImage img;

public void paint(Graphics g) {


g.drawImage(img, 0, 0, null);
}

public ImageComponent(String path) {


try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}

public Dimension getPreferredSize() {


if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(), img.getHeight());
}
}
}
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output


Introduction
Scrollbar control represents a scroll bar component in order to enable user to select from range of values.

Class declaration
Following is the declaration for java.awt.Scrollbar class:

public class Scrollbar


extends Component
implements Adjustable, Accessible

Field
Following are the fields for java.awt.Image class:

 static int HORIZONTAL --A constant that indicates a horizontal scroll bar.

 static int VERTICAL --A constant that indicates a vertical scroll bar.

Class constructors
S.N. Constructor & Description

Scrollbar()
1
Constructs a new vertical scroll bar.

Scrollbar(int orientation)
2
Constructs a new scroll bar with the specified orientation.

Scrollbar(int orientation, int value, int visible, int minimum, int maximum)
3
Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values.

Class methods
S.N. Method & Description

void addAdjustmentListener(AdjustmentListener l)
1
Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar.

void addNotify()
2
Creates the Scrollbar's peer.

int getBlockIncrement()
3
Gets the block increment of this scroll bar.

4 int getLineIncrement()
Deprecated. As of JDK version 1.1, replaced by getUnitIncrement().

int getMaximum()
5
Gets the maximum value of this scroll bar.

int getMinimum()
6
Gets the minimum value of this scroll bar.

int getOrientation()
7
Returns the orientation of this scroll bar.

int getPageIncrement()
8
Deprecated. As of JDK version 1.1, replaced by getBlockIncrement().

int getUnitIncrement()
9
Gets the unit increment for this scrollbar.

int getValue()
10
Gets the current value of this scroll bar.

boolean
11 getValueIsAdjusting()
Returns true if the value is in the process of changing as a result of actions being taken by the user.

int getVisible()
12
Deprecated. As of JDK version 1.1, replaced by getVisibleAmount().

int getVisibleAmount()
13
Gets the visible amount of this scroll bar.

protected String paramString()


14
Returns a string representing the state of this Scrollbar.

protected void processAdjustmentEvent(AdjustmentEvent e)


15
Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects.

protected void processEvent(AWTEvent e)


16
Processes events on this scroll bar.

void removeAdjustmentListener(AdjustmentListener l)
17
Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar.

void setBlockIncrement(int v)
18
Sets the block increment for this scroll bar.

19 void setLineIncrement(int v)
Deprecated. As of JDK version 1.1, replaced by setUnitIncrement(int).

void setMaximum(int newMaximum)


20
Sets the maximum value of this scroll bar.

void setMinimum(int newMinimum)


21
Sets the minimum value of this scroll bar.

void setOrientation(int orientation)


22
Sets the orientation for this scroll bar.

void setPageIncrement(int v)
23
Deprecated. As of JDK version 1.1, replaced by setBlockIncrement().

void setUnitIncrement(int v)
24
Sets the unit increment for this scroll bar.

void setValue(int newValue)


25
Sets the value of this scroll bar to the specified value.

void setValueIsAdjusting(boolean b)
26
Sets the valueIsAdjusting property.

void setValues(int value, int visible, int minimum, int maximum)


27
Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum.

void setVisibleAmount(int newAmount)


28
Sets the visible amount of this scroll bar.

AccessibleContext getAccessibleContext()
29
Gets the AccessibleContext associated with this Scrollbar.

AdjustmentListener[] getAdjustmentListeners()
30
Returns an array of all the adjustment listeners registered on this scrollbar.

<T extends EventListener>T[] getListeners(Class<T> listenerType)


31
Returns an array of all the objects currently registered as FooListeners upon this Scrollbar.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Component

 java.lang.Object
Choice Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showScrollbarDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showScrollbarDemo(){


headerLabel.setText("Control in action: Scrollbar");

final Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL);


final Scrollbar verticalScroller = new Scrollbar();
verticalScroller.setOrientation(Scrollbar.VERTICAL);
horizontalScroller.setMaximum (100);
horizontalScroller.setMinimum (1);
verticalScroller.setMaximum (100);
verticalScroller.setMinimum (1);

horizontalScroller.addAdjustmentListener(new AdjustmentListener() {

@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
statusLabel.setText("Horozontal: "
+horizontalScroller.getValue()
+" ,Vertical: "
+ verticalScroller.getValue());
}
});

verticalScroller.addAdjustmentListener(new AdjustmentListener() {

@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
statusLabel.setText("Horozontal: "
+horizontalScroller.getValue()
+" ,Vertical: "+ verticalScroller.getValue());
}
});

controlPanel.add(horizontalScroller);
controlPanel.add(verticalScroller);

mainFrame.setVisible(true);
}
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
Introduction
Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

Class declaration
Following is the declaration for java.awt.Dialog class:

public class Dialog


extends Window

Field
Following are the fields for java.awt.Image class:
 static Dialog.ModalityType DEFAULT_MODALITY_TYPE -- Default modality type for modal dialogs.

Class constructors
S.N. Constructor & Description

Dialog(Dialog owner)
1
Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an empty title.

Dialog(Dialog owner, String title)


2
Constructs an initially invisible, modeless Dialog with the specified owner Dialog and title.

Dialog(Dialog owner, String title, boolean modal)


3
Constructs an initially invisible Dialog with the specified owner Dialog, title, and modality.

Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)


4
Constructs an initially invisible Dialog with the specified owner Dialog, title, modality and GraphicsConfiguration.

Dialog(Frame owner)
5
Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title.

Dialog(Frame owner, boolean modal)


6
Constructs an initially invisible Dialog with the specified owner Frame and modality and an empty title.

Dialog(Frame owner, String title)


7
Constructs an initially invisible, modeless Dialog with the specified owner Frame and title.

Dialog(Frame owner, String title, boolean modal)


8
Constructs an initially invisible Dialog with the specified owner Frame, title and modality.

Dialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)


9
Constructs an initially invisible Dialog with the specified owner Frame, title, modality, and GraphicsConfiguration.

Dialog(Window owner)
10
Constructs an initially invisible, modeless Dialog with the specified owner Window and an empty title.

Dialog(Window owner, Dialog.ModalityType modalityType)


11
Constructs an initially invisible Dialog with the specified owner Window and modality and an empty title.

Dialog(Window owner, String title)


12
Constructs an initially invisible, modeless Dialog with the specified owner Window and title.

Dialog(Window owner, String title, Dialog.ModalityType modalityType)


13
Constructs an initially invisible Dialog with the specified owner Window, title and modality.

Dialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)


14
Constructs an initially invisible Dialog with the specified owner Window, title, modality and GraphicsConfiguration
Class methods
S.N. Method & Description

void addNotify()
1
Makes this Dialog displayable by connecting it to a native screen resource.

AccessibleContext getAccessibleContext()
2
Gets the AccessibleContext associated with this Dialog.

Dialog.ModalityType getModalityType()
3
Returns the modality type of this dialog.

String getTitle()
4
Gets the title of the dialog.

void hide()
5
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).

boolean isModal()
6
Indicates whether the dialog is modal.

boolean isResizable()
7
Indicates whether this dialog is resizable by the user.

boolean isUndecorated()
8
Indicates whether this dialog is undecorated.

protected String paramString()


9
Returns a string representing the state of this dialog.

void setModal(boolean modal)


10
Specifies whether this dialog should be modal.

void setModalityType(Dialog.ModalityType type)


11
Sets the modality type for this dialog.

void setResizable(boolean resizable)


12
Sets whether this dialog is resizable by the user.

void setTitle(String title)


13
Sets the title of the Dialog.

void setUndecorated(boolean undecorated)


14
Disables or enables decorations for this dialog.
void setVisible(boolean b)
15
Shows or hides this Dialog depending on the value of parameter b.

void show()
16
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).

void toBack()
17 If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active
Window.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Window

 java.awt.Component

 java.lang.Object

Dialog Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showDialogDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showDialogDemo(){


headerLabel.setText("Control in action: Dialog");
Button showAboutDialogButton = new Button("Show About Dialog");
showAboutDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AboutDialog aboutDialog = new AboutDialog(mainFrame);
aboutDialog.setVisible(true);
}
});

controlPanel.add(showAboutDialogButton);
mainFrame.setVisible(true);
}

class AboutDialog extends Dialog {


public AboutDialog(Frame parent){
super(parent, true);
setBackground(Color.gray);
setLayout(new BorderLayout());
Panel panel = new Panel();
panel.add(new Button("Close"));
add("South", panel);
setSize(200,200);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
dispose();
}
});
}

public boolean action(Event evt, Object arg){


if(arg.equals("Close")){
dispose();
return true;
}
return false;
}
public void paint(Graphics g){
g.setColor(Color.white);
g.drawString("TutorialsPoint.Com", 25,70 );
g.drawString("Version 1.0", 60, 90);
}
}
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Introduction
FileDialog control represents a dialog window from which the user can select a file.

Class declaration
Following is the declaration for java.awt.FileDialog class:

public class FileDialog


extends Dialog

Field
Following are the fields for java.awt.Image class:

 static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.

 static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.

Class constructors
S.N. Constructor & Description

FileDialog(Dialog parent)
1
Creates a file dialog for loading a file.

2 FileDialog(Dialog parent, String title)


Creates a file dialog window with the specified title for loading a file.

FileDialog(Dialog parent, String title, int mode)


3
Creates a file dialog window with the specified title for loading or saving a file.

FileDialog(Frame parent)
4
Creates a file dialog for loading a file.

FileDialog(Frame parent, String title)


5
Creates a file dialog window with the specified title for loading a file.

FileDialog(Frame parent, String title, int mode)


6
Creates a file dialog window with the specified title for loading or saving a file.

Class methods
S.N. Method & Description

void addNotify()
1
Creates the file dialog's peer.

String getDirectory()
2
Gets the directory of this file dialog.

String getFile()
3
Gets the selected file of this file dialog.

FilenameFilter getFilenameFilter()
4
Determines this file dialog's filename filter.

int getMode()
5
Indicates whether this file dialog box is for loading from a file or for saving to a file.

protected String paramString()


6
Returns a string representing the state of this FileDialog window.

void setDirectory(String dir)


7
Sets the directory of this file dialog window to be the specified directory.

void setFile(String file)


8
Sets the selected file for this file dialog window to be the specified file.

void setFilenameFilter(FilenameFilter filter)


9
Sets the filename filter for this file dialog window to the specified filter.
void setMode(int mode)
10
Sets the mode of the file dialog.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Dialog

 java.awt.Window

 java.awt.Component

 java.lang.Object

FileDialog Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showFileDialogDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showFileDialogDemo(){


headerLabel.setText("Control in action: FileDialog");

final FileDialog fileDialog = new FileDialog(mainFrame,"Select file");


Button showFileDialogButton = new Button("Open File");
showFileDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileDialog.setVisible(true);
statusLabel.setText("File Selected :"
+ fileDialog.getDirectory() + fileDialog.getFile());
}
});

controlPanel.add(showFileDialogButton);
mainFrame.setVisible(true);
}
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output


What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user
interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through
keyboard,selecting an item from list, scrolling the page are the activities that causes an event to happen.
Types of Event
The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person
interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse,
entering a character through keyboard,selecting an item from list, scrolling the page etc.

 Background Events - Those events that require the interaction of end user are known as background events. Operating system
interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.

What is Event Handling?


Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the
code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events.
This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:

 Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to
it's handler. Java provide as with classes for source object.

 Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation
point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process
the event an then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user
interface element is able to delegate the processing of an event to the separate piece of code. In this model ,Listener needs to be registered
with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event
notifications are sent only to those listener that want to receive them.

Steps involved in event handling


 The User clicks the button and the event is generated.

 Now the object of concerned event class is created automatically and information about the source and the event get populated
with in same object.

 Event object is forwarded to the method of registered listener class.

 the method is now get executed and returns.

Points to remember about listener


 In order to design a listener class we have to develop some listener interfaces.These Listener interfaces forecast some public
abstract callback methods which must be implemented by the listener class.

 If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.
Callback Methods
These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application
developer. Here the callback methods represents an event method. In response to an event java jre will fire callback method. All such
callback methods are provided in listener interfaces.

If a component wants some listener will listen to it's events the the source must register itself to the listener.

Event Handling Example


Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

The Event classes represent the event. Java provides us various Event classes but we will discuss those which are more frequently used.

EventObject class
It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source,
that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package.

Class declaration
Following is the declaration for java.util.EventObject class:

public class EventObject


extends Object
implements Serializable

Field
Following are the fields for java.util.EventObject class:

 protected Object source -- The object on which the Event initially occurred.

Class constructors
S.N. Constructor & Description

EventObject(Object source)
1
Constructs a prototypical Event.

Class methods
S.N. Method & Description

Object getSource()
1
The object on which the Event initially occurred.

2 String toString()
Returns a String representation of this EventObject.

Methods inherited
This class inherits methods from the following classes:

 java.lang.Object

AWT Event Classes:


Following is the list of commonly used event classes.

Sr. No. Control & Description

AWTEvent
1
It is the root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class.

ActionEvent
2
The ActionEvent is generated when button is clicked or the item of a list is double clicked.

InputEvent
3
The InputEvent class is root event class for all component-level input events.

KeyEvent
4
On entering the character the Key event is generated.

MouseEvent
5
This event indicates a mouse action occurred in a component.

TextEvent
6
The object of this class represents the text events.

WindowEvent
7
The object of this class represents the change in state of a window.

AdjustmentEvent
8
The object of this class represents the adjustment event emitted by Adjustable objects.

ComponentEvent
9
The object of this class represents the change in state of a window.

ContainerEvent
10
The object of this class represents the change in state of a window.

11 MouseMotionEvent
The object of this class represents the change in state of a window.

PaintEvent
12
The object of this class represents the change in state of a window

The Event listener represent the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss
those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of
EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from
EventObject.

EventListner interface
It is a marker interface which every listener interface has to extend.This class is defined in java.util package.

Class declaration
Following is the declaration for java.util.EventListener interface:

public interface EventListener

AWT Event Listener Interfaces:


Following is the list of commonly used event listeners.

Sr. No. Control & Description

ActionListener
1
This interface is used for receiving the action events.

ComponentListener
2
This interface is used for receiving the component events.

ItemListener
3
This interface is used for receiving the item events.

KeyListener
4
This interface is used for receiving the key events.

MouseListener
5
This interface is used for receiving the mouse events.

TextListener
6
This interface is used for receiving the text events.

7 WindowListener
This interface is used for receiving the window events.

AdjustmentListener
8
This interface is used for receiving the adjusmtent events.

ContainerListener
9
This interface is used for receiving the container events.

MouseMotionListener
10
This interface is used for receiving the mouse motion events.

FocusListener
11
This interface is used for receiving the focus events.

Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exists as convenience
for creating listener objects.

AWT Adapters:
Following is the list of commonly used adapters while listening GUI events in AWT.

Sr. No. Adapter & Description

FocusAdapter
1
An abstract adapter class for receiving focus events.

KeyAdapter
2
An abstract adapter class for receiving key events.

MouseAdapter
3
An abstract adapter class for receiving mouse events.

MouseMotionAdapter
4
An abstract adapter class for receiving mouse motion events.

WindowAdapter
5
An abstract adapter class for receiving window events.

Introduction
Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular
position within the container. The task of layouting the controls is done automatically by the Layout Manager.
Layout Manager
The layout manager automatically positions all the components within the container. If we do not use layout manager then also the
components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because
of the following two reasons.

 It is very tedious to handle a large number of controls within the container.

 Oftenly the width and height information of a component is not given when we need to arrange them.

Java provide us with various layout manager to position the controls. The properties like size,shape and arrangement varies from one layout
manager to other layout manager. When the size of the applet or the application window changes the size, shape and arrangement of the
components also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.

The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the
LayoutManager interface.

Following are the interfaces defining functionalities of Layout Managers.

Sr.
Interface & Description
No.

LayoutManager
1 The LayoutManager interface declares those methods which need to be implemented by the class whose object will act as a
layout manager.

LayoutManager2
2 The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those classes that know how to layout
containers based on layout constraint object.

AWT Layout Manager Classes:


Following is the list of commonly used controls while designed GUI using AWT.

Sr.
LayoutManager & Description
No.

BorderLayout
1
The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.

CardLayout
2
The CardLayout object treats each component in the container as a card. Only one card is visible at a time.

FlowLayout
3
The FlowLayout is the default layout.It layouts the components in a directional flow.

4 GridLayout
The GridLayout manages the components in form of a rectangular grid.

GridBagLayout
5 This is the most flexible layout manager class.The object of GridBagLayout aligns the component vertically,horizontally or along
their baseline without requiring the components of same size.

Containers are integral part of AWT GUI components. A container provides a space where a component can be located. A Container in
AWT is a component itself and it adds the capability to add component to itself. Following are noticable points to be considered.

 Sub classes of Container are called as Containter. For example Panel, Frame and Window.

 Container can add only Component to itself.

 A default layout is present in each container which can be overridden using setLayout method.

Sr. No. Container & Description

Container
1
It is a generic container object which can contain other AWT components.

AWT UI Elements:
Following is the list of commonly used containers while designed GUI using AWT.

Sr. No. Container & Description

Panel
1
Panel is the simplest container. It provides space in which any other component can be placed, including other panels.

Frame
2
A Frame is a top-level window with a title and a border

Window
3
A Window object is a top-level window with no borders and no menubar

As we know that every top-level window has a menu bar associated with it. This menu bar consist of various menu choices available to the
end user. Further each choice contains list of options which is called drop down menus. Menu and MenuItem controls are subclass of
MenuComponent class.
Menu Hiearchy

Menu Controls
Sr. No. Control & Description

MenuComponent
1
It is the top level class for all menu related controls.

MenuBar
2
The MenuBar object is associated with the top-level window.

MenuItem
3
The items in the menu must belong to the MenuItem or any of its subclass.

Menu
4
The Menu object is a pull-down menu component which is displayed from the menu bar.

CheckboxMenuItem
5
CheckboxMenuItem is subclass of MenuItem.

PopupMenu
6
PopupMenu can be dynamically popped up at a specified position within a component.

Event Handling Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui
>
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}
// check boxes

Used to select more than one option from the n number of options available.

// Demonstrate check boxes.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init() {
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

// Demonstrate check box group.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
public class CBGroup extends Applet implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
winXP = new Checkbox("Windows XP", cbg, true);
winVista = new Checkbox("Windows Vista", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("Mac OS", cbg, false);
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
// Demonstrate Choice lists.
import java.awt.*;
import java.awt.event.*;

import java.applet.*;
/*
<applet code="ChoiceDemo" width=300 height=180>
</applet>
*/
public class ChoiceDemo extends Applet implements ItemListener {
Choice os, browser;
String msg = "";
public void init() {
os = new Choice();
browser = new Choice();
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
// add choice lists to window
add(os);
add(browser);
// register to receive item events
os.addItemListener(this);
browser.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
-os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
// add lists to window
add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}

// Demonstrate text field.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet
implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);

add(name);
add(passp);
add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "
+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}

// Demonstrate TextArea.
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo" width=300 height=250>
</applet>
*/
public class TextAreaDemo extends Applet {
public void init() {
String val =
"Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.\n" +
"Building on a rich heritage, Java has advanced both\n" +
"the art and science of computer language design.\n\n" +
"One of the reasons for Java's ongoing success is its\n" +
"constant, steady rate of evolution. Java has never stood\n" +
"still. Instead, Java has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +
"Moreover, Java has often led the way, charting the\n" +
"course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TestKeyEvent" width=300 height=100>
</applet>
*/
public class TestKeyEvent extends Applet implements KeyListener
{
String msg =" ";
int x=10, y=20;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("key down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key up");
}
public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class TestMouseEvent extends Applet implements MouseListener


{
String msg =" ";
int x=0, y=0;
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=0;
y=10;
msg="mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=0;
y=10;
msg="mouse entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
x=0;
y=10;
msg="mouse exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="mouse down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="mouse up";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}

/*
<applet code="TestMouseEvent" width=300 height=100>
</applet>
*/
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time
than process.

Java Multithreading is mostly used in games, animation etc.

Advantage of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at
same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:

o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process have its own address in memory i.e. each process allocates separate memory area.
o Process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another require some time for saving and loading registers, memory
maps, updating lists etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o Thread is lightweight.
o Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a
common memory area.
As shown in the above figure, thread is executed inside the process. There is context-switching between the
threads. There can be multiple processes inside the OS and one process can have multiple threads.

Note: At a time one thread is executed only.

Do You Know
o How to perform two tasks by two threads ?
o How to perform multithreading by annonymous class ?
o What is the Thread Schedular and what is the difference between preemptive scheduling and time
slicing ?
o What happens if we start a thread twice ?
o What happens if we call the run() method instead of start() method ?
o What is the purpose of join method ?
o Why JVM terminates the daemon thread if there is no user threads remaining ?
o What is the shutdown hook?
o What is garbage collection ?
o What is the purpose of finalize() method ?
o What does gc() method ?
o What is synchronization and why use synchronization ?
o What is the difference between synchronized method and synchronized block ?
o What are the two ways to perform static synchronization ?
o What is deadlock and when it can occur ?
o What is interthread-communication or cooperation ?

What we will learn in Multithreading


o Multithreading
o Life Cycle of a Thread
o Two ways to create a Thread
o How to perform multiple tasks by multiple threads
o Thread Schedular
o Sleeping a thread
o Can we start a thread twice ?
o What happens if we call the run() method instead of start() method ?
o Joining a thread
o Naming a thread
o Priority of a thread
o Daemon Thread
o ShutdownHook
o Garbage collection
o Synchronization with synchronized method
o Synchronized block
o Static synchronization
o Deadlock
o Inter-thread communication
Life cycle of a Thread (Thread States)
1. Life cycle of a thread
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in
java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it
to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

Creating a Thread:

Java defines two ways in which this can be accomplished:

 You can implement the Runnable interface.

 You can extend the Thread class itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class needs to only implement a single method called run( ), which is declared like this:

public void run( )

You will define the code that constitutes the new thread inside run() method. It is important to understand that run()
can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that
class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName);

Here, threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is
specified by threadName.

After the new thread is created, it will not start running until you call its start( ) method, which is declared within
Thread. The start( ) method is shown here:

void start( );

Method-1 : By extend the Thread class of java.lang package.


Syntax...........

class MyThread extends Thread


{
-----------------;
-----------------;
}

Override the run( ) Method-The run( ) method has to be Overridden by writing codes required for the
thread. The thread behaves as per this code segment.

public void run()


{
----------------;
----------------;
}

hen we create a thread by extending Thread class:


-- When we extends a Thread class, whenever we will create our class object internally JVM will create an object to
super class(thread class). so here when we call start() method it will call Thread class start(). internally it will call
this.run(), here this indicates current class object(our class object). So it will call our class run() method.

class MyThread extends Thread


{
int i; //variable i
MyThread(int i) //constructor
{
this.i=i;

}
public void run() //this method override from thread class
{

while(true)
{
System.out.println("BRILLIANT"+i++);
try
{
Thread.sleep(1500); // use for break 1500 mili second
}
catch(InterruptedException e)
{
System.out.println(e);
}
if (i==15 ) // use for terminate the infinite loop
{
System.out.println(Thread.currentThread());
break;
}

}
}
}

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

MyThread m1=new MyThread(1);

m1.start(); // for start thread

System.out.println(Thread.currentThread());
}
}

Method :2 By Implements Runnable Interface.

Note- If you make a thread by using Runnable Interface then it must override the run() method.

public MyThread implements Runnable


{
-----------
-----------

public void run()


{
------
------
}
}
When we implements Runnable interface, we need to create Thread class object seperately, we need to pass our
class object as a parameter to Thread class constructor. When we call start() method with thread class object, it will
calls Thread class start() method from that it will call "this.run()" . Here this indicates Thread class object so it will
call Thread class run() from that it will call our class run() method.

Thread Priority

Thread priority is used by the thread scheduler for determinig the order of execution of threads. And you are
free to set a thread's priority as needed. A higher-priority thread gets more CPU time than a lower priority
one. You can use the method setPriority() of the thread class.
java.lang.Thread class consist 3 variables. They are,
1) MAX_PRIORITY
2) NORM_PRIORITY
3) MIN_PRIORITY

These 3 variables are static variables, so we can directly call with class name.
EX:
Thread.MAX_PRIORITY

to set priorities to a thread we will use setPriority() method and to know a thred's priority we will use getPriority()
method.

1) MAX_PRIORITY

public static final int MAX_PRIORITY


The name itself it tells us it is a maximum priority that a thread can have.

2) NORM_PRIORITY

public static final int NORM_PRIORITY


This is a default priority that is assigned to a thread. If we are not assigning any priority to a thread then by default
it will be having NORM_PRIORITY.

3) MIN_PRIORITY

public static final int MIN_PRIORITY


The name itself it tells us it is a minimum priority that a thread can have.

class MyThread extends Thread


 {
  String name;// name of the thread
  public  MyThread(String name)
    {
    super();
    this.name = name;
   
 }
 // run method implementation
  public void run()
       {
    int count = 0;
    while (true)
       {
      try
        {
        sleep(100);
        } catch (InterruptedException e)
         {
        System.out.println("thread Interrupted" );
          }
      System.out.println(name+":" + count++);
         if (count == 5)
        break;
    }
 }
 
}
// tester class  
public class TestPrority
 {
    public static void main(String[] args)// body of main method
       {
      MyThread thread1 = new  MyThread("thread1");
          System.out.println("current priority of thread :"+thread1.getPriority());
      thread1.setPriority(10);
          System.out.println("after set now priority of thread :"+ thread1.getPriority());
       MyThread thread2 = new  MyThread("thread2");
          System.out.println("current priority of thread :"+ thread1.getPriority());
      thread2.setPriority(1);
          System.out.println("after set now priority of thread :"+ thread1.getPriority());
      thread2.start();
      thread1.start();
     }//main close
}

2-Using isAlive() and join() method with thread

However this is hardly a satisfactory solution and it also raises a larger question; that is how can a thread
know when another thread has ended? So the thread class provides a method isAlive(). This method helps
you to detrmine whetehr a thread isAlive or not. The other method is join(). This method is finished the wait
of any thread. This method waits until the thread on which it is called terminates. Its name comes from the
concept of the calling thread waiting until the specified thread joins it. Additional forms of join() allow you to
specify a maximum amount of time that you want to wait for a specified tread to terminate.

syntax
final boolean isAlive();

the isAlive() method returns a boolean value; true when the thread is still in the running state and otherwise
it return false.

Syntax
final void join();
Eaxmple

class MyThread implements Runnable


{
  String name; // String variable thread
  Thread t;
// defination of constructor.....
MyThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    t.start(); // Start the thread
 }
// body of run method
public void run()
      {
      try {
       for (int i = 0; i < 5; i++) {
        System.out.println(name + ": " + i);
        Thread.sleep(2000);
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
 }
}
 
class Exp_Join {
  public static void main(String args[]) {
   // creating threa ..........
       MyThread ob1 = new MyThread("One");
    MyThread ob2 = new MyThread("Two");
    MyThread ob3 = new MyThread("Three");
  // check it is is Alive or not here ans is true printed because all isAlive
    System.out.println("Thread One is alive: " + ob1.t.isAlive());
    System.out.println("Thread Two is alive: " + ob2.t.isAlive());
    System.out.println("Thread Three is alive: " + ob3.t.isAlive());
   //join() used with in try block because it throws InterruptedException exception
       try {
      System.out.println("Waiting for threads to finish.");
      ob1.t.join();
      ob2.t.join();
      ob3.t.join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }
// now thread is existing so isAlive method return false
    System.out.println("Thread One is alive: " + ob1.t.isAlive());
    System.out.println("Thread Two is alive: " + ob2.t.isAlive());
    System.out.println("Thread Three is alive: " + ob3.t.isAlive());
 
    System.out.println("Main thread exiting.");
 }
}

 OUTPUT:

Thread Synchronization
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the
multiple threads in such a manner that only one thread can access a particular resource at a time

Constructors of java.lang.Thread

java.lang.Thread class consist 8 Constructors. They are,


1) public Thread()
2) public Thread(Runnable target)
3) public Thread(ThreadGroup group,Runnable target)
4) public Thread(String name)
5) public Thread(ThreadGroup group,String name)
6) public Thread(Runnable target,String name)
7) public Thread(ThreadGroup group, Runnable target, String name)
8) public Thread(ThreadGroup group, Runnable target, String name, long stackSize)

java.lang.Thread is a class consist the following methods.

public void start()

-- This method is a special method in java.lang.Thread class. If we call this method then it causes this thread to
begin its execution and it will intimate the JVM to share the resources from the existed resources of a process. and
the JVm will call the run() after sharing the resources.
In general it is never legal to start a thread more than once.

public void run()


-- When we call start() method internally it will call run() method. whatever the logic we are writting inside run()
method that will be executed simultaneously.

public final boolean isAlive()

-- Used to test weather a Thread is still running or dead(completed its execution). returns a boolean value based on
the thread working state.

public final void setPriority(int newPriority)

-- Used to set the priority to a thread.

public final int getPriority()

-- Used to get the priority of a thread.

public final void setName(String name)

-- Used to set the name to a thread.

public final String getName()

-- Used to get the name of a thread.

public final void setDaemon(boolean on)

-- To set a thread as Daemon thread. This method should be applied to a thread before starting it. Otherwise it will
throw IllegalThreadStateException.

public final boolean isDaemon()

-- Used to test a thread is daemon or not and returns a boolean value based on it.

public static Thread currentThread()

-- This method returns the currently executing Thread class object.

public static void yield()

-- Pauses the curently executing thread temporarly, and allows other threads to execute.

public static void sleep(long millis) throws InterruptedException

-- If we apply this method on any thread, hten the currently executing Thread will be in sleep state until the
specified time period in milli seconds. The sleeping thread may be interrupted by other threads, if it is interrupted
then it will throws an exception called interruptedException
public static void sleep(long millis,int nanos) throws InterruptedException

-- If we apply this method on any thread, hten the currently executing Thread will be in sleep state until the
specified time period. The sleeping thread may be interrupted by other threads, if it is interrupted then it will throws
an exception called interruptedException

public Thread.State getState()

-- Returns the current thread state. This method is introduced from jdk 1.5 onwards.

1-Thread with priority

Synchronization

In all situations the simultaneous execution is not suitable, in some cases when we are working with sensitive data,
then we should not allow more than one thread at a time for some security reasons. in such cases we need a
mechanism to restrict the threads from simultaneous execution.

when two or more threads need to access a shared resource which is restricted to allow only one thread at a time we
need a process to synchronize all the threads. This processes of synchronizing the threads is called as
Synchronzation.

In java this synchronization can be achieved by a keyword called synchronized. synchronized keyword can be used
in two ways.
1) synchronized block.
2) synchronized method.

When we are applying synchronization on a piece of code then there will be some lock associated with an object
used to enter into that synchronized area. so at a time one thread can use lock to enter into the synchronized area.
By this we can restrict allowing more than one thred to be execute on a shared resource.

public class SyncBlockExample extends Thread {

static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com",

"is", "the", "best" };

public SyncBlockExample(String id) {


super(id);

public static void main(String[] args) {

SyncBlockExample thread1 = new SyncBlockExample("thread1: ");

SyncBlockExample thread2 = new SyncBlockExample("thread2: ");

thread1.start();

thread2.start();

boolean t1IsAlive = true;

boolean t2IsAlive = true;

do {

if (t1IsAlive && !thread1.isAlive()) {

t1IsAlive = false;

System.out.println("t1 is dead.");

if (t2IsAlive && !thread2.isAlive()) {

t2IsAlive = false;

System.out.println("t2 is dead.");

} while (t1IsAlive || t2IsAlive);

void randomWait() {

try {

Thread.currentThread().sleep((long) (3000 * Math.random()));


} catch (InterruptedException e) {

System.out.println("Interrupted!");

public void run() {

synchronized (System.out)

for (int i = 0; i < msg.length; i++) {

randomWait();

System.out.println(getName() + msg[i]);

Dead Lock

Dead Lock is a situation which occures when two or more threads are blocked forever, waiting for each other.
Thread Dead-Lock may occure because of two or more threads depending on each other.

In general DeadLock occures because of poor synchronization logic written in program. Here is a small example
which explains the dead-lock situation clearly.

public class DeadLockExample {

String o1 = "Lock ";


String o2 = "Step ";

Thread t1 = (new Thread("Printer1") {

public void run() {

while (true) {

synchronized (o1) {

synchronized (o2) {

System.out.println(o1 + o2);

});

Thread t2 = (new Thread("Printer2") {

public void run() {

while (true) {

synchronized (o2) {

synchronized (o1) {

System.out.println(o2 + o1);

}
}

});

public static void main(String[] args) {

DeadLockExample dLock = new DeadLockExample();

dLock.t1.start();

dLock.t2.start();

Inter Thread Communication

Inter thread communication is nothing but thread to thread comminucation(communication between the threads).
Her we will see how a thread communicating with other threads.

First, consider the classic queuing mechanism, where one thread is producing some data and another is consuming
it. Until the second thread has to wait until the first thread transfers the data and vice-versa.

For mor clarification we will discuss this with an example. Let us consider the consumer-producer relationship,
suppose that the producer has to wait until the consumer is finished before it generates more data and vice-versa.

In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once
the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, this
process is continuously going on.

To avoid this problem with polling system, Java includes an sophisticated interthread communication mechanism
via the following methods:
wait(), notify(), notifyAll(). These methods are implemented as final methods in java.lang.Object, so all classes
have them. All the above 3 methods can be called only from a synchronized context(synchronized method/
synchronized block).

In java.lang.Object class, the wait() method is implemented in Various forms that allow you to specify a period of
time to wait.

1)wait() method:

Causes current thread to release the lock and wait until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this
object's monitor.
Syntax:

public final void wait()throws InterruptedException


public final void wait(long timeout)throws InterruptedException

2)notify() method:

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of
them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.

Syntax:

public final void notify()

3)notifyAll() method:

Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()

import java.lang.*;
class MyThread implements Runnable
{
int i;
public void run() //this method overrid from Runnable interface must be,fuctionality as per reqairements
{
i=0;
while(true)
{
System.out.println("BRILLIANT"+i++);
try
{
Thread.sleep(1500); // use for break 1500 mili second
}
catch(InterruptedException e)
{
System.out.println(e);
}
if (i==15 ) // use for terminate the infinite loop
{
System.out.println(Thread.currentThread());
break;
}
}
}
}
class ThreadDemo
{
public static void main(String []args)
{
MyThread r=new MyThread();

Thread t=new Thread(r); // I M P

/*from here run() method call which is override in Runner class*/

t.start(); // for start thread 4 execution

}
}

class MyThread extends Thread


{
String name;// name of the thread
public MyThread(String name)
{
super();
this.name = name;

}
// run method implementation
public void run()
{
int count = 0;
while (true)
{
try
{
sleep(100);
} catch (InterruptedException e)
{
System.out.println("thread Interrupted" );
}
System.out.println(name+":" + count++);
if (count == 5)
break;
}
}

}
// tester class
class TestPriority
{
public static void main(String[] args)// body of main method
{
MyThread thread1 = new MyThread("thread1");
System.out.println("current priority of thread :"+thread1.getPriority());
thread1.setPriority(10);
System.out.println("after set now priority of thread :"+ thread1.getPriority());
MyThread thread2 = new MyThread("thread2");
System.out.println("current priority of thread :"+ thread1.getPriority());
thread2.setPriority(1);
System.out.println("after set now priority of thread :"+ thread1.getPriority());
thread2.start();
thread1.start();
}//main close
}

Files

Java File Write

Java Write To FileThe FileWriter is a class used for writing character files. The constructors of this class assume
that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself,
construct an OutputStreamWriter on a FileOutputStream.

BufferedWriter

The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for
the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:

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

If you execute the above code program will write "Hello Java" into out.txt file. While creating the object of
FileWriter class we have passed the name of the file e.g. "out.txt" as constructor argument.

The BufferedWriter class takes FileWriter object as parameter. The write() method of the BufferedWriter class
actually writes the data into the text file.

Java Read File Line by Line

We will use the DataInputStream class to Read text File Line by Line. Our example program is reading a text file
(textfile.txt) one line at a time using the FileInputStream, DataInputStream and BufferedReader classes. This
example of reading file is efficient and can be used to read large text files also.

Since this program is using the BufferedReader class to read the data from stream line by line, application is using
very less memory and processing power. This program is effective in reading the huge text files which can range
into many GB's in size.

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

Java File Write

Java Write To FileThe FileWriter is a class used for writing character files. The constructors of this class assume
that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself,
construct an OutputStreamWriter on a FileOutputStream.

BufferedWriter

The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for
the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:

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

If you execute the above code program will write "Hello Java" into out.txt file. While creating the object of
FileWriter class we have passed the name of the file e.g. "out.txt" as constructor argument.

The BufferedWriter class takes FileWriter object as parameter. The write() method of the BufferedWriter class
actually writes the data into the text file.

Java Read File Line by Line


We will use the DataInputStream class to Read text File Line by Line. Our example program is reading a text file
(textfile.txt) one line at a time using the FileInputStream, DataInputStream and BufferedReader classes. This
example of reading file is efficient and can be used to read large text files also.

Since this program is using the BufferedReader class to read the data from stream line by line, application is using
very less memory and processing power. This program is effective in reading the huge text files which can range
into many GB's in size.

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

Class DataInputStream

The DataInputStream is convenient class for reading the primitive data from the input stream. The data read by
DataInputStream is independent of the OS and machine. It can read the data from any input stream. The
DataInputStream class can also read the data from output stream written by any other program. In our example
discussed we are just reading the text file one line at a time. The DataInputStream class must be used carefully as it
not thread safe. Programmer must write own code for making the read thread safe in a multi threaded environment.

Implementing Data input streams and data output strings basically represents Unicode strings in such a format that
can be regarded as a slight modification of UTF-8. UTF-8 or UCS Transformation Format-8-bit is a variable-width
encoding which encodes each Unicode character in a set of 1 to 4 octets in which the number of octets is dependent
upon the integer value assigned to the Unicode character. At present, UTF-8 is one of the major and dominant
character encoding for the World Wide Web, which accounts for over half of all Web pages.

Important methods of DataInputStream class are:

read(byte[] b)
read(byte[] b, int off, int len)
readFully(byte[] b)
readDouble()

Constructor of DataInputStream class

Here are the constructor of DataInputStream class.

DataInputStream(InputStream in) - In this Constructor DataInputStream takes InputStream as constructor argument.

The BufferedReader class

The BufferedReader class is used to read data from the character input stream every efficiently. It can read data
efficiently as characters, arrays and even lines. This class is very useful in reading the file line be line in Java very
easily. You just have to create the object of BufferedReader class by passing the the DataInputStream as
constructor parameter and then use the methods of BufferedReader class to read the desired data as characters,
array or lines.

The BufferedReader class uses the default buffer size of 8192 chars for reading the data into buffer. This buffer
size is sufficient for general applications. But it is also possible to specify the buffer size as per requirement.

Here are the constructor of BufferedReader class:

BufferedReader(Reader in) - This constructor is using the default buffer size.

BufferedReader(Reader in, int sz) - Here second argument takes the buffer size as parameter.

If you don't use the BufferedReader class for reading the data line by line then the performance of the application
will be very low. Because each request to the Reader internally sends the read request for underlying character or
byte stream which is resource hungry and time consuming. So, developers should use the BufferedReader class to
read the character stream.

Here is the example of using BufferedReader class:


BufferedReader in
= new BufferedReader(new FileReader("myfile.txt"));

If you don't use the buffering then the application performance will be slow. Since each time you calls the read() or
readLine() method, the data will be read from the the file itself and convert into the characters. So to read the file
line by line in Java you should always use the BufferedReader class.

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an
appropriate BufferedReader.

appended to an existing file. We will use the class FileWriter and BufferedWriter to append the data to a file.

FileWriter
The FileWriter is a class used for writing character files. The constructors of this class assume that the default
character encoding and the default byte-buffer size are acceptable. This constructor simply overwrite the contents in
the file by the specified string but if you put the boolean value as true with the file name (argument of the
constructor) then the constructor append the specified data to the file i.e. the pre-exist data in a file is not
overwritten and the new data is appended after the pre-exist data.

BufferedWriter

The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for
the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:


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

copy contents from one file to another file. This topic is related to the I/O (input/output) of java.io package.

In this example we are using File class of java.io package. The File class is an abstract representation of file and
directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract
pathname has two components:

An optional system-dependent prefix string,


such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
A sequence of zero or more string names.

Explanation

This program copies one file to another file. We will be declaring a function called copyfile which copies the
contents from one specified file to another specified file.

copyfile(String srFile, String dtFile)

The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new
File instance for the file name passed as parameter

File f1 = new File(srFile);


File f2 = new File(dtFile);

and creates another InputStream instance for the input object and OutputStream instance for the output object
passed as parameter

InputStream in = new FileInputStream(f1);


OutputStream out = new FileOutputStream(f2);

and then create a byte type buffer for buffering the contents of one file and write to another specified file from the
first one specified file.

// For creating a byte type buffer


byte[] buf = new byte[1024];
// For writing to another specified file from buffer buf
out.write(buf, 0, len);

Code of the Program :


import java.io.*;

public class CopyFile{


private static void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

//For Append the file.


// OutputStream out = new FileOutputStream(f2,true);

//For Overwrite the file.


OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];


int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
switch(args.length){
case 0: ("File has not mentioned.");
System.exit(0);
case 1: System.out.println("Destination file has not mentioned.");
System.exit(0);
case 2: copyfile(args[0],args[1]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}
Deleting File

Explanation

This program takes an input for the file name to be deleted and deletes the specified file if that exists. We will be
declaring a function called deletefile() which deletes the specified directory or file.

deletefile(String file)

The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the
file name passed as parameter

File f1 = new File(file);

and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returns true if and
only if the file or directory is successfully deleted; false otherwise.

delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the
directory must be empty in order to be deleted.

Returns:

true if and only if the file or directory is successfully deleted; false otherwise

Code of the Program :


import java.io.*;

public class DeleteFile{

private static void deletefile(String file){

File f1 = new File(file);

boolean success = f1.delete();

if (!success){

System.out.println("Deletion failed.");

System.exit(0);
}
else{
System.out.println("File deleted.");
}
}

public static void main(String[] args){

switch(args.length){

case 0: System.out.println("File has not mentioned.");

System.exit(0);

case 1: deletefile(args[0]);

System.exit(0);

default : System.out.println("Multiple files are not allow.");

System.exit(0);

Java Collections
Overview of Collections Framework
A collection is group of objects, known as its elements. The Collections framework in java helps us to store the
data elements of different data types as well as in grouping various objects.Objects can either be of similar type or
different types. Untill now,we have used arrays to store data elements but with arrays we generally face the
following problems:
 Array can only store the data elements or objects of similar type
 Adding or deleting array element is difficult.

To Overcome these problems,a new concept called Collections framework was introduced in J2SE 1.2 and was
expanded in 1.4 and again in Java 5, and yet again in Java 6, gives you lists, sets, maps, and queues to satisfy most
of your coding needs.
A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfaces
and a set of standard utility methods and algorithms. In addition, the framework also provides several abstract
implementations, which are designed to make it easier for you to create new and different implementations for
handling collections of data.

Core Collection Interfaces


The core interfaces that define common functionality and allow collections to be manipulated independent of their
implementation.
The core Interfaces used in the Collection framework are:
 Collection
 List
 Set
 QueueSortedSet
 NavigableSet
 Map
 SortedMap
 NavigableMap

Please note that Collection and Map are two top level interfaces.

Collections come in four basic flavors:

 Lists Lists of things (classes that implement List).


 Sets Unique things (classes that implement Set).
 Maps Things with a unique ID (classes that implement Map).
 Queues Things arranged by the order in which they are to be processed.
The List Interface :
List cares about index(i.e order) and allows duplicates. The List interface is used to manage the order of the
elements or objects in a collection. The three List implementations are ArrayList,Vector and LinkedList.

ArrayList:
ArrayList is an array which grows dynamically.It gives you fast iteration and fast random access. To state the
obvious: it is an ordered collection (by index), but not sorted.ArrayList now implements the new RandomAccess
interface—a marker interface (meaning it has no methods) that says, "this list supports fast (generally constant
time) random access".Choose the ArrayList over a LinkedList when you need fast iteration but aren't as likely
to be doing a lot of insertion and deletion.

Vector:
A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety.You'll
normally want to use ArrayList instead of Vector because the synchronized methods add a performance hit you
might not need. And if you do need thread safety, there are utility methods in class Collections that can help. Vector
is the only class other than ArrayList to implement RandomAccess.

LinkedList:
A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one
another. This linkage gives you new methods (beyond what you get from the List interface) for adding and
removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in
mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast
insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue
interface. As such, it now supports the common queue methods: peek(), poll(), and offer().

Set Interface :
A Set cares about uniqueness—it doesn't allow duplicates.The three Set implementations are described in the
following sections.

HashSet:
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient
your hashCode() implementation the better access performance you'll get. Use this class when you want a collection
with no duplicates and you don't care about order when you iterate through it.

LinkedHashSet:
A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this
class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is
unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

TreeSet:
The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure (but you
knew that), and guarantees that the elements will be in ascending order, according to natural order. Optionally, you
can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should
be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator. As of
Java 6, TreeSet implements NavigableSet.

Map Interface :
A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and
the value are, of course, objects. You're probably quite familiar with Maps since many languages support data
structures that use a key/value or name/value pair. The Map implementations let you do things like search for a
value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets,
Maps rely on the equals() method to determine whether two keys are the same or different.

HashMap:
The HashMap gives you an unsorted, unordered Map. When you need a Map and you don't care about the order
(when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead. Where the
keys land in the Map is based on the key's hashcode, so, like HashSet, the more efficient your hashCode()
implementation, the better access performance you'll get. HashMap allows one null key and multiple null values in
a collection.

Hashtable:
Like Vector, Hashtable has existed from prehistoric Java times. For fun, don't forget to note the naming
inconsistency: HashMap vs. Hashtable. Where's the capitalization of t? Oh well, you won't be expected to spell it.
Anyway, just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the
synchronized counterpart to HashMap. Remember that you don't synchronize a class, so when we say that Vector
and Hashtable are synchronized, we just mean that the key methods of the class are synchronized. Another
difference, though, is that while HashMap lets you have null values as well as one null key, a Hashtable doesn't let
you have anything that's null.

LinkedHashMap:
Like its Set counterpart, LinkedHashSet, the LinkedHash- Map collection maintains insertion order (or, optionally,
access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can
expect faster iteration with a LinkedHashMap.

TreeMap:
You can probably guess by now that a TreeMap is a sorted Map. And you already know that by default, this means
"sorted by the natural order of the elements." Like TreeSet, TreeMap lets you define a custom sort order (via a
Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to
one another when they're being ordered. As of Java 6, TreeMap implements NavigableMap.

Queue Interface:
A Queue is designed to hold a list of "to-dos," or things to be processed in some way. Although other orders are
possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection
methods and they also add methods to add and subtract elements and review queue elements.
PriorityQueue:
This class is new with Java 5. Since the LinkedList class has been enhanced to implement the Queue interface,
basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority
out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering
(in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case,
the elements' ordering represents their relative priority.

Collection represents the group of objects. Depending on the method of storing and retrieving, collections are
basically divided into three parts – Set, Map and List. Where Set does not contain duplicate values, Map contains
key value type of data whereas List can have a duplicate values stored in it sequentially. This framework is
provided in “java.util” package. Collection is the parent interface of all collections in java.

Following list describes the core collection interfaces.

Java Collection Interfaces

Collection — the root of the collection hierarchy. A collection represents a group of objects known as its
elements. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are
unordered. The Java platform doesn’t provide any direct implementations of this interface but provides
implementations of more specific sub interfaces, such as Set and List.

Set — a collection that cannot contain duplicate elements

List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a
List generally has precise control over where in the list each element is inserted and can access elements by their
integer index (position).

Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a
Queue provides additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the
exceptions are priority queues, which order elements according to a supplied comparator or the elements’ natural
ordering.
Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one
value. If you’ve used Hashtable, you’re already familiar with the basics of Map.

Concrete Classes :

Java Collection interfaces and concrete classes

HashSet :
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no
guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant
over time. This class permits the null element.

LinkedHashSet :
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation
differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list
defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note
that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if
s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation).

Interface SortedSet:
A set that further guarantees that its iterator will traverse the set in ascending element order, sorted according to the
natural ordering of its elements (see Comparable), or by a Comparator provided at sorted set creation time. Several
additional operations are provided to take advantage of the ordering. (This interface is the set analogue of
SortedMap).

TreeSet:
This class implements the Set interface, backed by a TreeMap instance. This class guarantees that the sorted set
will be in ascending element order, sorted according to the natural order of the elements (seeComparable), or by the
comparator provided at set creation time, depending on which constructor is used.

ArrayList:
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all
elements, including null. In addition to implementing the List interface, this class provides methods to manipulate
the size of the array that is used internally to store the list.

Vector:
This class is roughly equivalent to ArrayList except it is Synchronized.

LinkedList:
Linked list implementation of the List and Queue interfaces. Implements all optional operations, and permits all
elements (including null).

JAVA Map interface and concrete classes

HashMap:
The HashMap class is roughly equivalent toHashtable, except that it is unsynchronized and permits nulls.

HashTable:
Hash table based implementation of the Map interface. This implementation provides all of the optional map
operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in
particular, it does not guarantee that the order will remain constant over time.
LinkedHashMap:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This
implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map
(insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.

TreeMap:
This class guarantees that the map will be in ascending key order, sorted according to the natural order for the
key’s class (seeComparable), or by the comparator provided at creation time, depending on which constructor is
used.

Note :
To synchronize the Set Concrete classes, use below code:

1 Set s = Collections.synchronizedSet(CONCREATECLASS_OBJECT);

To Synchronize the List Concreate classes :

1 List list = Collections.synchronizedList(CONCREATECLASS_OBJECT);

package: A collection of classes. The built-in Java classes are organized in packages.
A package name consists of several components separated by periods. A package name needs to follow these guidelines:

A package name must be singular. For example, write interface.play instead of interface.plays.

The first component of the package should be in lowercase. You can name subsequent components according to an organization’s internal
naming conventions.

For global packages, which are distributed to other organizations, the first component should be one of the standard top-level domain
names, such as com, edu, gov, mil, net, and org. For example, com.netsoft.interface.play represents a global package name. Notice that it is
prefixed with the standard top-level domain name, com.
All standard Java distribution packages are prefixed with either java or javax. This helps maintain consistency in java package names
regardless of the vendor of the Java development environment

Package Name  Description


java.lang Basic language functionality and fundamental types
java.util Collection data structure classes
java.io File operations
java.math Multiprecision arithmetics
java.nio The New I/O framework for Java
java.net Networking operations, sockets, DNS lookups
java.security Key generation, encryption and decryption
java.sql Java Database Connectivity to access databases
java.awt Basic hierarchy of packages for native GUI components
javax.swing Hierarchy of packages for platform-independent rich GUI
java.applet Classes for creating an applet

Create It's Own package

For creating a package we use the following steps.

Defining a Package

To define a package, include a package command as the first statement in a Java source file. Any classes
declared within that file will belong to the specified package. If you omit the package statement then the class
names are put into the default package, that has no name. This is the general form of the package
statement:

Syntax

package packageName;

How to create a hierarchy of packages

To create a hierarchy of packages, separate each package name from the one above it with a period. The
general form of a multilevel package statement:

Syntax

package pkg1[.pkg2[.pkg3]];
A package is a collection of related classes.It helps Organize your classes into a folder structure and make it
easy to locate and use them.
More importantly,It helps improve re-usability.
Syntax:-
1 package;

The following video takes you through the steps of creating a package.
Please be patient . Video will load in some time. If you still face issue viewing video click here
Assignment 1:To create a package
Step 1) Copy the following code into an editor
package p1;
class c1{
public void m1(){
System.out.println("Method m1 of Class c1");
}
public static void main(String args[]){
c1 obj = new c1();
obj.m1();
}
}
Step 2) Save the file as Demo.java. Compile the file as, javac – d . Demo.java
Step 3) Run the code as java p1.c1

Assignment 2) To create a sub-package


Step1) Copy the following code into an editor
package p1.p2;
class c2{

public void m2(){


System.out.println("Method m2 of Class c2");
}
public static void main(String args[]){
c2 obj = new c2();
obj.m2();
}
}
Step 2) Save the file as Demo2.java. Compile the file as javac – d . Demo2.java
Step 3) Run the code as java p1.p2.c2
importing a package
To create an object of a class (bundled in a package), in your code, you have to use its fully qualified name.
Ex.
1 java.awt.event.actionListner object = new java.awt.event.actionListner();
But , it could become tedious to type in the long dot-separated package path name for every class you want to use.
Instead it is recommended you use the import statement.
Syntax
1 import ;
Once imported , you can use the class without mentioning its fully qualified name.
Ex:
import java.awt.event.*; // * signifies all classes in this package
import javax.swing.JFrame // here only the JFrame class is imported
//Usage
JFrame f = new JFrame; // without fully qualified name.
Assignment 3: To import package
Step 1) Copy the code into an editor.

// Using packages created in earlier assignment


package p3;
import p1.*; //imports classes only in package p1 and NOT in the sub-package p2
class c3{
public void m3(){
System.out.println("Method m3 of Class c3");
}
public static void main(String args[]){
c1 obj1 = new c1();
obj1.m1();
p1.p2.c2 obj2 = new p1.p2.c2();
obj2.m2();
}
}
Step 2) Save the file as Demo2.java . Compile the file using the command javac –d .Demo2.java
Step3) Execute the code using the command java p3.c3
Packages – points to note:
• To avoid naming conflicts packages are given names of the domain name of the company in reverse Ex :
com.guru99. com.microsoft, com.infosys etc.
• When a package name is not specified , a class is into the default package (the current working directory)
and the package itself is given no name. Hence you were able to execute assignments earlier.
• While creating a package, care should be taken that the statement for creating ` must be written before any
other import statements
1
2
3 // not allowed
import package p1.*;
package p3;

1
2
3 //correct syntax
package p3;
import package p1.*;
the java.lang package is imported by default for any class that you create in Java. You can study it more in detail
here.
The java API is very extensive , contains classes which can perform almost all your programming tasks right from
Data Structure Manipulation til Networking. More often than not , you will be using API files in your code. You
can see the API documentation here.

How to create User defined packages in Java


by Kanwarpal Singh  |  in Java at  Wednesday, June 12, 2013
Packages can be defined as a method to put Classes,Methods,variables and Interfaces
together in a same pack.This grouping is basically done on the basis of functionality.In
simpler words,packages act as a container for classes.Packages are an important part of
Java,each packages has its own functionality,packages provides following advantages:
 Classes of a particular package of the other program can be easily reused.
 Two different packages can have same class name.
 Packages provides us ways to hide classes from accidental use.

Java supports two types of Packages:


1. Java API(Application Programming Interface) Packages.
2. User defined Packages.

1.Java API Packages:The API packages which are already defined in Java are called Java
API packages,they are also known as built in packages.For Ex:Java.lang, Java.util, Java.io.

2.User defined packages: Java also supports a functionality that the users can define
their own packages.Now the problem arises,that how we can create and run user defined
packages in Java.In order to create new user defined package you need to follow  the
below steps:
 Firstly,you need to create a New folder,give it the name,you want to give to your
package.
 Then you need to create a new class outside that folder and then compile the
package,remember that you need to compile only the package,you should not run
it,because it does not contain any main method.
 Now create new program whatever you want to create.
 Then import the package you had created and then compile and run the program.

package Mine;                                                   //New package declared by user


public class packs
 {
public void display()
{
System.out.println("Welcome to World of Java");
}
}                                            

Now create a program outside the Package folder,the following examples shows how we
had create a program outside the 'Mine' package folder and then we need to import our
package using 'import' keyword,lets see how;

import Mine.*;                                                      //Package is imported


class dort{
public static void main(String args[])
{
packs d=new packs();                                              // Object of Package class is created

d.display();                                                             //Method of our Package is accessed


}
}

The output goes here:

Create a folder called Mine


package Mine;           //New package declared by user
public class packs
 {
public void display()
{
System.out.println("Welcome to World of Java");
}
}         

save the file as packs.java

compile the file packs.java

java
cd..

import Mine.*;                      //Package is imported


class dort{
public static void main(String args[])
{
packs d=new packs();                                              // Object of Package class is created

d.display();                                                             //Method of our Package is accessed


}
}

java the file as dort.java

javac dort.java

java dort

User defined package is created with the help of “package” keyword. Whereas to use a package we use the import keyword.

Demo.java
package abhi;
public class Demo
{
public void sum(int num1,int num2)
{
int result;
result=num1+num2;
System.out.println("the sum of two numbers is:"+result);
}
}

Tester.java
 
import abhi.Demo;
class Tester extends Demo
{
public static void main(String args[])
{
Tester obj=new Tester();
obj.sum(10,20);
}
}

Procedure to run the program:

First compile the Demo.java as follows:

For compilation Demo.java:

javac –d . Demo.java

Secondly compile the Tester.java in another Command Prompt.

For compilation Tester.java:

javac Tester.java

java Tester

Output
Java is a friendly language and permits to create our own packages and use in
programming. We know earlier, Java allows us to create our exceptions. Creating
packages are indispensable in project development where number of developers are
involved doing different modules and tasks. We know packages avoid name collision
problems. Package naming conventions are very helpful to locate the applications
developed by a single individual or team.

Following steps are to be followed in creating and using packages.

Create a package with a .class file


set the classpath from the directory from which you would like to access. It may be
in a different drive and directory. Let us call it as a target directory.
Write a program and use the file from the package.
Let us create a package called forest and place a class called Tiger in it. Access the
package from a different drive and directory.

1st Step: Create a package (forest) and place Tiger.class in it.

Let us assume C:\snr is the current directory where we would like to create the
package.

C:\snr > notepad Tiger.java


package forest;
import java.util.*;
public class Tiger
{
public void getDetails(String nickName, int weight)
{
System.out.println("Tiger nick name is " + nickName);
System.out.println("Tiger weight is " + weight);
}
}
Order of Package Statement

The above program codingwise is very simple but is important to know the steps of
package creation.

package forest;
import java.util.*;
public class Tiger

package is a keyword of Java followed by the package name. Just writing the
package statement followed by the name creates a new package; see how simple
Java is to practice. For this reason, Java is known as a production language.
While creating packages, the order of statements is very important. The order must
be like this, else, compilation error.

Package statement
Import statement
Class declaration
If exists, the package statement must be first one in the program. If exists, the
import statement must be the second one. Our class declaration is the third. Any
order changes, it is a compilation error.

When the code is ready, the next job is compilation. We must compile with package
notation. Package notation uses –d compiler option as follows.

C:\snr > javac -d . Tiger.java


The –d compiler option creates a new folder called forest and places the Tiger.class
in it. The dot (.) is an operating system's environment variable that indicates the
current directory. It is an instruction to the OS to create a directory called forest and
place the Tiger.class in it.

Using Custom-Defined Packages


After creating the package let us use it.

2nd step: Set the classpath from the target directory.

Let us assume D:\sumathi is the target directory. Let us access Tiger.class in forest
package from here.

From the target directory set the classpath following way.

D:\sumathi> set classpath=C:\snr;%classpath%;


classpath is another environment variable which gives the address of the forest
directory to the OS. %classpath% informs the OS to append the already existing
classpath to the current classpath that is right now set.

3rd Step: Now finally, write a program from the target directory D:/sumathi and
access the package.

D:\sumathi> notepad Animal.java


The above statement creates a file called Animal.java and write the code in it, say, as
follows.

import forest.Tiger;
public class Animal
{
public static void main(String args[])
{
Tiger t1 = new Tiger ();
t1.getDetails("Everest", 50);
}
}
The compilation and execution is as usual as follows.

D:\sumathi> javac Animal.java


D:\sumathi> java Animal

Following is the output screen.

- See more at:


http://way2java.com/packages/creating-custom-defined-packages/#sthash.mliMfJU
C.dpuf

Super Keyword

Super is an implicit keyword create by JVM and supply each and every java program for three purpose in other
words super is one of the keyword which is placing in important role in three places.

1. At variable level
2. At method level
3. At constructor level

Need of super keyword:

Whenever the derived class is inherits the base class features, there is a possibility that base class features are
similar to derived class features and JVM gets an ambiguity. In order to differentiate between base class features
and derived class features must be preceded by super keyword.

Syntax:

super.baseclass features.

Super at variable level:

Whenever the derived class inherit base class data members there is a possibility that base class data member are
similar to derived class data member and JVM gets an ambiguity.

In order to differentiate between the data member of base class and derived class, in the context of derived class the
base class data members must be preceded by super keyword.

Syntax:

super.baseclass datamember name

if we are not writing super keyword before the base class data member name than it will be referred as current class
data member name and base class data member are hidden in the context of derived class.

Program without using super keyword


class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+salary);//print current class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}
Output:
Salary: 20000.0

In the above program in Employee and HR class salary is common properties of both class the instance of current
or derived class is referred by instance by default but here we want to refer base class instance variable that is why
why we use super keyword to distinguish between parent/base class instance variable and current/derived class
instance variable.

Program using super keyword al variable level


class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);//print base class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}
Output:
Salary: 10000.0

A java program which listed the concept of super keyword at variable level.

class Bc
{
int a;
void display()
{
System.out.println("Base----------Dis()");
}
}
class Dc extends Bc
{
int a,c;
void set(int x,int y)
{
super.a=x;
this.a=y;
}
void add()
{
c=super.a+this.a;

}
void display()
{

System.out.println("val of a is="+super.a);
System.out.println("val of b is="+a);
System.out.println("sum ="+c);
}
}//DC
class Supervarib
{
public static void main(String[] args)
{
if(args.length!=2)
{
System.out.println("Enter two values");
}
else
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
Dc d1=new Dc();
d1.set(x,y);
d1.add();
d1.display();
}//else
}//main
}//BC

Super at method overriding level

We know that method overriding is equal to method heading is same and method body is different. The process of
re-defining the original method base class into various derived class by inheriting from base class for performing
multiple operations is known as method overriding.

In order to apply method overriding concept, we must apply inheritance principle.

The original method always resides in base class and overriding method always resides in derived classes.

A java program which listed the concept of super keyword at method overriding level.

class Bc
{
void op(int x,int y)
{
System.out.println("this is an base class");
int z=x+y;
System.out.println("sum of base="+z);
}
}
class Ibc extends Bc
{
void op(int x,int y)
{
super.op(x,y);
System.out.println("this is an intermediate class");
int z=x-y;
System.out.println("sub od Ibc="+z);
}
}
class Dc extends Ibc
{
void op(int n1,int n2)
{
super.op(n1,n2);
System.out.println("this is an dervied class");
int r=n1*n2;
System.out.println("mul of Dc="+r);
}
}

class SuperOver
{
public static void main(String[] args)
{
Dc d1=new Dc();
d1.op(10,20);
}
}

Super at constructor level

Whenever we develop any inheritance based application it is highly recommended to create an object of bottom
most derived class because it contains the features of top most based class and intermediate base class.

When we create an object of bottom most derived class first we get the memory space for data member of top most
class second we get the memory space of data member of intermediate base class and at last we get the memory
space for bottom most derived class.

In which order the memory space is created in the same order values must be initialized otherwise we get compile
time error that is first we must initialize top most base class data member, second must be initialize intermediate
base class and at last we must be initialized bottom most derived class data member.

We know that for initializing the data members of top most base class intermediate base class and bottom most
derived class we required constructor concept.

Hence all the above point makes to understand constructor are calling from bottom to top and executing from top to
bottom.

In order to establish the connection between base class and constructor and derived class constructors JVM
provides two implicit functions they are:

1. Super()
2. Super(...)
Super()

It is used for calling super class default constructor from the context of derived class constructors.

Super keyword used to call base class constructor


class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Output:
Employee class Constructor
HR class Constructor

Super(...)

It is used for calling super class parameterize constructor from the context of derived class constructor.

Important rules

Whenever we are using either super() or super(...) in the derived class constructors the super always must be as a
first executable statement in the body of derived class constructor otherwise we get a compile time error.

The following diagram use possibilities of using super() and super(........)


Rule 1 and Rule 3

Whenever the derived class constructor want to call default constructor of base class, in the context of derived class
constructors we write super(). Which is optional to write because every base class constructor contains single form
of default constructor?

Rule 2 and Rule 4

Whenever the derived class constructor wants to call parameterized constructor of base class in the context of
derived class constructor we must write super(...). which is mandatory to write because a base class may contain
multiple forms of parameterized constructors.
This Keyword
This Keyword

“this” is a keyword in java language represents current class object, it can be use in two ways.

1. this . (this dot)


2. this (this off)

this . (this dot)

which can be used to differentiate variable of class and formal parameters of method or constructor.

“this” keyword are used for two purpose, they are

1. it always points to current class object.


2. Whenever the formal parameter and data member of the class are similar and JVM gets an ambiguity (no
clarity between formal parameter and data members of the class).

To differentiate between formal parameter and data member of the class, the data members of the class must be
preceded by “this.”.

Syntax

this.data member of current class.

Note: If any variable is preceded by “this.” JVM treated that variable as class variable.

Example of this keyword


class A
{
int x;
int y;
char z;
A(int x, float z)
{
this.x=x;
this.y=y;
}
void fun1(char z)
{
this.z=z;
System.out.println(this.z);
}
}

class ThisDemo
{
public static void main(String args[])
{
A oa1=new A(10,20.7f);
System.out.println(oa1.x);
System.out.println(oa1.y);
oa1.fun1('H');
}
}
Output:
10
0
H

Note 1: the scope of this keyword is within the class.

Note 2: The main purpose of using “this” keyword in real life application is to differentiate variable of class or
formal parameters of methods or constructor (it is highly recommended to use the same variable name either in a
class or method and constructor while working with similar objects).

this ()

which can be used to call one constructor within the another constructor without creation of objects multiple time
for the same class.

Syntax:

this(); // call no parametrized or default constructor


this(value1,value2,.....) //call parametrize constructor

Rules to use this()

this() always should be the first statement of the constructor. One constructor can call only other single constructor
at a time by using this().
Final Keyword

In java language final keyword can be used in following way.

1. Final at variable level


2. Final at method level
3. Final at class level

Final at variable level

Final keyword is used to make a variable as a constant. This is similar to const in other language. A variable
declared with the final keyword cannot be modified by the program after initialization. This is useful to universal
constants, such as “PI”.

Example:

public class Circle


{
public static final double PI=3.14159;

public static void main(String[] args)


{
System.out.println(PI);
}
}

Final at method level

It makes a method final, meaning that sub classes can not override this method. The compiler checks and gives an
error if you try to override the method.

When we want to restrict overriding, and then make a method as a final.

Example:

public class A
{
public void fun1()
{
............
}
public final void fun2()
{
............
}

}
Class B extends A
{
public void fun1()
{
..............
}
public void fun2()
{
..............// it gives an error because we can not override final method
}
}

Final at class level

It makes a class final, meaning that the class can not be inheriting by other classes. When we want to restrict
inheritance then make class as a final.

Example:

Public final class A


{
........
........
}
Public class B extends A
{
......... // it gives an error, because we can not inherit final class
........
}

Factory Method

A factory method is one whose return type is similar to the class name in which class is present. The purpose of
factory method is to create an object without using new operator.
Rules for writting factory method
1. The return type of the factory method must be similar to class name in which class it presents.
2. Every factory method in java is static.
3. The access specifier of the factory method must be public.

Final Keyword

In java language final keyword can be used in following way.

 Final at variable level

 Final at method level

 Final at class level

Final at variable level

Final keyword is used to make a variable as a constant. This is similar to const in other language. A variable

declared with the final keyword cannot be modified by the program after initialization. This is useful to universal

constants, such as "PI".

Example

public class Circle


{
public static final double PI=3.14159;
public static void main(String[] args)
{
System.out.println(PI);
}
}

Final at method level

It makes a method final, meaning that sub classes can not override this method. The compiler checks and gives an

error if you try to override the method.

When we want to restrict overriding, then make a method as a final.

Example

public class A
{
public void fun1()
{
.......
}
public final void fun2()
{
.......
}

}
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
// it gives an error because we can not override final method
}
}

Example of final keyword at method level


Example

class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");
}
}
class Developer extends Employee
{
void disp()
{
System.out.println("How are you ?");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}
}

Output

It gives an error
Final at class level

It makes a class final, meaning that the class can not be inheriting by other classes. When we want to restrict

inheritance then make class as a final.

Example

public final class A


{
......
......
}
public class B extends A
{
// it gives an error, because we can not inherit final class
}

Example of final keyword at class level


Example

final class Employee


{
int salary=10000;
}
class Developer extends Employee
{
void show()
{
System.out.println("Hello Good Morning");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
}
}

Output

Output:

It gives an error

Static Keyword

The static keyword is used in java mainly for memory management. Static keyword are used with variables,

methods, blocks and nested class. Static is a keyword that are used for share the same variable or method of a

given class. This is used for a constant variable or a method that is the same for every instance of a class. The main

method of a class is generally labeled static.

No object needs to be created to use static variable or call static methods, just put the class name before the static

variable or method to use them. Static method can not call non-static method.

In java language static keyword can be used for following

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

Static variable

If any variable we declared as static is known as static variable.

 Static variable is used for fulfill the common requirement. For Example company name of
employees,college name of students etc. Name of the college is common for all students.

 The static variable allocate memory only once in class area at the time of class loading.
Advantage of static variable

Using static variable we make our program memory efficient (i.e it saves memory).

When and why we use static variable

Suppose we want to store record of all employee of any company, in this case employee id is unique for every

employee but company name is common for all. When we create a static variable as a company name then only

once memory is allocated otherwise it allocate a memory space each time for every employee.

Syntax for declare static variable:

public static variableName;

Syntax for declare static method:

public static void methodName()


{
.......
.......
}

Syntax for access static methods and static variable

Syntax

className.variableName=10;
className.methodName();

Example

public static final double PI=3.1415;


public static void main(String args[])
{
......
......
}
Difference between static and final keyword

static keyword always fixed the memory that means that will be located only once in the program where

as final keyword always fixed the value that means it makes variable values constant.

Note: As for as real time statement there concern every final variable should be declared the static but there is no

compulsion that every static variable declared as final.

Example of static variable.

In the below example College_Name is always same, and it is declared as static.

Example

class Student
{
int roll_no;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.name);
System.out.println(Student.College_Name);
Student s2=new Student();
s2.roll_no=200;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.name);
System.out.println(Student.College_Name);
}
}
Example

Output:

100

abcd

ITM

200

zyx

ITM

In the above example College_Name variable is commonly sharable by both S1 and S2 objects.
In the above image static data variable are store in method are and non static variable is store in java stack. Read

more about this in JVM Architecture chapter

why main method is static ?

Because object is not required to call static method if main() is non-static method, then jvm create object first then

call main() method due to that face the problem of extra memory allocation.
tatic and Non-Static Variable

Memory for non-static variable is created at the time of create an object of class. Memory for static variable is

created only one in the program at the time of loading of class.The variable of any class are classified into two types

 Non-static or instance variable

 Static or class variable

Difference between non-static and static variable

Non-static variable Static variable

These variable should not be preceded by These variables are preceded by static keyword.
any static keyword Example: Example

class A class A
1 { {
int a; static int b;
} }

Memory is allocated for these variable Memory is allocated for these variable at the time
2
whenever an object is created of loading of the class.
Memory is allocated multiple time Memory is allocated for these variable only once
3
whenever a new object is created. in the program.
Non-static variable also known as Memory is allocated at the time of loading
4 instance variable while because memory ofclass so that these are also known
is allocated whenever instance is created. as classvariable.
Static variable are common for every object that
Non-static variable are specific to an
5 means there memory location can be sharable by
object
every object reference or same class.
Non-static variable can access with object
Static variable can access with class reference.
reference.
Syntax
Syntax
6
class_name.variable_name
obj_ref.variable_name
Note: static variable not only can be access with class reference but also some time it can be accessed with object

reference.

Example of static and non-static variable.


Example

class Student
{
int roll_no;
float marks;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.marks=65.8f;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.marks);
System.out.println(s1.name);
System.out.println(Student.College_Name);
//or System.out.println(s1. College_Name); but first is use in real time.
Student s2=new Student();
s2.roll_no=200;
s2.marks=75.8f;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.marks);
System.out.println(s2.name);
System.out.println(Student.College_Name);
}
}
Output

100

65.8

abcd
ITM
200
75.8
zyx
ITM
Note: In the above example College_Name variable is commonly sharable by both S1 and S2 objects.

Understand static and non-static variable using counter

Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor. Since

instance variable gets the memory at the time of object creation, each object will have the copy of the instance

variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count

variable.
Example

class Counter
{
int count=0;//will get memory when instance is created
Counter()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the value of the

static variable, it will retain its value.

Example

class Counter
{
static int count=0; //will get memory only once
Counter()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output

Static and Non-Static Method

In case of static method memory is allocated multiple time whenever method is calling. But memory for static method

is allocated only once at the time of class loading. Method of a class can be declared in two different ways

 Non-static methods

 Static methods

Difference between non-static and static Method

Non-Static method Static method


1 These method never be preceded by These method always preceded by static keyword
static keyword Example:
Example:
static void fun2()
void fun1() {
{
......
......
......
......
}
}

Memory is allocated multiple time Memory is allocated only once at the time of class
2
whenever method is calling. loading.
It is specific to an object so that these are These are common to every object so that it is
3
also known as instance method. also known as member method or class method.
These methods always access with object These property always access with class
reference reference
4 Syntax: Syntax:

Objref.methodname(); className.methodname();
If any method wants to be execute
If any method wants to be execute only once in
5 multiple time that can be declare as non
the program that can be declare as static .
static.

Note: In some cases static methods not only can access with class reference but also can access with object

reference.

Example of Static and non-Static Method


Example

class A
{
void fun1()
{
System.out.println("Hello I am Non-Static");
}
static void fun2()
{
System.out.println("Hello I am Static");
}
}
class Person
{
public static void main(String args[])
{
A oa=new A();
oa.fun1(); // non static method
A.fun2(); // static method
}
}

Output

Hello I am Non-Static

Hello I am Static

Following table represent how the static and non-static properties are accessed in the different static or non-static

method of same class or other class.

Program to accessing static and non-static properties.


Example

class A
{
int y;
void f2()
{
System.out.println("Hello f2()");
}
}
class B
{
int z;
void f3()
{
System.out.println("Hello f3()");
A a1=new A();
a1.f2();
}
}
class Sdemo
{
static int x;
static void f1()
{
System.out.println("Hello f1()");
}
public static void main(String[] args)
{
x=10;
System.out.println("x="+x);
f1();
System.out.println("Hello main");
B b1=new B();
b1.f3();
}
}
Static Block

Static block is a set of statements, which will be executed by the JVM before execution of main method.

At the time of class loading if we want to perform any activity we have to define that activity inside static block

because static block execute at the time of class loading.

In a class we can take any number of static block but all these static block will be execute from top to bottom.

Syntax

static
{
........
//Set of Statements
........
}

Note: In real time application static block can be used whenever we want to execute any instructions or statements

before execution of main method.


Example of static block

class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
public static void main(String args[])
{
System.out.println("This is main()");
}
}

Output

Hello how are u ?

This is main()

Run java program without main method

class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
}

Output

Output:

Hello how are u ?

Exception is thread "main" java.lang.no-suchmethodError:Main


Note: "Exception is thread "main" java.lang.no-suchmethodError:Main" warning is given in java 1.7 and its above

versions
More than one static block in a program

class StaticDemo
{
static
{
System.out.println("First static block");
}
static
{
System.out.println("Second Static block");
}
public static void main(String args[])
{
System.out.println("This is main()");
}
}

Output

Output:

First static block

Second static block

This is main()

Note: "Here static block run according to there order (sequence by) from top to bottom.

Why a static block executes before the main method ?

A class has to be loaded in main memory before we start using it. Static block is executed during class loading. This

is the reason why a static block executes before the main method.
This Keyword

this is a reference variable that refers to the current object. It is a keyword in java language represents

current class object

Usage of this keyword

 this keyword can be used to refer current class instance variable.

 this() can be used to invoke current class constructor.

 this keyword can be used to invoke current class method (implicitly)

 this can be passed as an argument in the method call.

 this can be passed as argument in the constructor call.

 this keyword can also be used to return the current class instance.

Why use this keyword ?

The main purpose of using this keyword is to differentiate the formal parameter and data members of class,

whenever the formal parameter and data members of the class are similar then jvm get ambiguity (no clarity between

formal parameter and member of the class)

To differentiate between formal parameter and data member of the class, the data member of the class must be

preceded by "this".

"this" keyword can be use in two ways.


1. this . (this dot)
2. this() (this off)

this . (this dot)

which can be used to differentiate variable of class and formal parameters of method or constructor.

"this" keyword are used for two purpose, they are


1. It always points to current class object.
2. Whenever the formal parameter and data member of the class are similar and JVM gets an
ambiguity (no clarity between formal parameter and data members of theclass).
To differentiate between formal parameter and data member of the class, the data members of the class must be

preceded by "this".
Syntax

this.data member of current class.

Note: If any variable is preceded by "this" JVM treated that variable as class variable.

Example without this keyword


Example

class Employee
{
int id;
String name;

Employee(int id,String name)


{
id = id;
name = name;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show();
e2.show();
}
}

Output

Output:

0 null

0 null

In the above example, parameter (formal arguments) and instance variables are same that is why we are using this

keyword to distinguish between local variable and instance variable.

Example of this keyword


Example

class Employee
{
int id;
String name;

Employee(int id,String name)


{
this.id = id;
this.name = name;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show();
e2.show();
}
}

Output

111 Harry

112 Jacy

Note 1: the scope of this keyword is within the class.

Note 2: The main purpose of using "this" keyword in real life application is to differentiate variable of class or formal

parameters of methods or constructor (it is highly recommended to use the same variable name either in a class or

method and constructor while working with similar objects).

Example when no need of this keyword


Example

class Employee
{
int id;
String name;

Employee(int i,String n)
{
id = i;
name = n;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show();
e2.show();
}
}

Syntax

111 Harry

112 Jacy

In the above example, no need of use this keyword because parameter (formal arguments) and instance variables

are different. This keyword is only use when parameter (formal arguments) and instance variables are same.

this ()

which can be used to call one constructor within the another constructor without creation of objects multiple time for

the same class.
Syntax

this(); // call no parametrized or default constructor


this(value1,value2,.....) //call parametrize constructor

this keyword used to invoke current class method (implicitly)

By using this keyword you can invoke the method of the current class. If you do not use the this keyword, compiler

automatically adds this keyword at time of invoking of the method.


Example of this keyword

class Student
{
void show()
{
System.out.println("You got A+");
}
void marks()
{
this.show(); //no need to use this here because compiler does it.
}
void display()
{
show(); //compiler act marks() as this.marks()
}
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}
Syntax

You got A+

Rules to use this()

this() always should be the first statement of the constructor. One constructor can call only other single constructor

at a time by using this().
Super Keyword

Super keyword in java is a reference variable that is used to refer parent class object.  Super is an implicit keyword

create by JVM and supply each and every java program for performing important role in three places.

 At variable level

 At method level

 At constructor level

Need of super keyword:

Whenever the derived class is inherits the base class features, there is a possibility that base class features are

similar to derived class features and JVM gets an ambiguity. In order to differentiate between base class features

and derived class features must be preceded by super keyword.

Syntax

super.baseclass features.

Super at variable level:

Whenever the derived class inherit base class data members there is a possibility that base class data member are

similar to derived class data member and JVM gets an ambiguity.

In order to differentiate between the data member of base class and derived class, in the context of derived class the

base class data members must be preceded by super keyword.

Syntax

super.baseclass datamember name

if we are not writing super keyword before the base class data member name than it will be referred as current class

data member name and base class data member are hidden in the context of derived class.
Program without using super keyword
Example

class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+salary);//print current class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}

Output

Salary: 20000.0

In the above program in Employee and HR class salary is common properties of both class the instance of current or

derived class is referred by instance by default but here we want to refer base class instance variable that is why we

use super keyword to distinguish between parent or base class instance variable and current or derived class

instance variable.
Program using super keyword al variable level
Example

class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);//print base class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}

Output

Salary: 10000.0

Super at method level

The super keyword can also be used to invoke or call parent class method. It should be use in case of method

overriding. In other word super keyword use when base class method name and derived class method name have

same name.
Example of super keyword at method level
Example

class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}

class Faculty extends Student


{
void message()
{
System.out.println("Good Morning Students");
}

void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}

public static void main(String args[])


{
Student s=new Student();
s.display();
}
}

Output

Good Morning Students


Good Morning Sir
In the above example Student and Faculty both classes have message() method if we call message() method from

Student class, it will call the message() method of Student class not of Person class because priority of local is high.

In case there is no method in subclass as parent, there is no need to use super. In the example given below

message() method is invoked from Student class but Student class does not have message() method, so you can

directly call message() method.

Program where super is not required


Example

class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}

class Faculty extends Student


{

void display()
{
message();//will invoke or call parent class message() method
}

public static void main(String args[])


{
Student s=new Student();
s.display();
}
}

Output
Good Morning Sir

Super at constructor level

The super keyword can also be used to invoke or call the parent class constructor. Constructor are calling from

bottom to top and executing from top to bottom.

To establish the connection between base class constructor and derived class constructors JVM provides two

implicit methods they are:

 Super()

 Super(...)

Super()

Super() It is used for calling super class default constructor from the context of derived class constructors.

Super keyword used to call base class constructor


Syntax

class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}

Output

Employee class Constructor

HR class Constructor

Note: super() is added in each class constructor automatically by compiler.

In constructor, default constructor is provided by compiler automatically but it also adds  super()before the first

statement of constructor.If you are creating your own constructor and you do not have either this() or super() as the

first statement, compiler will provide super() as the first statement of the constructor.

Super(...)

Super(...) It is used for calling super class parameterize constructor from the context of derived class constructor.
Important rules

Whenever we are using either super() or super(...) in the derived class constructors the superalways must be as a

first executable statement in the body of derived class constructor otherwise we get a compile time error.

The following diagram use possibilities of using super() and super(........)

Rule 1 and Rule 3

Whenever the derived class constructor want to call default constructor of base class, in the context of derived class

constructors we write super(). Which is optional to write because every base class constructor contains

single form of default constructor?


Rule 2 and Rule 4

Whenever the derived class constructor wants to call parameterized constructor of base class in the context of

derived class constructor we must write super(...). which is mandatory to write because a base class may contain

multiple forms of parameterized constructors.

Synchronized Keyword

Synchronized Keyword is used for when we want to allowed only one thread at a time then use Synchronized

modifier. If a method or block declared as a Synchronized then at a time only one thread is allowed to operate on the

given object.

Synchronized is a Modifier which is applicable for the method or block, we can not declare classor variable with this

modifier.
Advantage of Synchronized

The main advantage of Synchronized keyword is we can resolve data inconsistency problem.

Dis-Advantage of Synchronized

The main dis-advantage of Synchronized keyword is it increased the waiting time of thread and effect performance of

the system, Hence if there is no specific requirement it is never recommended to use synchronized keyword.

Volatile Keyword

If the variable keep on changing such type of variables we have to declare with volatile modifier. Volatile is a modifier

applicable only for variables but not for method and class.

If a variable declared as volatile then for every thread a separate local copy will be created. Every intermediate

modification performed by that thread will takes place in local copy instead of master copy. Once the value got

finalized just before terminating the thread the master copy value will be updated with local stable value.

Advantage of Volatile

The main advantage of Volatile keyword is we can resolve data inconsistency problems.

Dis-Advantage of Volatile

The main dis-advantage of Volatile keyword is, crating and maintaining a separate copy for every thread, increases

complexity of the programming and effects performance of the system. Hence if there is no specific requirement it is

never recommended to use volatile keyword, and it is almost outdated keyword.

Note: Volatile variable means its value keep on changing where as final variable means its value never changes.

Hence final-Volatile combination is illegal combination for variables.


Inner Classes

If one class is existing within another class is known as inner class or nested class

Syntax

class Outerclass_name

.....

.....

class Innerclass_name1

.....

.....

class Innerclass_name1

.....

.....

.....

The main purpose of using inner class

 To provide more security by making those inner class properties specific to only outer class but not
for external classes.
 To make more than one property of classes private properties.

Private is a keyword in java language, it is preceded by any variable that property can be access only within the

class but not outside of it (provides more security).

If more than one property of class wants to make as private properties than all can capped under private inner class.

Syntax

class Outerclass_name

private class Innerclass_name

.....

..... //private properties

Note:No outer class made as private class otherwise this is not available for JVM at the time of execution.

Rules to access properties of inner classes

 Inner class properties can be accessed in the outer class with the object reference but not directly.

 Outer class properties can be access directly within the inner class.

 Inner class properties can�t be accessed directly or by creating directly object.


Note: In special situation inner class property can be accessed in the external class by creating special objects with

the reference of its outer class.


Example

class A //outer class


{
void fun1()
{
System.out.println("Hello fun1()"); // inner class properties should be access using
//object reference in outer class.
B ob=new B();
ob.x=10
System.out.println("x= "+ob.x);
ob.fun2();
}
void fun3() // outer class fun3()
{
System.out.println("Hello fun3()");
}
class B // inner class
{
int x; // inner class variable
void fun2() //inner class fun2()
{
System.out.println("Hello fun2()");
fun3(); //outer class properties can be access directly
}
}
}

class C // external class


{
void fun3()
{
System.out.println("Hello fun3()");
}
}

class IncDemo
{
public static void main(String args[])
{
A oa=new A();
oa.fun1();
C oc=new C();
oc.fun3();
}
}

Output

Hello fun1()

X=10

Hello fun2()

Hello fun3()

Accessing inner class properties in the external class

1. If inner class in non static the object can be created with the following syntax

Syntax

class Outer_class

class Inner_class

.....

.....

.....

.....
}

class External_class

Outer_class.Inner_Class objectrefernce=new Outer_Class.External_Class();

2. If inner class is static the object reference can be created with the following syntax

Syntax

class Outer_class

static class Inner_Class

.....

.....

class External_Class

Outer_class.Inner_Class objectrefernce=new Outer_Class.External_Class();

}
Example

class A //Outer class


{
class B // non-static inner class
{
int x; //inner class variable
void fun1() //inner class fun1()
{
System.out.println("Hello fun1()");
}
}
static class C //static inner class
{
int y=20; // inner class variable
void fun2()
{
System.out.println("Hello fun2()");
}
}
}

class IncDemo
{
public static void main(String args[])
{
A.B ob=new A().new.B();
System.out.println(ob.x);
ob.fun1();
A.C oc=new A.C();
System.out.println(oc.y);
oc.fun2();
}
}
Abstract classes

We know that every java program must start with a concept of class that is without classes concept there is no java

program perfect.

In java programming we have two types of classes they are


1. Concrete class
2. Abstract class

Concrete class

A concrete class is one which is containing fully defined methods or implemented method.

Example

class Helloworld
{
void display()
{
System.out.println("Good Morning........");
}
}

Here Helloworld class is containing a defined method and object can be created directly.

Create an object

Helloworld obj=new Helloworld();


obj.display();

Every concrete class have specific feature and these classes are used for specific requirement but not for common

requirement.

If we use concrete classes for fulfill common requirements than such application will get the following limitations.

 Application will take more amount of memory space (main memory).

 Application execution time is more.


 Application performance is decreased.

To overcome above limitation you can use abstract class.

Abstract class

A class that is declared with abstract keyword, is known as abstract class. An abstract class is one which is

containing some defined method and some undefined method. In java programming undefined methods are known

as un-Implemented or abstract method.

Syntax

abstract class className

......

Example

abstract class A
{
.....
}

If any class have any abstract method then that class become an abstract class.

Example

class Vachile
{
abstract void Bike();
}

Class Vachile is become an abstract class because it have abstract Bike() method.

Make class as abstract class

To make the class as abstract class, whose definition must be preceded by a abstract keyword.

Example

abstract class Vachile


{
......
}

Abstract method

An abstract method is one which contains only declaration or prototype but it never contains body or definition. In

order to make any undefined method as abstract whose declaration is must be predefined by abstract keyword.

Syntax

abstract ReturnType methodName(List of formal parameter)


Example

abstract void sum();


abstract void diff(int, int);

Example of abstract class

abstract class Vachile


{
abstract void speed(); // abstract method
}
class Bike extends Vachile
{
void speed()
{
System.out.println("Speed limit is 40 km/hr..");
}
public static void main(String args[])
{
Vachile obj = new Bike(); //indirect object creation
obj.speed();
}
}

Output

Speed limit is 40 km/hr..

Create an Object of abstract class

An object of abstract class can not be created directly but it can be created indirectly. It means you can create an

object of abstract derived class. You can see in above example

Example

Vachile obj = new Bike(); //indirect object creation


Important Points about abstract class

 Abstract class of java always contains common features.

 Every abstract class participate in inheritance.


 Abstract classes definitions should not be made as final because abstract classes always participate
in inheritance classes.

 An object of abstract class can not be created directly but it can be created indirectly.

 All the abstract classes of java makes use of polymorphism along with method overriding for
business logic development and makes use of dynamic binding for execution logic.

Advantage of abstract class

 Less memory space for the application

 Less execution time

 More performance

Why abstract class have no abstract static method ?

In abstract classes we have only abstract instance method but not containing abstract static methods because every

instance method is created for performing repeated operation where as static method is created for performing one

time operations in other word every abstract method is instance but not static.

Abstract base class

An abstract base class is one which is containing physical representation of abstract methods which are inherited by

various sub classes.

Abstract derived class

An abstract derived class is one which is containing logic representation of abstract methods which are inherited

from abstract base class with respect to both abstract base class and abstract derived class one can not create

object s directly but we can create there objects indirectly both abstract base class and abstract derived class are

always reusable by various sub classes.


When the derived class inherits multiple abstract method from abstract base class and if the derived class is not

defining at least one abstract method then the derived class is known as abstract derived class and whose definition

must be made as abstract by using abstract keyword. (When the derived class become an abstract derived class).

If the derived class defined all the abstract methods which are inherited form abstract Base class then the derived

class is known as concrete derived class.

Example of abstract class having method body

abstract class Vachile


{
abstract void speed();
void mileage()
{
System.out.println("Mileage is 60 km/ltr..");
}
}
class Bike extends Vachile
{
void speed()
{
System.out.println("Speed limit is 40 km/hr..");
}
public static void main(String args[])
{
Vachile obj = new Bike();
obj.speed();
obj.mileage();
}
}

Output

Mileage is 60 km/ltr..

Speed limit is 40 km/hr..

Example of abstract class having constructor, data member, methods

abstract class Vachile


{
int limit=40;
Vachile()
{
System.out.println("constructor is invoked");
}
void getDetails()
{
System.out.println("it has two wheels");
}
abstract void run();
}
class Bike extends Vachile
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Vachile obj = new Bike();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
}

Output

constructor is invoked

running safely..

it has two wheels

40

Difference between abstract class and concrete class

Concrete class Abstract class


Concrete class are used for specific Abstract class are used for fulfill common
requirement requirement.
Object of abstract class can not be create
Object of concrete class can be create directly.
directly (can create indirectly).
Concrete class containing fully defined methods Abstract class have both undefined method
or implemented method. and defined method.
Package

A package is a collection of similar types of classes, interfaces and sub-packages.

Purpose of package

The purpose of package concept is to provide common classes and interfaces for any program. In other words if we

want to develop any class or interface which is common for most of the java programs than such common classes

and interfaces must be place in a package.

Packages in Java are the way to organize files when a project has many modules. Same like we organized our files

in Computer. For example we store all movies in one folder and songs inother folder, here also we store same type

of files in a particular package for example in awt package have all classes and interfaces for design GUI

components.
Advantage of package

 Package is used to categorize the classes and interfaces so that they can be easily maintained

 Application development time is less, because reuse the code

 Application memory space is less (main memory)

 Application execution time is less

 Application performance is enhance (improve)

 Redundancy (repetition) of code is minimized

 Package provides access protection.

 Package removes naming collision.

Type of package

Package are classified into two type which are given below.

1. Predefined or built-in package


2. User defined package
Predefined or built-in package

These are the package which are already designed by the Sun Microsystem and supply as a part of java API, every

predefined package is collection of predefined classes, interfaces and sub-package.

User defined package

If any package is design by the user is known as user defined package. User defined package are those which are

developed by java programmer and supply as a part of their project to deal with common requirement.

Rules to create user defined package

 package statement should be the first statement of any package program.

 Choose an appropriate class name or interface name and whose modifier must be public.

 Any package program can contain only one public class or only one public interface but it can
contain any number of normal classes.

 Package program should not contain any main class (that means it should not contain any main())

 modifier of constructor of the class which is present in the package must be public. (This is not
applicable in case of interface because interface have no constructor.)

 The modifier of method of class or interface which is present in the package must be public (This
rule is optional in case of interface because interface methods by default public)

 Every package program should be save either with public class name or public Interface name
Compile package programs

For compilation of package program first we save program with public className.java and it compile using below

syntax:

Syntax

javac -d . className.java

Syntax

javac -d path className.java

Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a separate folder for the

given package in given path. When we give specific path then it create a new folder at that location and when we use

. (dot) then it crate a folder at current working directory.


Note: Any package program can be compile but can not be execute or run. These program can be executed through

user defined program which are importing package program.

Example of package program

Package program which is save with A.java and compile by javac -d . A.java

Example

package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}

Import above class in below program using import packageName.className

Example

import mypack.A;
public class Hello
{
public static void main(String arg[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}

Explanations: In the above program first we create Package program which is save with A.java and compiled

by "javac -d . A.java". Again we import class "A" in class Hello using "import mypack.A;" statement.


Difference between Inheritance and package

Inheritance concept always used to reuse the feature within the program between class to class, interface to

interface and interface to class but not accessing the feature across the program.

Package concept is to reuse the feature both within the program and across the programs between class to class,

interface to interface and interface to class.

Difference between package keyword and import keyword

Package keyword is always used for creating the undefined package and placing common classes and interfaces.

import is a keyword which is used for referring or using the classes and interfaces of a specific package.

Exception Handling

The process of converting system error messages into user friendly error message is known asException handling.

This is one of the powerful feature of Java to handle run time error and maintain normal flow of java application.

Exception

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the

program's Instructions.
Hierarchy of Exception classes

Type of Exception

 Checked Exception

 Un-Checked Exception
Checked Exception

These are the exception are checked at compile-time. In general checked exception also can be handle by

Exception class. The classes that extend Throwable class except RuntimeException are known

as checked exceptions

Only for remember: Checked means checked by compiler so checked exception are checkedat compile-time.

Un-Checked Exception

These are the exception both identifies or raised at run time, these can be handle using RunTimeException class.

Note: In real time application mostly we can handle unchecked exception.

Only for remember: Un-checked means not checked by compiler so un-checked exception arechecked at run-time

not compile time.


Difference between checked Exception and un-checked Exception

Checked Exception Un-Checked Exception


checked Exception are checked at
1 un-checked Exception are checked at run time
compile time
for checked Exception Extend
2 Throwable class except for un-checked Exception extend RuntimeException.
RuntimeException.
e.g. 
e.g. 
ArithmeticException, NullPointerException,
3 IOException, SQLException,
ArrayIndexOutOfBoundsException,
FileNotFoundException etc.
NumberNotFoundException etc.

Difference between Error and Exception

Error Exception
1 Can be handle. Can not be handle.
Example: Example:
2 NoSuchMethodError ClassNotFoundException
OutOfMemoryError NumberFormateException

Handling the Exception

Handling the exception is nothing but converting system error message into user friendly error message in other

word whenever an exception occurs in the java, JVM will create an object appropriate exception of sub class and
generates system error message of by default which are not recommended in real industry. Industry is highly

recommended to convert system error message into user friendly error message by using exception handling

feature.

Use Five keywords for Handling the Exception

 try

 catch

 finally

 throws

 throw

Syntax for handling the exception

Syntax

try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
finally
{
// statements which will execute compulsory
}
Example without Exception Handling
Syntax

class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be zero");
}
}

Abnormally terminate program and give a message like below, this error message is not understandable by user so

we convert this error message into user friendly error message, like "denominator not be zero".

Example of Exception Handling


Example

class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}
}
}

Output

Denominator not be zero

try and catch block

try block

Inside try block we write the block of statements which causes executions at run time in other words try block

always contains problematic statements.

Important points about try block

 If any exception occurs in try block then CPU controls comes out to the try block and executes
appropriate catch block.

 After executing appropriate catch block, even through we use run time statement, CPU control
never goes to try block to execute the rest of the statements.

 Each and every try block must be immediately followed by catch block that is no intermediate
statements are allowed between try and catch block.
Syntax

try
{
.....
}
/* Here no other statements are allowed
between try and catch block */
catch()
{
....
}

 Each and every try block must contains at least one catch block. But it is highly recommended to
write multiple catch blocks for generating multiple user friendly error messages.

 One try block can contains another try block that is nested or inner try block can be possible.
Syntax

try
{
.......
try
{
.......
}
}

catch block

Inside catch block we write the block of statements which will generates user friendly error messages.

catch block important points

 Catch block will execute exception occurs in try block.

 You can write multiple catch blocks for generating multiple user friendly error messages to make
your application strong. You can see below example.

 At a time only one catch block will execute out of multiple catch blocks.

 in catch block you declare an object of sub class and it will be internally referenced by JVM.
Example without Exception Handling
Example

class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be zero");
}
}

Abnormally terminate program and give a message like below, this error message is not understandable by user so

we convert this error message into user friendly error message, like "denominator not be zero".

Example of Exception Handling


Example

class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}
}
}

Output

Denominator not be zero

Multiple catch block

You can write multiple catch blocks for generating multiple user friendly error messages to make your application

strong. You can see below example.

Example

import java.util.*;
class ExceptionDemo
{
public static void main(String[] args)
{
int a, b, ans=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any two numbers: ");
try
{
a=s.nextInt();
b=s.nextInt();
ans=a/b;
System.out.println("Result: "+ans);
}
catch(ArithmeticException ae)
{
System.out.println("Denominator not be zero");
}
catch(Exception e)
{
System.out.println("Enter valid number");
}
}
}

Output

Enter any two number: 5 0

Denominator not be zero

Method Overriding in Java


1. Understanding problem without method overriding
2. Can we override the static method
3. method overloading vs method overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.

In other words, If subclass provides the specific implementation of the method that has been provided by one
of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is already provided by
its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

1. class Vehicle{  
2.   void run(){System.out.println("Vehicle is running");}  
3. }  
4. class Bike extends Vehicle{  
5.     
6.   public static void main(String args[]){  
7.   Bike obj = new Bike();  
8.   obj.run();  
9.   }  
10. }  
Test it Now
Output:Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use
method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method is same and there is IS-A relationship
between the classes, so there is method overriding.

1. class Vehicle{  
2. void run(){System.out.println("Vehicle is running");}  
3. }  
4. class Bike2 extends Vehicle{  
5. void run(){System.out.println("Bike is running safely");}  
6.   
7. public static void main(String args[]){  
8. Bike2 obj = new Bike2();  
9. obj.run();  
10. }  
Test it Now
Output:Bike is running safely
Real example of Java Method Overriding
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest
varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of
interest.

1. class Bank{  
2. int getRateOfInterest(){return 0;}  
3. }  
4.   
5. class SBI extends Bank{  
6. int getRateOfInterest(){return 8;}  
7. }  
8.   
9. class ICICI extends Bank{  
10. int getRateOfInterest(){return 7;}  
11. }  
12. class AXIS extends Bank{  
13. int getRateOfInterest(){return 9;}  
14. }  
15.   
16. class Test2{  
17. public static void main(String args[]){  
18. SBI s=new SBI();  
19. ICICI i=new ICICI();  
20. AXIS a=new AXIS();  
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
24. }  
25. }  
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.

Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object. Static belongs to
class area and instance belongs to heap area.

Can we override java main method?

No, because main is a static method.

Difference between method overloading and method overriding in java


No. Method Overloading Method Overriding

1) Method overloading is used to increase the readability of Method overriding is used to provide the
the program. specific implementation of the method
that is already provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two


classesthat have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter must be In case of method overriding, parameter


different. must be same.

4) Method overloading is the example of compile time Method overriding is the example of run
polymorphism. time polymorphism.

5) In java, method overloading can't be performed by Return type must be same or covariantin
changing return type of the method only. Return type can method overriding.
be same or different in method overloading. But you must
have to change the parameter.

There are many differences between method overloading and method overriding in java. A list of differences
between method overloading and method overriding are given below:

Java Method Overloading example


1. class OverloadingExample{  
2. static int add(int a,int b){return a+b;}  
3. static int add(int a,int b,int c){return a+b+c;}  
4. }  

Java Method Overriding example


1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void eat(){System.out.println("eating bread...");}  
6. }  

ExceptionHandling with MethodOverriding in Java


There are many rules if we talk about methodoverriding with exception handling. The Rules are as follows:
 If the superclass method does not declare an exception
o If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but it can declare unchecked exception.
 If the superclass method declares an exception

o If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.

If the superclass method does not declare an exception

1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare
the checked exception.
1. import java.io.*;  
2. class Parent{  
3.   void msg(){System.out.println("parent");}  
4. }  
5.   
6. class TestExceptionChild extends Parent{  
7.   void msg()throws IOException{  
8.     System.out.println("TestExceptionChild");  
9.   }  
10.   public static void main(String args[]){  
11.    Parent p=new TestExceptionChild();  
12.    p.msg();  
13.   }  
14. }  
Test it Now
Output:Compile Time Error

2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare
the checked exception but can declare unchecked exception.
1. import java.io.*;  
2. class Parent{  
3.   void msg(){System.out.println("parent");}  
4. }  
5.   
6. class TestExceptionChild1 extends Parent{  
7.   void msg()throws ArithmeticException{  
8.     System.out.println("child");  
9.   }  
10.   public static void main(String args[]){  
11.    Parent p=new TestExceptionChild1();  
12.    p.msg();  
13.   }  
14. }  
Test it Now
Output:child

If the superclass method declares an exception

1) Rule: If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent exception


1. import java.io.*;  
2. class Parent{  
3.   void msg()throws ArithmeticException{System.out.println("parent");}  
4. }  
5.   
6. class TestExceptionChild2 extends Parent{  
7.   void msg()throws Exception{System.out.println("child");}  
8.   
9.   public static void main(String args[]){  
10.    Parent p=new TestExceptionChild2();  
11.    try{  
12.    p.msg();  
13.    }catch(Exception e){}  
14.   }  
15. }  
Test it Now
Output:Compile Time Error

Example in case subclass overridden method declares same exception


1. import java.io.*;  
2. class Parent{  
3.   void msg()throws Exception{System.out.println("parent");}  
4. }  
5.   
6. class TestExceptionChild3 extends Parent{  
7.   void msg()throws Exception{System.out.println("child");}  
8.   
9.   public static void main(String args[]){  
10.    Parent p=new TestExceptionChild3();  
11.    try{  
12.    p.msg();  
13.    }catch(Exception e){}  
14.   }  
15. }  
Test it Now
Output:child

Example in case subclass overridden method declares subclass exception


1. import java.io.*;  
2. class Parent{  
3.   void msg()throws Exception{System.out.println("parent");}  
4. }  
5.   
6. class TestExceptionChild4 extends Parent{  
7.   void msg()throws ArithmeticException{System.out.println("child");}  
8.   
9.   public static void main(String args[]){  
10.    Parent p=new TestExceptionChild4();  
11.    try{  
12.    p.msg();  
13.    }catch(Exception e){}  
14.   }  
15. }  
Test it Now
Output:child
Example in case subclass overridden method declares no exception
1. import java.io.*;  
2. class Parent{  
3.   void msg()throws Exception{System.out.println("parent");}  
4. }  
5.   
6. class TestExceptionChild5 extends Parent{  
7.   void msg(){System.out.println("child");}  
8.   
9.   public static void main(String args[]){  
10.    Parent p=new TestExceptionChild5();  
11.    try{  
12.    p.msg();  
13.    }catch(Exception e){}  
14.   }  
15. }  
Test it Now
Output:child

Java Custom Exception


If you are creating your own Exception that is known as custom exception or user-defined exception. Java
custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

1. class InvalidAgeException extends Exception{  
2.  InvalidAgeException(String s){  
3.   super(s);  
4.  }  
5. }  
1. class TestCustomException1{  
2.   
3.    static void validate(int age)throws InvalidAgeException{  
4.      if(age<18)  
5.       throw new InvalidAgeException("not valid");  
6.      else  
7.       System.out.println("welcome to vote");  
8.    }  
9.      
10.    public static void main(String args[]){  
11.       try{  
12.       validate(13);  
13.       }catch(Exception m){System.out.println("Exception occured: "+m);}  
14.   
15.       System.out.println("rest of the code...");  
16.   }  
17. }  

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. static binding (also known as early binding).


2. dynamic binding (also known as late binding).

Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

1. int data=30;  

Here data variable is a type of int.

2) References have a type


1. class Dog{  
2.  public static void main(String args[]){  
3.   Dog d1;//Here d1 is a type of Dog  
4.  }  
5. }  

3) Objects have a type


An object is an instance of particular java class,but it is also an instance of its superclass.
1. class Animal{}  
2.   
3. class Dog extends Animal{  
4.  public static void main(String args[]){  
5.   Dog d1=new Dog();  
6.  }  
7. }  
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding


1. class Dog{  
2.  private void eat(){System.out.println("dog is eating...");}  
3.   
4.  public static void main(String args[]){  
5.   Dog d1=new Dog();  
6.   d1.eat();  
7.  }  
8. }  

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding


1. class Animal{  
2.  void eat(){System.out.println("animal is eating...");}  
3. }  
4.   
5. class Dog extends Animal{  
6.  void eat(){System.out.println("dog is eating...");}  
7.   
8.  public static void main(String args[]){  
9.   Animal a=new Dog();  
10.   a.eat();  
11.  }  
12. }  
Test it Now
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is
also an instance of Animal.So compiler doesn't know its type, only its base type.

Java instanceof
1. java instanceof
2. Example of instanceof operator
3. Applying the instanceof operator with a variable the have null value
4. Downcasting with instanceof operator
5. Downcasting without instanceof operator

The java instanceof operator is used to test whether the object is an instance of the specified type (class or
subclass or interface).

The instanceof in java is also known as type comparison operatorbecause it compares the instance with type.
It returns either true or false. If we apply the instanceof operator with any variable that has null value, it
returns false.

Simple example of java instanceof

Let's see the simple example of instance operator where it tests the current class.

1. class Simple1{  
2.  public static void main(String args[]){  
3.  Simple1 s=new Simple1();  
4.  System.out.println(s instanceof Simple);//true  
5.  }  
6. }  
Test it Now
Output:true

An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of
Dog can be referred by either Dog or Animal class.

Another example of java instanceof operator


1. class Animal{}  
2. class Dog1 extends Animal{//Dog inherits Animal  
3.   
4.  public static void main(String args[]){  
5.  Dog1 d=new Dog1();  
6.  System.out.println(d instanceof Animal);//true  
7.  }  
8. }  
Test it Now
Output:true
instanceof in java with a variable that have null value
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example
given below where we apply instanceof operator with the variable that have null value.

1. class Dog2{  
2.  public static void main(String args[]){  
3.   Dog2 d=null;  
4.   System.out.println(d instanceof Dog2);//false  
5.  }  
6. }  
Test it Now
Output:false

Downcasting with java instanceof operator


When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly,
compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime.
But if we use instanceof operator, downcasting is possible.

1. Dog d=new Animal();//Compilation error  

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

1. Dog d=(Dog)new Animal();  
2. //Compiles successfully but ClassCastException is thrown at runtime  

Possibility of downcasting with instanceof

Let's see the example, where downcasting is possible by instanceof operator.

1. class Animal { }  
2.   
3. class Dog3 extends Animal {  
4.   static void method(Animal a) {  
5.     if(a instanceof Dog3){  
6.        Dog3 d=(Dog3)a;//downcasting  
7.        System.out.println("ok downcasting performed");  
8.     }  
9.   }  
10.    
11.   public static void main (String [] args) {  
12.     Animal a=new Dog3();  
13.     Dog3.method(a);  
14.   }  
15.     
16.  }  
Test it Now
Output:ok downcasting performed

Downcasting without the use of java instanceof

Downcasting can also be performed without the use of instanceof operator as displayed in the following
example:

1. class Animal { }  
2. class Dog4 extends Animal {  
3.   static void method(Animal a) {  
4.        Dog4 d=(Dog4)a;//downcasting  
5.        System.out.println("ok downcasting performed");  
6.   }  
7.    public static void main (String [] args) {  
8.     Animal a=new Dog4();  
9.     Dog4.method(a);  
10.   }  
11. }  
Test it Now
Output:ok downcasting performed

Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast
it, it is fine. But what will happen if we write:

1. Animal a=new Animal();  
2. Dog.method(a);  
3. //Now ClassCastException but not in case of instanceof operator  

Understanding Real use of instanceof in java


Let's see the real use of instanceof keyword by the example given below.

1. interface Printable{}  
2. class A implements Printable{  
3. public void a(){System.out.println("a method");}  
4. }  
5. class B implements Printable{  
6. public void b(){System.out.println("b method");}  
7. }  
8.   
9. class Call{  
10. void invoke(Printable p){//upcasting  
11. if(p instanceof A){  
12. A a=(A)p;//Downcasting   
13. a.a();  
14. }  
15. if(p instanceof B){  
16. B b=(B)p;//Downcasting   
17. b.b();  
18. }  
19.   
20. }  
21. }//end of Call class  
22.   
23. class Test4{  
24. public static void main(String args[]){  
25. Printable p=new B();  
26. Call c=new Call();  
27. c.invoke(p);  
28. }  
29. }  
Test it Now
Output: b method

Covariant Return Type


The covariant return type specifies that the return type may vary in the same direction as the subclass.

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5,
it is possible to override method by changing the return type if subclass overrides any method whose return
type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:

Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.

Simple example of Covariant Return Type


1. class A{  
2. A get(){return this;}  
3. }  
4.   
5. class B1 extends A{  
6. B1 get(){return this;}  
7. void message(){System.out.println("welcome to covariant return type");}  
8.   
9. public static void main(String args[]){  
10. new B1().get().message();  
11. }  
12. }  
Test it Now
Output:welcome to covariant return type
As you can see in the above example, the return type of the get() method of A class is A but the return type
of the get() method of B class is B. Both methods have different return type but it is method overriding. This
is known as covariant return type.

Java Member inner class


A non-static class that is created inside a class but outside a method is called member inner class.

Syntax:

1. class Outer{  
2.  //code  
3.  class Inner{  
4.   //code  
5.  }  
6. }  

Java Member inner class example


In this example, we are creating msg() method in member inner class that is accessing the private data
member of outer class.

1. class TestMemberOuter1{  
2.  private int data=30;  
3.  class Inner{  
4.   void msg(){System.out.println("data is "+data);}  
5.  }  
6.  public static void main(String args[]){  
7.   TestMemberOuter1 obj=new TestMemberOuter1();  
8.   TestMemberOuter1.Inner in=obj.new Inner();  
9.   in.msg();  
10.  }  
11. }  
Test it Now

Output:

data is 30
Internal working of Java member inner class
The java compiler creates two class files in case of inner class. The class file name of inner class is
"Outer$Inner". If you want to instantiate inner class, you must have to create the instance of outer class. In
such case, instance of inner class is created inside the instance of outer class.

Internal code generated by the compiler


The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the
reference of Outer class that is why it can access all the data members of Outer class including private.

1. import java.io.PrintStream;  
2. class Outer$Inner  
3. {  
4.     final Outer this$0;  
5.     Outer$Inner()  
6.     {   super();  
7.         this$0 = Outer.this;  
8.     }  
9.     void msg()  
10.     {  
11.         System.out.println((new StringBuilder()).append("data is ")  
12.                     .append(Outer.access$000(Outer.this)).toString());  
13.     }  
14. }  

Java Anonymous inner class


A class that have no name is known as anonymous inner class in java. It should be used if you have to
override method of class or interface. Java Anonymous inner class can be created by two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class


1. abstract class Person{  
2.   abstract void eat();  
3. }  
4. class TestAnonymousInner{  
5.  public static void main(String args[]){  
6.   Person p=new Person(){  
7.   void eat(){System.out.println("nice fruits");}  
8.   };  
9.   p.eat();  
10.  }  
11. }  
Test it Now

Output:

nice fruits

Internal working of given code


1. Person p=new Person(){  
2. void eat(){System.out.println("nice fruits");}  
3. };  
1. A class is created but its name is decided by the compiler which extends the Person class and provides
the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler


1. import java.io.PrintStream;  
2. static class TestAnonymousInner$1 extends Person  
3. {  
4.    TestAnonymousInner$1(){}  
5.    void eat()  
6.     {  
7.         System.out.println("nice fruits");  
8.     }  
9. }  

Java anonymous inner class example using interface


1. interface Eatable{  
2.  void eat();  
3. }  
4. class TestAnnonymousInner1{  
5.  public static void main(String args[]){  
6.  Eatable e=new Eatable(){  
7.   public void eat(){System.out.println("nice fruits");}  
8.  };  
9.  e.eat();  
10.  }  
11. }  
Test it Now

Output:

nice fruits
Internal working of given code

It performs two main tasks behind this code:

1. Eatable p=new Eatable(){  
2. void eat(){System.out.println("nice fruits");}  
3. };  
1. A class is created but its name is decided by the compiler which implements the Eatable interface and
provides the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of Eatable type.

Internal class generated by the compiler


1. import java.io.PrintStream;  
2. static class TestAnonymousInner1$1 implements Eatable  
3. {  
4. TestAnonymousInner1$1(){}  
5. void eat(){System.out.println("nice fruits");}  
6. }  

Java Local inner class


A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of
local inner class, you must instantiate this class inside the method.

Java local inner class example


1. public class localInner1{  
2.  private int data=30;//instance variable  
3.  void display(){  
4.   class Local{  
5.    void msg(){System.out.println(data);}  
6.   }  
7.   Local l=new Local();  
8.   l.msg();  
9.  }  
10.  public static void main(String args[]){  
11.   localInner1 obj=new localInner1();  
12.   obj.display();  
13.  }  
14. }  
Test it Now

Output:

30
Internal class generated by the compiler

In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.

1. import java.io.PrintStream;  
2. class localInner1$Local  
3. {  
4.     final localInner1 this$0;  
5.     localInner1$Local()  
6.     {     
7.         super();  
8.         this$0 = Simple.this;  
9.     }  
10.     void msg()  
11.     {  
12.         System.out.println(localInner1.access$000(localInner1.this));  
13.     }  
14. }  

Rule: Local variable can't be private, public or protected.

Rules for Java Local Inner class


1) Local inner class cannot be invoked from outside the method.

2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access
the non-final local variable in local inner class.

Example of local inner class with local variable


1. class localInner2{  
2.  private int data=30;//instance variable  
3.  void display(){  
4.   int value=50;//local variable must be final till jdk 1.7 only  
5.   class Local{  
6.    void msg(){System.out.println(value);}  
7.   }  
8.   Local l=new Local();  
9.   l.msg();  
10.  }  
11.  public static void main(String args[]){  
12.   localInner2 obj=new localInner2();  
13.   obj.display();  
14.  }  
15. }  
Test it Now
Output:

50

Java static nested class


A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data
members and methods. It can be accessed by outer class name.

o It can access static data members of outer class including private.


o Static nested class cannot access non-static (instance) data member or method.

Java static nested class example with instance method


1. class TestOuter1{  
2.   static int data=30;  
3.   static class Inner{  
4.    void msg(){System.out.println("data is "+data);}  
5.   }  
6.   public static void main(String args[]){  
7.   TestOuter1.Inner obj=new TestOuter1.Inner();  
8.   obj.msg();  
9.   }  
10. }  
Test it Now

Output:

data is 30

In this example, you need to create the instance of static nested class because it has instance method msg().
But you don't need to create the object of Outer class because nested class is static and static properties,
methods or classes can be accessed without object.

Internal class generated by the compiler


1. import java.io.PrintStream;  
2. static class TestOuter1$Inner  
3. {  
4. TestOuter1$Inner(){}  
5. void msg(){  
6. System.out.println((new StringBuilder()).append("data is ")  
7. .append(TestOuter1.data).toString());  
8. }    
9. }  

Java static nested class example with static method


If you have the static member inside static nested class, you don't need to create instance of static nested
class.

1. class TestOuter2{  
2.   static int data=30;  
3.   static class Inner{  
4.    static void msg(){System.out.println("data is "+data);}  
5.   }  
6.   public static void main(String args[]){  
7.   TestOuter2.Inner.msg();//no need to create the instance of static nested class  
8.   }  
9. }  
Test it Now

Output:

data is 30

Java Nested Interface


An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces
are used to group related interfaces so that they can be easy to maintain. The nested interface must be
referred by the outer interface or class. It can't be accessed directly.

Points to remember for nested interfaces

There are given some points that should be remembered by the java programmer.

o Nested interface must be public if it is declared inside the interface but it can have any access modifier
if declared within the class.
o Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface


1. interface interface_name{  
2.  ...  
3.  interface nested_interface_name{  
4.   ...  
5.  }  
6. }   
Syntax of nested interface which is declared within the class
1. class class_name{  
2.  ...  
3.  interface nested_interface_name{  
4.   ...  
5.  }  
6. }   

Example of nested interface which is declared within the interface


In this example, we are going to learn how to declare the nested interface and how we can access it.
1. interface Showable{  
2.   void show();  
3.   interface Message{  
4.    void msg();  
5.   }  
6. }  
7.   
8. class TestNestedInterface1 implements Showable.Message{  
9.  public void msg(){System.out.println("Hello nested interface");}  
10.   
11.  public static void main(String args[]){  
12.   Showable.Message message=new TestNestedInterface1();//upcasting here  
13.   message.msg();  
14.  }  
15. }  
Test it Now
download the example of nested interface
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer interface
Showable because it cannot be accessed directly. It is just like almirah inside the room, we cannot access
the almirah directly because we must enter the room first. In collection frameword, sun microsystem has
provided a nested interface Entry. Entry is the subinterface of Map i.e. accessed by Map.Entry.

Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
1. public static interface Showable$Message  
2. {  
3.   public abstract void msg();  
4. }  

Example of nested interface which is declared within the class


Let's see how can we define an interface inside the class and how can we access it.
1. class A{  
2.   interface Message{  
3.    void msg();  
4.   }  
5. }  
6.   
7. class TestNestedInterface2 implements A.Message{  
8.  public void msg(){System.out.println("Hello nested interface");}  
9.   
10.  public static void main(String args[]){  
11.   A.Message message=new TestNestedInterface2();//upcasting here  
12.   message.msg();  
13.  }  
14. }  
Test it Now
Output:hello nested interface

Can we define a class inside the interface?

Yes, If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we
define a class within the interface:

1. interface M{  
2.   class A{}  
3. }  
Java Reflection API
Java Reflection is a process of examining or modifying the run time behavior of a class at run time.

The java.lang.Class class provides many methods that can be used to get metadata, examine and change
the run time behavior of a class.

The java.lang and java.lang.reflect packages provide classes for java reflection.

Where it is used

The Reflection API is mainly used in:

 IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.


 Debugger
 Test Tools etc.

Do You Know ?
 How many ways we can get the instance of Class class ?
 How to create the javap tool ?
 How to create the appletviewer tool ?
 How to access the private method from outside the class ?

java.lang.Class class
The java.lang.Class class performs mainly two tasks:

 provides methods to get the metadata of a class at run time.


 provides methods to examine and change the run time behavior of a class.

Commonly used methods of Class class:


Method Description

1) public String getName() returns the class name

2) public static Class forName(String className)throws loads the class and returns
ClassNotFoundException the reference of Class class.

3) public Object newInstance()throws creates new instance.


InstantiationException,IllegalAccessException

4) public boolean isInterface() checks if it is interface.

5) public boolean isArray() checks if it is array.

6) public boolean isPrimitive() checks if it is primitive.

7) public Class getSuperclass() returns the superclass class


reference.

8) public Field[] getDeclaredFields()throws SecurityException returns the total number of


fields of this class.

9) public Method[] getDeclaredMethods()throws SecurityException returns the total number of


methods of this class.

10) public Constructor[] getDeclaredConstructors()throws SecurityException returns the total number of


constructors of this class.

11) public Method getDeclaredMethod(String name,Class[] returns the method class


parameterTypes)throws NoSuchMethodException,SecurityException instance.

How to get the object of Class class?


There are 3 ways to get the instance of Class class. They are as follows:

 forName() method of Class class


 getClass() method of Object class
 the .class syntax

1) forName() method of Class class


 is used to load the class dynamically.
 returns the instance of Class class.
 It should be used if you know the fully qualified name of class.This cannot be used for primitive types.

Let's see the simple example of forName() method.

1. class Simple{}  
2.   
3. class Test{  
4.  public static void main(String args[]){  
5.   Class c=Class.forName("Simple");  
6.   System.out.println(c.getName());  
7.  }  
8. }  
Output:Simple

2) getClass() method of Object class

It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with
primitives.

1. class Simple{}  
2.   
3. class Test{  
4.   void printName(Object obj){  
5.   Class c=obj.getClass();    
6.   System.out.println(c.getName());  
7.   }  
8.   public static void main(String args[]){  
9.    Simple s=new Simple();  
10.    
11.    Test t=new Test();  
12.    t.printName(s);  
13.  }  
14. }  
15.    
Output:Simple

3) The .class syntax

If a type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the
name of the type.It can be used for primitive data type also.

1. class Test{  
2.   public static void main(String args[]){  
3.    Class c = boolean.class;   
4.    System.out.println(c.getName());  
5.   
6.    Class c2 = Test.class;   
7.    System.out.println(c2.getName());  
8.  }  
9. }  
Output:boolean
Test
Determining the class object
Following methods of Class class is used to determine the class object:

1) public boolean isInterface(): determines if the specified Class object represents an interface type.
2) public boolean isArray(): determines if this Class object represents an array class.
3) public boolean isPrimitive(): determines if the specified Class object represents a primitive type.

Let's see the simple example of reflection api to determine the object type.

1. class Simple{}  
2. interface My{}  
3.   
4. class Test{  
5.  public static void main(String args[]){  
6.   try{  
7.    Class c=Class.forName("Simple");  
8.    System.out.println(c.isInterface());  
9.      
10.    Class c2=Class.forName("My");  
11.    System.out.println(c2.isInterface());  
12.     
13.   }catch(Exception e){System.out.println(e);}  
14.   
15.  }  
16. }  

newInstance() method
The newInstance() method of Class class and Constructor class is used to create a new instance of the
class.

The newInstance() method of Class class can invoke zero-argument constructor whereas newInstance()
method of Constructor class can invoke any number of arguments. So Constructor class is preferred over
Class class.
Syntax of newInstance() method of Class class

public T newInstance()throws InstantiationException,IllegalAccessException

Here T is the generic version. You can think it like Object class. You will learn about generics later.

Example of newInstance() method

Let's see the simple example to use newInstance() method.

1. class Simple{  
2.  void message(){System.out.println("Hello Java");}  
3. }  
4.   
5. class Test{  
6.  public static void main(String args[]){  
7.   try{  
8.   Class c=Class.forName("Simple");  
9.   Simple s=(Simple)c.newInstance();  
10.   s.message();  
11.   
12.   }catch(Exception e){System.out.println(e);}  
13.   
14.  }  
15. }  

Understanding javap tool


The javap command disassembles a class file. The javap command displays information about the
fields,constructors and methods present in a class file.

Syntax to use javap tool

Let's see how to use javap tool or command.

1. javap fully_class_name  

Example to use javap tool


1. javap java.lang.Object  
Output:
1. Compiled from "Object.java"  
2. public class java.lang.Object {  
3.   public java.lang.Object();  
4.   public final native java.lang.Class<?> getClass();  
5.   public native int hashCode();  
6.   public boolean equals(java.lang.Object);  
7.   protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException;  
8.   public java.lang.String toString();  
9.   public final native void notify();  
10.   public final native void notifyAll();  
11.   public final native void wait(long) throws java.lang.InterruptedException;  
12.   public final void wait(long, int) throws java.lang.InterruptedException;  
13.   public final void wait() throws java.lang.InterruptedException;  
14.   protected void finalize() throws java.lang.Throwable;  
15.   static {};  
16. }  

Another example to use javap tool for your class

Let's use the javap command for our java file.

1. class Simple{  
2. public static void main(String args[]){  
3. System.out.println("hello java");  
4. }  
5. }  

Now let's use the javap tool to disassemble the class file.

1. javap Simple  
Output:
1. Compiled from ".java"  
2. class Simple {  
3.   Simple();  
4.   public static void main(java.lang.String[]);  
5. }  

javap -c command

You can use the javap -c command to see disassembled code. The code that reflects the java bytecode.

1. javap -c Simple  
Output:
1. Compiled from ".java"  
2. class Simple {  
3.   Simple();  
4.     Code:  
5.        0: aload_0         
6.        1: invokespecial #1                  // Method java/lang/Object."<init>":()V  
7.        4: return          
8.   
9.   public static void main(java.lang.String[]);  
10.     Code:  
11.        0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;  
12.        3: ldc           #3                  // String hello java  
13.        5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/
String;)V  
14.        8: return          
15. }  

Options of javap tool


The important options of javap tool are as follows.

Option Description

-help prints the help message.

-l prints line number and local variable

-c disassembles the code

-s prints internal type signature

-sysinfo shows system info (path, size, date, MD5 hash)

-constants shows static final constants

-version shows version information

Creating a program that works as javap tool


Following methods of java.lang.Class class can be used to display the metadata of a class.

Method Description

public Field[] getDeclaredFields()throws returns an array of Field objects reflecting all the fields
SecurityException declared by the class or interface represented by this Class
object.

public Constructor[] returns an array of Constructor objects reflecting all the


getDeclaredConstructors()throws constructors declared by the class represented by this Class
SecurityException object.
public Method[] getDeclaredMethods()throws returns an array of Method objects reflecting all the
SecurityException methods declared by the class or interface represented by
this Class object.

Example of creating javap tool

Let's create a program that works like javap tool.

1. import java.lang.reflect.*;  
2.   
3. public class MyJavap{  
4.    public static void main(String[] args)throws Exception {  
5.     Class c=Class.forName(args[0]);  
6.       
7.     System.out.println("Fields........");  
8.     Field f[]=c.getDeclaredFields();  
9.     for(int i=0;i<f.length;i++)  
10.         System.out.println(f[i]);  
11.       
12.     System.out.println("Constructors........");  
13.     Constructor con[]=c.getDeclaredConstructors();  
14.     for(int i=0;i<con.length;i++)  
15.         System.out.println(con[i]);  
16.       
17.         System.out.println("Methods........");  
18.     Method m[]=c.getDeclaredMethods();  
19.     for(int i=0;i<m.length;i++)  
20.         System.out.println(m[i]);  
21.    }  
22. }  

At runtime, you can get the details of any class, it may be user-defined or pre-defined class.
Output:
Creating your own appletviewer
As you know well that appletviewer tool creates a frame and displays the output of applet in the frame.You
can also create your frame and display the applet output.

Example that works like appletviewer tool

Let's see the simple example that works like appletviewer tool. This example displays applet on the frame.

1. import java.applet.Applet;  
2. import java.awt.Frame;  
3. import java.awt.Graphics;  
4.   
5. public class MyViewer extends Frame{  
6.   public static void main(String[] args) throws Exception{  
7.     Class c=Class.forName(args[0]);  
8.           
9.     MyViewer v=new MyViewer();  
10.     v.setSize(400,400);  
11.     v.setLayout(null);  
12.     v.setVisible(true);  
13.           
14.     Applet a=(Applet)c.newInstance();  
15.     a.start();  
16.     Graphics g=v.getGraphics();  
17.     a.paint(g);  
18.     a.stop();  
19.           
20.   }  
21.   
22. }  
1. //simple program of applet  
2.   
3. import java.applet.Applet;  
4. import java.awt.Graphics;  
5.   
6. public class First extends Applet{  
7.   
8.     public void paint(Graphics g){g.drawString("Welcome",50, 50);}  
9. }  
Output:
 
How to call private method from another class in java
You can call the private method from outside the class by changing the runtime behaviour of the class.

By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private method from


any other class.
Required methods of Method class

1) public void setAccessible(boolean status) throws SecurityException sets the accessibility of the


method.

2) public Object invoke(Object method, Object... args) throws IllegalAccessException,


IllegalArgumentException, InvocationTargetException is used to invoke the method.

Required method of Class class

1) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws


NoSuchMethodException,SecurityException: returns a Method object that reflects the specified declared
method of the class or interface represented by this Class object.

Example of calling private method from another class

Let's see the simple example to call private method from another class.

File: A.java
1. public class A {  
2.   private void message(){System.out.println("hello java"); }  
3. }  
File: MethodCall.java
1. import java.lang.reflect.Method;  
2. public class MethodCall{  
3. public static void main(String[] args)throws Exception{  
4.   
5.     Class c = Class.forName("A");  
6.     Object o= c.newInstance();  
7.     Method m =c.getDeclaredMethod("message", null);  
8.     m.setAccessible(true);  
9.     m.invoke(o, null);  
10. }  
11. }  
Output:hello java
Another example to call parameterized private method from another class

Let's see the example to call parameterized private method from another class

File: A.java
1. class A{  
2. private void cube(int n){System.out.println(n*n*n);}  
3. }  
File: M.java
1. import java.lang.reflect.*;  
2. class M{  
3. public static void main(String args[])throws Exception{  
4. Class c=A.class;  
5. Object obj=c.newInstance();  
6.   
7. Method m=c.getDeclaredMethod("cube",new Class[]{int.class});  
8. m.setAccessible(true);  
9. m.invoke(obj,4);  
10. }}  
Output:64
Serialization in Java
1. Serialization
2. Serializable Interface
3. Example of Serialization
4. Deserialization
5. Example of Deserialization
6. Serialization with Inheritance
7. Externalizable interface
8. Serialization and static datamember

Serialization in java is a mechanism of writing the state of an object into a byte stream.

It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.

The reverse operation of serialization is called deserialization.

The String class and all the wrapper classes implementsjava.io.Serializable interface by default.

Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marshaling).

java.io.Serializable interface
Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a
certain capability.

It must be implemented by the class whose object you want to persist. Let's see the example given below:

1. import java.io.Serializable;  
2. public class Student implements Serializable{  
3.  int id;  
4.  String name;  
5.  public Student(int id, String name) {  
6.   this.id = id;  
7.   this.name = name;  
8.  }  
9. }  
ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types and Java objects to an OutputStream.
Only objects that support the java.io.Serializable interface can be written to streams.

Constructor
1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an ObjectOutputStream that
writes to the specified OutputStream.

Important Methods
Method Description

1) public final void writeObject(Object obj) throws writes the specified object to the
IOException {} ObjectOutputStream.

2) public void flush() throws IOException {} flushes the current output stream.

3) public void close() throws IOException {} closes the current output stream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class. The writeObject() method of
ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the
object in the file named f.txt.

1. import java.io.*;  
2. class Persist{  
3.  public static void main(String args[])throws Exception{  
4.   Student s1 =new Student(211,"ravi");  
5.   
6.   FileOutputStream fout=new FileOutputStream("f.txt");  
7.   ObjectOutputStream out=new ObjectOutputStream(fout);  
8.   
9.   out.writeObject(s1);  
10.   out.flush();  
11.   System.out.println("success");  
12.  }  
13. }  
success
download this example of serialization
Deserialization in java
Deserialization is the process of reconstructing the object from the serialized state.It is the reverse
operation of serialization.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor
1) public ObjectInputStream(InputStream in) throws creates an ObjectInputStream that reads from
IOException {} the specified InputStream.

Important Methods
Method Description

1) public final Object readObject() throws IOException, reads an object from the input
ClassNotFoundException{} stream.

2) public void close() throws IOException {} closes ObjectInputStream.

Example of Java Deserialization


1. import java.io.*;  
2. class Depersist{  
3.  public static void main(String args[])throws Exception{  
4.     
5.   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
6.   Student s=(Student)in.readObject();  
7.   System.out.println(s.id+" "+s.name);  
8.   
9.   in.close();  
10.  }  
11. }  
211 ravi
download this example of deserialization
Java Serialization with Inheritance (IS-A Relationship)
If a class implements serializable then all its sub classes will also be serializable. Let's see the example
given below:

1. import java.io.Serializable;  
2. class Person implements Serializable{  
3.  int id;  
4.  String name;  
5.  Person(int id, String name) {  
6.   this.id = id;  
7.   this.name = name;  
8.  }  
9. }  
1. class Student extends Person{  
2.  String course;  
3.  int fee;  
4.  public Student(int id, String name, String course, int fee) {  
5.   super(id,name);  
6.   this.course=course;  
7.   this.fee=fee;  
8.  }  
9. }  

Now you can serialize the Student class object that extends the Person class which is Serializable.Parent
class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.

Java Serialization with Aggregation (HAS-A Relationship)


If a class has a reference of another class, all the references must be Serializable otherwise serialization
process will not be performed. In such case, NotSerializableException is thrown at runtime.

1. class Address{  
2.  String addressLine,city,state;  
3.  public Address(String addressLine, String city, String state) {  
4.   this.addressLine=addressLine;  
5.   this.city=city;  
6.   this.state=state;  
7.  }  
8. }  
1. import java.io.Serializable;  
2. public class Student implements Serializable{  
3.  int id;  
4.  String name;  
5.  Address address;//HAS-A  
6.  public Student(int id, String name) {  
7.   this.id = id;  
8.   this.name = name;  
9.  }  
10. }  

Since Address is not Serializable, you can not serialize the instance of Student class.

Note: All the objects within an object must be Serializable.

Java Serialization with static data member


If there is any static data member in a class, it will not be serialized because static is the part of class not
object.

1. class Employee implements Serializable{  
2.  int id;  
3.  String name;  
4.  static String company="SSS IT Pvt Ltd";//it won't be serialized  
5.  public Student(int id, String name) {  
6.   this.id = id;  
7.   this.name = name;  
8.  }  
9. }  

Java Serialization with array or collection


Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is
not serialiizable, serialization will be failed.

Externalizable in java
The Externalizable interface provides the facility of writing the state of an object into a byte stream in
compress format. It is not a marker interface.

The Externalizable interface provides two methods:

 public void writeExternal(ObjectOutput out) throws IOException

 public void readExternal(ObjectInput in) throws IOException

Java Transient Keyword


If you don't want to serialize any data member of a class, you can mark it as transient.

Visit next page for more details.

Java Transient Keyword


Java transient keyword is used in serialization. If you define any data member as transient, it will not be
serialized.

Let's take an example, I have declared a class as Student, it has three data members id, name and age. If
you serialize the object, all the values will be serialized but I don't want to serialize one value, e.g. age then
we can declare the age data member as transient.

Example of Java Transient Keyword

In this example, we have created the two classes Student and PersistExample. The age data member of the
Student class is declared as transient, its value will not be serialized.

If you deserialize the object, you will get the default value for transient variable.

Let's create a class with transient variable.

1. import java.io.Serializable;  
2. public class Student implements Serializable{  
3.  int id;  
4.  String name;  
5.  transient int age;//Now it will not be serialized  
6.  public Student(int id, String name,int age) {  
7.   this.id = id;  
8.   this.name = name;  
9.   this.age=age;  
10.  }  
11. }  

Now write the code to serialize the object.

1. import java.io.*;  
2. class PersistExample{  
3.  public static void main(String args[])throws Exception{  
4.   Student s1 =new Student(211,"ravi",22);//creating object  
5.   //writing object into file  
6.   FileOutputStream f=new FileOutputStream("f.txt");  
7.   ObjectOutputStream out=new ObjectOutputStream(f);  
8.   out.writeObject(s1);  
9.   out.flush();  
10.   
11.   out.close();  
12.   f.close();  
13.   System.out.println("success");  
14.  }  
15. }  

Output:

success

Now write the code for deserialization.

1. import java.io.*;  
2. class DePersist{  
3.  public static void main(String args[])throws Exception{  
4.   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
5.   Student s=(Student)in.readObject();  
6.   System.out.println(s.id+" "+s.name+" "+s.age);  
7.   in.close();  
8.  }  
9. }  
211 ravi 0

As you can see, printing age of the student returns 0 because value of age was not serialized.

Java Networking
Java Networking is a concept of connecting two or more computing devices together so that we can share
resources.

Java socket programming provides facility to share data between different computing devices.
Advantage of Java Networking
1. sharing resources
2. centralize software management

Do You Know ?
 How to perform connection-oriented Socket Programming in networking ?
 How to display the data of any online web page ?
 How to get the IP address of any host name e.g. www.google.com ?
 How to perform connection-less socket programming in networking ?

Java Networking Terminology


The widely used java networking terminologies are given below:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets
that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For example:

 TCP
 FTP
 Telnet
 SMTP
 POP etc.

3) Port Number

The port number is used to uniquely identify different applications. It acts as a communication endpoint
between applications.

The port number is associated with the IP address for communication between two applications.
4) MAC Address

MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). A network
node can have multiple NIC but each with unique MAC.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The
example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast.
The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communication.

Visit next page for java socket programming.

What we will learn in Networking Tutorial


 Networking and Networking Terminology
 Socket Programming (Connection-oriented)
 URL class
 Displaying data of a webpage by URLConnection class
 InetAddress class
 DatagramSocket and DatagramPacket (Connection-less)

Java Socket Programming


Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket
and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to
create a socket.

Important methods
Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication
with the clients.

Important methods
Method Description

1) public Socket accept() returns the socket and establish a connection between server and client.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming


Let's see a simple of java socket programming in which client sends a text and server receives it.

File: MyServer.java

1. import java.io.*;  
2. import java.net.*;  
3. public class MyServer {  
4. public static void main(String[] args){  
5. try{  
6. ServerSocket ss=new ServerSocket(6666);  
7. Socket s=ss.accept();//establishes connection   
8. DataInputStream dis=new DataInputStream(s.getInputStream());  
9. String  str=(String)dis.readUTF();  
10. System.out.println("message= "+str);  
11. ss.close();  
12. }catch(Exception e){System.out.println(e);}  
13. }  
14. }  

File: MyClient.java

1. import java.io.*;  
2. import java.net.*;  
3. public class MyClient {  
4. public static void main(String[] args) {  
5. try{      
6. Socket s=new Socket("localhost",6666);  
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
8. dout.writeUTF("Hello Server");  
9. dout.flush();  
10. dout.close();  
11. s.close();  
12. }catch(Exception e){System.out.println(e);}  
13. }  
14. }  
download this example

To execute this program open two command prompts and execute each program at each command prompt as
displayed in the below figure.

After running the client application, a message will be displayed on the server console.
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the text. Then server will
write to the client and client will receive and print the text. The step goes on.

File: MyServer.java

1. import java.net.*;  
2. import java.io.*;  
3. class MyServer{  
4. public static void main(String args[])throws Exception{  
5. ServerSocket ss=new ServerSocket(3333);  
6. Socket s=ss.accept();  
7. DataInputStream din=new DataInputStream(s.getInputStream());  
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
10.   
11. String str="",str2="";  
12. while(!str.equals("stop")){  
13. str=din.readUTF();  
14. System.out.println("client says: "+str);  
15. str2=br.readLine();  
16. dout.writeUTF(str2);  
17. dout.flush();  
18. }  
19. din.close();  
20. s.close();  
21. ss.close();  
22. }}  

File: MyClient.java

1. import java.net.*;  
2. import java.io.*;  
3. class MyClient{  
4. public static void main(String args[])throws Exception{  
5. Socket s=new Socket("localhost",3333);  
6. DataInputStream din=new DataInputStream(s.getInputStream());  
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
9.   
10. String str="",str2="";  
11. while(!str.equals("stop")){  
12. str=br.readLine();  
13. dout.writeUTF(str);  
14. dout.flush();  
15. str2=din.readUTF();  
16. System.out.println("Server says: "+str2);  
17. }  
18.   
19. dout.close();  
20. s.close();  
21. }}  

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a
resource on the World Wide Web. For example:

1. http://www.javatpoint.com/java-tutorial  

A URL contains many information:

1. Protocol: In this case, http is the protocol.


2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
3. Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is
the port number. If port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.
Commonly used methods of Java URL class
The java.net.URL class provides many methods. The important methods of URL class are given below.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public URLConnection it returns the instance of URLConnection i.e. associated with this
openConnection() URL.

Example of Java URL class


1. //URLDemo.java  
2. import java.io.*;  
3. import java.net.*;  
4. public class URLDemo{  
5. public static void main(String[] args){  
6. try{  
7. URL url=new URL("http://www.javatpoint.com/java-tutorial");  
8.   
9. System.out.println("Protocol: "+url.getProtocol());  
10. System.out.println("Host Name: "+url.getHost());  
11. System.out.println("Port Number: "+url.getPort());  
12. System.out.println("File Name: "+url.getFile());  
13.   
14. }catch(Exception e){System.out.println(e);}  
15. }  
16. }  
Test it Now

Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
download this example
Java URLConnection class
The Java URLConnection class represents a communication link between the URL and the application. This
class can be used to read and write data to the specified resource referred by the URL.

How to get the object of URLConnection class

The openConnection() method of URL class returns the object of URLConnection class. Syntax:

1. public URLConnection openConnection()throws IOException{}  

Displaying source code of a webpage by URLConnecton class


The URLConnection class provides many methods, we can display all the data of a webpage by using the
getInputStream() method. The getInputStream() method returns all the data of the specified URL in the
stream that can be read and displayed.

Example of Java URLConnecton class


1. import java.io.*;  
2. import java.net.*;  
3. public class URLConnectionExample {  
4. public static void main(String[] args){  
5. try{  
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");  
7. URLConnection urlcon=url.openConnection();  
8. InputStream stream=urlcon.getInputStream();  
9. int i;  
10. while((i=stream.read())!=-1){  
11. System.out.print((char)i);  
12. }  
13. }catch(Exception e){System.out.println(e);}  
14. }  
15. }  

Java HttpURLConnection class


The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.

By the help of HttpURLConnection class, you can information of any HTTP URL such as header information,
status code, response code etc.

The java.net.HttpURLConnection is subclass of URLConnection class.


How to get the object of HttpURLConnection class

The openConnection() method of URL class returns the object of URLConnection class. Syntax:

1. public URLConnection openConnection()throws IOException{}  

You can typecast it to HttpURLConnection type as given below.

1. URL url=new URL("http://www.javatpoint.com/java-tutorial");    
2. HttpURLConnection huc=(HttpURLConnection)url.openConnection();  

Java HttpURLConnecton Example


1. import java.io.*;    
2. import java.net.*;    
3. public class HttpURLConnectionDemo{    
4. public static void main(String[] args){    
5. try{    
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");    
7. HttpURLConnection huc=(HttpURLConnection)url.openConnection();  
8. for(int i=1;i<=8;i++){  
9. System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));  
10. }  
11. huc.disconnect();   
12. }catch(Exception e){System.out.println(e);}    
13. }    
14. }    
Test it Now

Output:

Date = Wed, 10 Dec 2014 19:31:14 GMT


Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked

Java InetAddress class


Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get
the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com etc.
Commonly used methods of InetAddress class
Method Description

public static InetAddress getByName(String host) throws it returns the instance of InetAddress containing
UnknownHostException LocalHost IP and name.

public static InetAddress getLocalHost() throws it returns the instance of InetAdddress containing
UnknownHostException local host name and address.

public String getHostName() it returns the host name of the IP address.

public String getHostAddress() it returns the IP address in string format.

Example of Java InetAddress class


Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com website.

1. import java.io.*;  
2. import java.net.*;  
3. public class InetDemo{  
4. public static void main(String[] args){  
5. try{  
6. InetAddress ip=InetAddress.getByName("www.javatpoint.com");  
7.   
8. System.out.println("Host Name: "+ip.getHostName());  
9. System.out.println("IP Address: "+ip.getHostAddress());  
10. }catch(Exception e){System.out.println(e);}  
11. }  
12. }  
Test it Now

Output:

Host Name: www.javatpoint.com


IP Address: 206.51.231.148

Java DatagramSocket and DatagramPacket


Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram
packets.

A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.

Commonly used Constructors of DatagramSocket class


 DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
 DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with
the given Port Number.
 DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram
socket and binds it with the specified port number and host address.

Java DatagramPacket class


Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive
in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class


 DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to
receive the packets.
 DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram
packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by DatagramSocket


1. //DSender.java  
2. import java.net.*;  
3. public class DSender{  
4.   public static void main(String[] args) throws Exception {  
5.     DatagramSocket ds = new DatagramSocket();  
6.     String str = "Welcome java";  
7.     InetAddress ip = InetAddress.getByName("127.0.0.1");  
8.      
9.     DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);  
10.     ds.send(dp);  
11.     ds.close();  
12.   }  
13. }  
Example of Receiving DatagramPacket by DatagramSocket
1. //DReceiver.java  
2. import java.net.*;  
3. public class DReceiver{  
4.   public static void main(String[] args) throws Exception {  
5.     DatagramSocket ds = new DatagramSocket(3000);  
6.     byte[] buf = new byte[1024];  
7.     DatagramPacket dp = new DatagramPacket(buf, 1024);  
8.     ds.receive(dp);  
9.     String str = new String(dp.getData(), 0, dp.getLength());  
10.     System.out.println(str);  
11.     ds.close();  
12.   }  
13. }  

1. import java.awt.*;  
2. import java.awt.event.*;  
3.   
4. class AEvent extends Frame implements ActionListener{  
5. TextField tf;  
6. AEvent(){  
7.   
8. tf=new TextField();  
9. tf.setBounds(60,50,170,20);  
10.   
11. Button b=new Button("click me");  
12. b.setBounds(100,120,80,30);  
13.   
14. b.addActionListener(this);  
15.   
16. add(b);add(tf);  
17.   
18. setSize(300,300);  
19. setLayout(null);  
20. setVisible(true);  
21.   
22. }  
23.   
24. public void actionPerformed(ActionEvent e){  
25. tf.setText("Welcome");  
26. }  
27.   
28. public static void main(String args[]){  
29. new AEvent();  
30. }  
31. }  
 Example of event handling by Outer class:
1. import java.awt.*;  
2. import java.awt.event.*;  
3. class AEvent2 extends Frame{  
4. TextField tf;  
5. AEvent2(){  
6.   
7. tf=new TextField();  
8. tf.setBounds(60,50,170,20);  
9.   
10. Button b=new Button("click me");  
11. b.setBounds(100,120,80,30);  
12.   
13. Outer o=new Outer(this);  
14. b.addActionListener(o);//passing outer class instance  
15.   
16. add(b);add(tf);  
17.   
18. setSize(300,300);  
19. setLayout(null);  
20. setVisible(true);  
21. }  
22. public static void main(String args[]){  
23. new AEvent2();  
24. }  
25. }  
1. import java.awt.event.*;  
2. class Outer implements ActionListener{  
3. AEvent2 obj;  
4. Outer(AEvent2 obj){  
5. this.obj=obj;  
6. }  
7. public void actionPerformed(ActionEvent e){  
8. obj.tf.setText("welcome");  
9. }  
10. }  

3) Example of event handling by Annonymous class:


1. import java.awt.*;  
2. import java.awt.event.*;  
3. class AEvent3 extends Frame{  
4. TextField tf;  
5. AEvent3(){  
6. tf=new TextField();  
7. tf.setBounds(60,50,170,20);  
8. Button b=new Button("click me");  
9. b.setBounds(50,120,80,30);  
10.   
11. b.addActionListener(new ActionListener(){  
12. public void actionPerformed(){  
13. tf.setText("hello");  
14. }  
15. });  
16. add(b);add(tf);  
17. setSize(300,300);  
18. setLayout(null);  
19. setVisible(true);  
20. }  
21. public static void main(String args[]){  
22. new AEvent3();  
23. }  
24. }  

 Example of event handling by Outer class:


1. import java.awt.*;  
2. import java.awt.event.*;  
3. class AEvent2 extends Frame{  
4. TextField tf;  
5. AEvent2(){  
6.   
7. tf=new TextField();  
8. tf.setBounds(60,50,170,20);  
9.   
10. Button b=new Button("click me");  
11. b.setBounds(100,120,80,30);  
12.   
13. Outer o=new Outer(this);  
14. b.addActionListener(o);//passing outer class instance  
15.   
16. add(b);add(tf);  
17.   
18. setSize(300,300);  
19. setLayout(null);  
20. setVisible(true);  
21. }  
22. public static void main(String args[]){  
23. new AEvent2();  
24. }  
25. }  
1. import java.awt.event.*;  
2. class Outer implements ActionListener{  
3. AEvent2 obj;  
4. Outer(AEvent2 obj){  
5. this.obj=obj;  
6. }  
7. public void actionPerformed(ActionEvent e){  
8. obj.tf.setText("welcome");  
9. }  
10. }  
3) Example of event handling by Annonymous class:
1. import java.awt.*;  
2. import java.awt.event.*;  
3. class AEvent3 extends Frame{  
4. TextField tf;  
5. AEvent3(){  
6. tf=new TextField();  
7. tf.setBounds(60,50,170,20);  
8. Button b=new Button("click me");  
9. b.setBounds(50,120,80,30);  
10.   
11. b.addActionListener(new ActionListener(){  
12. public void actionPerformed(){  
13. tf.setText("hello");  
14. }  
15. });  
16. add(b);add(tf);  
17. setSize(300,300);  
18. setLayout(null);  
19. setVisible(true);  
20. }  
21. public static void main(String args[]){  
22. new AEvent3();  
23. }  
24. }  

JButton class:
The JButton class is used to create a button that have plateform-independent implementation.

Commonly used Constructors:


 JButton(): creates a button with no text and icon.
 JButton(String s): creates a button with the specified text.
 JButton(Icon i): creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


1) public void setText(String s): is used to set specified text on button.
2) public String getText(): is used to return the text of the button.
3) public void setEnabled(boolean b): is used to enable or disable the button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
5) public Icon getIcon(): is used to get the Icon of the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this object.
Note: The JButton class extends AbstractButton class.

Example of displaying image on the button:


1. import java.awt.event.*;  
2. import javax.swing.*;  
3.   
4. public class ImageButton{  
5. ImageButton(){  
6. JFrame f=new JFrame();  
7.                   
8.           
9. JButton b=new JButton(new ImageIcon("b.jpg"));  
10. b.setBounds(130,100,100, 40);  
11.       
12. f.add(b);  
13.           
14. f.setSize(300,400);  
15. f.setLayout(null);  
16. f.setVisible(true);  
17.           
18. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
19.           
20.     }  
21.       
22. public static void main(String[] args) {  
23.     new ImageButton();  
24. }  
25. }  
download this example

How to make an executable jar file in Java


The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An executable jar
file calls the main method of the class if you double click it.

To create the executable jar file, you need to create .mf file, also known as manifest file.

Download this example

Creating manifest file

To create manifest file, you need to write Main-Class, then colon, then space, then classname then enter. For
example:
myfile.mf
1. Main-Class: First  

As you can see, the mf file starts with Main-Class colon space class name. Here, class name is First.

In mf file, new line is must after the class name.

Creating executable jar file using jar tool

The jar tool provides many switches, some of them are as follows:

1. -c creates new archive file


2. -v generates verbose output. It displays the included or extracted resource on the standard output.
3. -m includes manifest information from the given mf file.
4. -f specifies the archive file name
5. -x extracts files from the archive file

Now, let's write the code to generated the executable jar using mf file.

You need to write jar then swiches then mf_file then jar_file then .classfile as given below:

1. jar -cvmf myfile.mf myjar.jar First.class  

It is shown in the image given below:

Now it will create the executable jar file. If you double pass4real it click on it, it will call the main method of
the First class.
We are assuming that you have created any window based application using AWT or SWING. If you don't, you
can use the code given below:

First.java
1. import javax.swing.*;    
2. public class First{    
3. First(){    
4. JFrame f=new JFrame();    
5.                     
6. JButton b=new JButton("click");    
7. b.setBounds(130,100,100, 40);    
8.         
9. f.add(b);    
10.             
11. f.setSize(300,400);    
12. f.setLayout(null);    
13. f.setVisible(true);    
14.             
15. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
16. }    
17. public static void main(String[] args) {    
18.     new First();    
19. }    
20. }    

JRadioButton class
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options.
It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

Commonly used Constructors of JRadioButton class:


 JRadioButton(): creates an unselected radio button with no text.
 JRadioButton(String s): creates an unselected radio button with specified text.
 JRadioButton(String s, boolean selected): creates a radio button with the specified text and
selected status.

Commonly used Methods of AbstractButton class:


1) public void setText(String s): is used to set specified text on button.
2) public String getText(): is used to return the text of the button.
3) public void setEnabled(boolean b): is used to enable or disable the button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
5) public Icon getIcon(): is used to get the Icon of the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this object.

Note: The JRadioButton class extends the JToggleButton class that extends AbstractButton class.

Example of JRadioButton class:


1. import javax.swing.*;  
2. public class Radio {  
3. JFrame f;  
4.   
5. Radio(){  
6. f=new JFrame();  
7.   
8. JRadioButton r1=new JRadioButton("A) Male");  
9. JRadioButton r2=new JRadioButton("B) FeMale");  
10. r1.setBounds(50,100,70,30);  
11. r2.setBounds(50,150,70,30);  
12.   
13. ButtonGroup bg=new ButtonGroup();  
14. bg.add(r1);bg.add(r2);  
15.   
16. f.add(r1);f.add(r2);  
17.   
18. f.setSize(300,300);  
19. f.setLayout(null);  
20. f.setVisible(true);  
21. }  
22. public static void main(String[] args) {  
23.     new Radio();  
24. }  
25. }  
download this example

ButtonGroup class:
The ButtonGroup class can be used to group multiple buttons so that at a time only one button can be
selected.

JRadioButton example with event handling


1. import javax.swing.*;  
2. import java.awt.event.*;  
3. class RadioExample extends JFrame implements ActionListener{  
4. JRadioButton rb1,rb2;  
5. JButton b;  
6. RadioExample(){  
7.   
8. rb1=new JRadioButton("Male");  
9. rb1.setBounds(100,50,100,30);  
10.   
11. rb2=new JRadioButton("Female");  
12. rb2.setBounds(100,100,100,30);  
13.   
14. ButtonGroup bg=new ButtonGroup();  
15. bg.add(rb1);bg.add(rb2);  
16.   
17. b=new JButton("click");  
18. b.setBounds(100,150,80,30);  
19. b.addActionListener(this);  
20.   
21. add(rb1);add(rb2);add(b);  
22.   
23. setSize(300,300);  
24. setLayout(null);  
25. setVisible(true);  
26. }  
27. public void actionPerformed(ActionEvent e){  
28. if(rb1.isSelected()){  
29. JOptionPane.showMessageDialog(this,"You are male");  
30. }  
31. if(rb2.isSelected()){  
32. JOptionPane.showMessageDialog(this,"You are female");  
33. }  
34. }  
35. public static void main(String args[]){  
36. new RadioExample();  
37. }}  
 

JTextArea class (Swing Tutorial):


The JTextArea class is used to create a text area. It is a multiline area that displays the plain text only.

Commonly used Constructors:


 JTextArea(): creates a text area that displays no text initially.
 JTextArea(String s): creates a text area that displays specified text initially.
 JTextArea(int row, int column): creates a text area with the specified number of rows and columns
that displays no text initially..
 JTextArea(String s, int row, int column): creates a text area with the specified number of rows
and columns that displays specified text.

Commonly used methods of JTextArea class:


1) public void setRows(int rows): is used to set specified number of rows.
2) public void setColumns(int cols):: is used to set specified number of columns.
3) public void setFont(Font f): is used to set the specified font.
4) public void insert(String s, int position): is used to insert the specified text on the specified
position.
5) public void append(String s): is used to append the given text to the end of the document.

Example of JTextField class:


1. import java.awt.Color;  
2. import javax.swing.*;  
3.   
4. public class TArea {  
5.     JTextArea area;  
6.     JFrame f;  
7.     TArea(){  
8.     f=new JFrame();  
9.           
10.     area=new JTextArea(300,300);  
11.     area.setBounds(10,30,300,300);  
12.       
13.     area.setBackground(Color.black);  
14.     area.setForeground(Color.white);  
15.           
16.     f.add(area);  
17.       
18.     f.setSize(400,400);  
19.     f.setLayout(null);  
20.     f.setVisible(true);  
21. }  
22.     public static void main(String[] args) {  
23.         new TArea();  
24.     }  
25. }  

JComboBox class:
The JComboBox class is used to create the combobox (drop-down list). At a time only one item can be
selected from the item list.
Commonly used Constructors of JComboBox class:
JComboBox()
JComboBox(Object[] items)
JComboBox(Vector<?> items)

Commonly used methods of JComboBox class:


1) public void addItem(Object anObject): is used to add an item to the item list.
2) public void removeItem(Object anObject): is used to delete an item to the item list.
3) public void removeAllItems(): is used to remove all the items from the list.
4) public void setEditable(boolean b): is used to determine whether the JComboBox is editable.
5) public void addActionListener(ActionListener a): is used to add the ActionListener.
6) public void addItemListener(ItemListener i): is used to add the ItemListener.

Example of JComboBox class:


1. import javax.swing.*;  
2. public class Combo {  
3. JFrame f;  
4. Combo(){  
5.     f=new JFrame("Combo ex");  
6.       
7.     String country[]={"India","Aus","U.S.A","England","Newzeland"};  
8.       
9.     JComboBox cb=new JComboBox(country);  
10.     cb.setBounds(50, 50,90,20);  
11.     f.add(cb);  
12.       
13.     f.setLayout(null);  
14.     f.setSize(400,500);  
15.     f.setVisible(true);  
16.       
17. }  
18. public static void main(String[] args) {  
19.     new Combo();  
20.       
21. }  
22. }  

JTable class (Swing Tutorial):


The JTable class is used to display the data on two dimensional tables of cells.

Commonly used Constructors of JTable class:


 JTable(): creates a table with empty cells.
 JTable(Object[][] rows, Object[] columns): creates a table with the specified data.
Example of JTable class:
1. import javax.swing.*;  
2. public class MyTable {  
3.     JFrame f;  
4. MyTable(){  
5.     f=new JFrame();  
6.       
7.     String data[][]={ {"101","Amit","670000"},  
8.               {"102","Jai","780000"},  
9.                           {"101","Sachin","700000"}};  
10.     String column[]={"ID","NAME","SALARY"};  
11.       
12.     JTable jt=new JTable(data,column);  
13.     jt.setBounds(30,40,200,300);  
14.       
15.     JScrollPane sp=new JScrollPane(jt);  
16.     f.add(sp);  
17.       
18.     f.setSize(300,400);  
19. //  f.setLayout(null);  
20.     f.setVisible(true);  
21. }  
22. public static void main(String[] args) {  
23.     new MyTable();  
24. }  
25. }  

JColorChooser class:
The JColorChooser class is used to create a color chooser dialog box so that user can select any color.

Commonly used Constructors of JColorChooser class:


 JColorChooser(): is used to create a color chooser pane with white color initially.

 JColorChooser(Color initialColor): is used to create a color chooser pane with the specified color
initially.

Commonly used methods of JColorChooser class:


public static Color showDialog(Component c, String title, Color initialColor): is used to show the
color-chooser dialog box.
Example of JColorChooser class:

1. import java.awt.event.*;  
2. import java.awt.*;  
3. import javax.swing.*;  
4.   
5. public class JColorChooserExample extends JFrame implements ActionListener{  
6. JButton b;  
7. Container c;  
8.   
9. JColorChooserExample(){  
10.     c=getContentPane();  
11.     c.setLayout(new FlowLayout());  
12.       
13.     b=new JButton("color");  
14.     b.addActionListener(this);  
15.       
16.     c.add(b);  
17. }  
18.   
19. public void actionPerformed(ActionEvent e) {  
20. Color initialcolor=Color.RED;  
21. Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);  
22. c.setBackground(color);  
23. }  
24.   
25. public static void main(String[] args) {  
26.     JColorChooserExample ch=new JColorChooserExample();  
27.     ch.setSize(400,400);  
28.     ch.setVisible(true);  
29.     ch.setDefaultCloseOperation(EXIT_ON_CLOSE);  
30. }  
31. }  

JProgressBar class:
The JProgressBar class is used to display the progress of the task.

Commonly used Constructors of JProgressBar class:


 JProgressBar(): is used to create a horizontal progress bar but no string text.
 JProgressBar(int min, int max): is used to create a horizontal progress bar with the specified
minimum and maximum value.
 JProgressBar(int orient): is used to create a progress bar with the specified orientation, it can be
either Vertical or Horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL
constants.
 JProgressBar(int orient, int min, int max): is used to create a progress bar with the specified
orientation, minimum and maximum value.

Commonly used methods of JProgressBar class:


1) public void setStringPainted(boolean b): is used to determine whether string should be displayed.
2) public void setString(String s): is used to set value to the progress string.
3) public void setOrientation(int orientation): is used to set the orientation, it may be either vertical
or horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants..
4) public void setValue(int value): is used to set the current value on the progress bar.

Example of JProgressBar class:


1. import javax.swing.*;  
2. public class MyProgress extends JFrame{  
3. JProgressBar jb;  
4. int i=0,num=0;  
5.   
6. MyProgress(){  
7. jb=new JProgressBar(0,2000);  
8. jb.setBounds(40,40,200,30);  
9.       
10. jb.setValue(0);  
11. jb.setStringPainted(true);  
12.       
13. add(jb);  
14. setSize(400,400);  
15. setLayout(null);  
16. }  
17.   
18. public void iterate(){  
19. while(i<=2000){  
20.   jb.setValue(i);  
21.   i=i+20;  
22.   try{Thread.sleep(150);}catch(Exception e){}  
23. }  
24. }  
25. public static void main(String[] args) {  
26.     MyProgress m=new MyProgress();  
27.     m.setVisible(true);  
28.     m.iterate();  
29. }  
30. }  

JSlider class:
The JSlider is used to create the slider. By using JSlider a user can select a value from a specific range.

Commonly used Constructors of JSlider class:


 JSlider(): creates a slider with the initial value of 50 and range of 0 to 100.
 JSlider(int orientation): creates a slider with the specified orientation set by either
JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial value 50.
 JSlider(int min, int max): creates a horizontal slider using the given min and max.
 JSlider(int min, int max, int value): creates a horizontal slider using the given min, max and value.
 JSlider(int orientation, int min, int max, int value): creates a slider using the given orientation,
min, max and value.

Commonly used Methods of JSlider class:


1) public void setMinorTickSpacing(int n): is used to set the minor tick spacing to the slider.
2) public void setMajorTickSpacing(int n): is used to set the major tick spacing to the slider.
3) public void setPaintTicks(boolean b): is used to determine whether tick marks are painted.
4) public void setPaintLabels(boolean b): is used to determine whether labels are painted.
5) public void setPaintTracks(boolean b): is used to determine whether track is painted.

Simple example of JSlider class:

1. import javax.swing.*;  
2.   
3. public class SliderExample1 extends JFrame{  
4.   
5. public SliderExample1() {  
6. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);  
7. JPanel panel=new JPanel();  
8. panel.add(slider);  
9.   
10. add(panel);  
11. }  
12.   
13. public static void main(String s[]) {  
14. SliderExample1 frame=new SliderExample1();  
15. frame.pack();  
16. frame.setVisible(true);  
17. }  
18. }  
download this example

Example of JSlider class that paints ticks:

1. import javax.swing.*;  
2.   
3. public class SliderExample extends JFrame{  
4.   
5. public SliderExample() {  
6.   
7. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);  
8. slider.setMinorTickSpacing(2);  
9. slider.setMajorTickSpacing(10);  
10.   
11. slider.setPaintTicks(true);  
12. slider.setPaintLabels(true);  
13.   
14. JPanel panel=new JPanel();  
15. panel.add(slider);  
16. add(panel);  
17. }  
18.   
19. public static void main(String s[]) {  
20. SliderExample frame=new SliderExample();  
21. frame.pack();  
22. frame.setVisible(true);  
23.   
24. }  
25. }  
Example of digital clock in swing:

1. import javax.swing.*;  
2. import java.awt.*;  
3. import java.text.*;  
4. import java.util.*;  
5. public class DigitalWatch implements Runnable{  
6. JFrame f;  
7. Thread t=null;  
8. int hours=0, minutes=0, seconds=0;  
9. String timeString = "";  
10. JButton b;  
11.   
12. DigitalWatch(){  
13.     f=new JFrame();  
14.       
15.     t = new Thread(this);  
16.         t.start();  
17.       
18.     b=new JButton();  
19.         b.setBounds(100,100,100,50);  
20.       
21.     f.add(b);  
22.     f.setSize(300,400);  
23.     f.setLayout(null);  
24.     f.setVisible(true);  
25. }  
26.   
27.  public void run() {  
28.       try {  
29.          while (true) {  
30.   
31.             Calendar cal = Calendar.getInstance();  
32.             hours = cal.get( Calendar.HOUR_OF_DAY );  
33.             if ( hours > 12 ) hours -= 12;  
34.             minutes = cal.get( Calendar.MINUTE );  
35.             seconds = cal.get( Calendar.SECOND );  
36.   
37.             SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");  
38.             Date date = cal.getTime();  
39.             timeString = formatter.format( date );  
40.   
41.             printTime();  
42.   
43.             t.sleep( 1000 );  // interval given in milliseconds  
44.          }  
45.       }  
46.       catch (Exception e) { }  
47.  }  
48.   
49. public void printTime(){  
50. b.setText(timeString);  
51. }  
52.   
53. public static void main(String[] args) {  
54.     new DigitalWatch();  
55.           
56.   
57. }  
58. }  

Displaying graphics in swing:


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.

11. public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.

Example of displaying graphics in swing:

1. import java.awt.*;  
2. import javax.swing.JFrame;  
3.   
4. public class DisplayGraphics extends Canvas{  
5.       
6.     public void paint(Graphics g) {  
7.         g.drawString("Hello",40,40);  
8.         setBackground(Color.WHITE);  
9.         g.fillRect(130, 30,100, 80);  
10.         g.drawOval(30,130,50, 60);  
11.         setForeground(Color.RED);  
12.         g.fillOval(130,130,50, 60);  
13.         g.drawArc(30, 200, 40,50,90,60);  
14.         g.fillArc(30, 130, 40,50,180,40);  
15.           
16.     }  
17.         public static void main(String[] args) {  
18.         DisplayGraphics m=new DisplayGraphics();  
19.         JFrame f=new JFrame();  
20.         f.add(m);  
21.         f.setSize(400,400);  
22.         //f.setLayout(null);  
23.         f.setVisible(true);  
24.     }  
25.   
26. }  

Displaying image in swing:


For displaying image, we can use the method drawImage() of Graphics class.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.

Example of displaying image in swing:

1. import java.awt.*;  
2. import javax.swing.JFrame;  
3.   
4. public class MyCanvas extends Canvas{  
5.       
6.     public void paint(Graphics g) {  
7.   
8.         Toolkit t=Toolkit.getDefaultToolkit();  
9.         Image i=t.getImage("p3.gif");  
10.         g.drawImage(i, 120,100,this);  
11.           
12.     }  
13.         public static void main(String[] args) {  
14.         MyCanvas m=new MyCanvas();  
15.         JFrame f=new JFrame();  
16.         f.add(m);  
17.         f.setSize(400,400);  
18.         f.setVisible(true);  
19.     }  
20.   
21. }  

Example of creating Edit menu for Notepad:


1. import javax.swing.*;  
2. import java.awt.event.*;  
3.   
4. public class Notepad implements ActionListener{  
5. JFrame f;  
6. JMenuBar mb;  
7. JMenu file,edit,help;  
8. JMenuItem cut,copy,paste,selectAll;  
9. JTextArea ta;  
10.       
11. Notepad(){  
12. f=new JFrame();  
13.   
14. cut=new JMenuItem("cut");  
15. copy=new JMenuItem("copy");  
16. paste=new JMenuItem("paste");  
17. selectAll=new JMenuItem("selectAll");  
18.   
19. cut.addActionListener(this);  
20. copy.addActionListener(this);  
21. paste.addActionListener(this);  
22. selectAll.addActionListener(this);  
23.   
24. mb=new JMenuBar();  
25. mb.setBounds(5,5,400,40);  
26.   
27. file=new JMenu("File");  
28. edit=new JMenu("Edit");  
29. help=new JMenu("Help");  
30.   
31. edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);  
32.   
33.   
34. mb.add(file);mb.add(edit);mb.add(help);  
35.   
36. ta=new JTextArea();  
37. ta.setBounds(5,30,460,460);  
38.   
39. f.add(mb);f.add(ta);  
40.   
41. f.setLayout(null);  
42. f.setSize(500,500);  
43. f.setVisible(true);  
44. }  
45.   
46. public void actionPerformed(ActionEvent e) {  
47. if(e.getSource()==cut)  
48. ta.cut();  
49. if(e.getSource()==paste)  
50. ta.paste();  
51. if(e.getSource()==copy)  
52. ta.copy();  
53. if(e.getSource()==selectAll)  
54. ta.selectAll();  
55. }  
56.   
57. public static void main(String[] args) {  
58.     new Notepad();  
59. }  
60. }  

RMI

next →← prev

RMI (Remote Method Invocation)


1. Remote Method Invocation (RMI)
2. Understanding stub and skeleton
1. stub
2. skeleton
3. Requirements for the distributed applications
4. Steps to write the RMI program
5. RMI Example

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed


application in java. The RMI allows an object to invoke methods on an object running in another JVM.

The RMI provides remote communication between the applications using two objects stub and skeleton.

Understanding stub and skeleton

RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM. Let's understand the stub
and skeleton objects:
stub

The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it.
It resides at the client side and represents the remote object. When the caller invokes method on the stub
object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton

The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are
routed through it. When the skeleton receives the incoming request, it does the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
Understanding requirements for the distributed applications
If any application performs these tasks, it can be distributed application.

.
1. The application need to locate the remote method
2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.

The RMI application have all these features, so it is called the distributed application.

Steps to write the RMI program


The is given the 6 steps to write the RMI program.

1. Create the remote interface


2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

RMI Example

In this example, we have followed all the 6 steps to create and run the rmi application. The client
application need only two files, remote interface and client application. In the rmi application, both client
and server interacts with the remote interface. The client application invokes methods on the proxy object,
RMI sends the request to the remote JVM. The return value is sent back to the proxy object and then to
the client application.
1) create the remote interface

For creating the remote interface, extend the Remote interface and declare the RemoteException with all
the methods of the remote interface. Here, we are creating a remote interface that extends the Remote
interface. There is only one method named add() and it declares RemoteException.

1. import java.rmi.*;  
2. public interface Adder extends Remote{  
3. public int add(int x,int y)throws RemoteException;  
4. }  

2) Provide the implementation of the remote interface

Now provide the implementation of the remote interface. For providing the implementation of the Remote
interface, we need to

 Either extend the UnicastRemoteObject class,


 or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
1. import java.rmi.*;  
2. import java.rmi.server.*;  
3. public class AdderRemote extends UnicastRemoteObject implements Adder{  
4. AdderRemote()throws RemoteException{  
5. super();  
6. }  
7. public int add(int x,int y){return x+y;}  
8. }  

3) create the stub and skeleton objects using the rmic tool.

Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the RMI
compiler and creates stub and skeleton objects.

1. rmic AdderRemote  

4) Start the registry service by the rmiregistry tool

Now start the registry service by using the rmiregistry tool. If you don't specify the port number, it uses a
default port number. In this example, we are using the port number 5000.

1. rmiregistry 5000  

5) Create and run the server application

Now rmi services need to be hosted in a server process. The Naming class provides methods to get and
store the remote object. The Naming class provides 5 methods.

1. public static java.rmi.Remote lookup(java.lang.String) throws


java.rmi.NotBoundException, java.net.MalformedURLException,
java.rmi.RemoteException; it returns the reference of the remote object.
2. public static void bind(java.lang.String, java.rmi.Remote) throws
java.rmi.AlreadyBoundException, java.net.MalformedURLException,
java.rmi.RemoteException; it binds the remote object with the given name.
3. public static void unbind(java.lang.String) throws java.rmi.RemoteException,
java.rmi.NotBoundException, java.net.MalformedURLException; it destroys the remote
object which is bound with the given name.
4. public static void rebind(java.lang.String, java.rmi.Remote) throws
java.rmi.RemoteException, java.net.MalformedURLException; it binds the remote object to
the new name.
5. public static java.lang.String[] list(java.lang.String) throws java.rmi.RemoteException,
java.net.MalformedURLException; it returns an array of the names of the remote objects bound
in the registry.
In this example, we are binding the remote object by the name sonoo.

1. import java.rmi.*;  
2. import java.rmi.registry.*;  
3. public class MyServer{  
4. public static void main(String args[]){  
5. try{  
6. Adder stub=new AdderRemote();  
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);  
8. }catch(Exception e){System.out.println(e);}  
9. }  
10. }  

6) Create and run the client application

At the client we are getting the stub object by the lookup() method of the Naming class and invoking the
method on this object. In this example, we are running the server and client applications, in the same
machine so we are using localhost. If you want to access the remote object from another machine, change
the localhost to the host name (or IP address) where the remote object is located.

1. import java.rmi.*;  
2. public class MyClient{  
3. public static void main(String args[]){  
4. try{  
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");  
6. System.out.println(stub.add(34,4));  
7. }catch(Exception e){}  
8. }  
9. }  

download this example of rmi

1. For running this rmi example,  
2.   
3. 1) compile all the java files  
4.   
5. javac *.java  
6.   
7. 2)create stub and skeleton object by rmic tool  
8.   
9. rmic AdderRemote  
10.   
11. 3)start rmi registry in one command prompt  
12.   
13. rmiregistry 5000  
14.   
15. 4)start the server in another command prompt  
16.   
17. java MyServer  
18.   
19. 5)start the client application in another command prompt  
20.   
21. java MyClient  
Output of this RMI example
 
Meaningful example of RMI application with database

Consider a scenario, there are two applications running in different machines. Let's say MachineA and
MachineB, machineA is located in United States and MachineB in India. MachineB want to get list of all the
customers of MachineA application.

Let's develop the RMI application by following the steps.

1) Create the table

First of all, we need to create the table in the database. Here, we are using Oracle10 database.
2) Create Customer class and Remote interface
File: Customer.java
1. package com.javatpoint;  
2. public class Customer implements java.io.Serializable{  
3.     private int acc_no;  
4.     private String firstname,lastname,email;  
5.     private float amount;  
6. //getters and setters  
7. }  

Note: Customer class must be Serializable.

File: Bank.java
1. package com.javatpoint;  
2. import java.rmi.*;  
3. import java.util.*;  
4. interface Bank extends Remote{  
5. public List<Customer> getCustomers()throws RemoteException;  
6. }  

3) Create the class that provides the implementation of Remote interface


File: BankImpl.java
1. package com.javatpoint;  
2. import java.rmi.*;  
3. import java.rmi.server.*;  
4. import java.sql.*;  
5. import java.util.*;  
6. class BankImpl extends UnicastRemoteObject implements Bank{  
7. BankImpl()throws RemoteException{}  
8.   
9. public List<Customer> getCustomers(){  
10. List<Customer> list=new ArrayList<Customer>();  
11. try{  
12. Class.forName("oracle.jdbc.driver.OracleDriver");  
13. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle
");  
14. PreparedStatement ps=con.prepareStatement("select * from customer400");  
15. ResultSet rs=ps.executeQuery();  
16.   
17. while(rs.next()){  
18. Customer c=new Customer();  
19. c.setAcc_no(rs.getInt(1));  
20. c.setFirstname(rs.getString(2));  
21. c.setLastname(rs.getString(3));  
22. c.setEmail(rs.getString(4));  
23. c.setAmount(rs.getFloat(5));  
24. list.add(c);  
25. }  
26.   
27. con.close();  
28. }catch(Exception e){System.out.println(e);}  
29. return list;  
30. }//end of getCustomers()  
31. }  

4) Compile the class rmic tool and start the registry service by rmiregistry tool

5) Create and run the Server


File: MyServer.java
1. package com.javatpoint;  
2. import java.rmi.*;  
3. public class MyServer{  
4. public static void main(String args[])throws Exception{  
5. Remote r=new BankImpl();  
6. Naming.rebind("rmi://localhost:6666/javatpoint",r);  
7. }}  

6) Create and run the Client


File: MyClient.java
1. package com.javatpoint;  
2. import java.util.*;  
3. import java.rmi.*;  
4. public class MyClient{  
5. public static void main(String args[])throws Exception{  
6. Bank b=(Bank)Naming.lookup("rmi://localhost:6666/javatpoint");  
7.   
8. List<Customer> list=b.getCustomers();  
9. for(Customer c:list){  
10. System.out.println(c.getAcc_no()+" "+c.getFirstname()+" "+c.getLastname()  
11. +" "+c.getEmail()+" "+c.getAmount());  
12. }  
13.   
14. }}  
Java I/O Tutorial
Java I/O (Input and Output) is used to process the input and produce the output based on the input.

Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.

We can perform file handling in java by java IO API.

Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it's like a
stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are attached with console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and error message to the console.

1. System.out.println("simple message");  
2. System.err.println("error message");  
Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character  
2. System.out.println((char)i);//will print the character  
Do You Know ?
 How to write a common data to multiple files using single stream only ?
 How can we access multiple files by single stream ?
 How can we improve the performance of Input and Output operation ?
 How many ways can we read data from the keyboard?
 What is console class ?

 How to compress and uncompress the data of a file?

OutputStream

Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral
device or socket.

InputStream

Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device
or socket.

Let's understand working of Java OutputStream and InputStream by the figure given below.

OutputStream class

OutputStream class is an abstract class.It is the superclass of all classes representing an output stream of
bytes. An output stream accepts output bytes and sends them to some sink.
Commonly used methods of OutputStream class
Method Description

1) public void write(int)throws IOException: is used to write a byte to the current output stream.

2) public void write(byte[])throws is used to write an array of byte to the current output
IOException: stream.

3) public void flush()throws IOException: flushes the current output stream.

4) public void close()throws IOException: is used to close the current output stream.

InputStream class

InputStream class is an abstract class.It is the superclass of all classes representing an input stream of bytes.

Commonly used methods of InputStream class


Method Description

1) public abstract int read()throws reads the next byte of data from the input stream.It returns -1 at
IOException: the end of file.

2) public int available()throws returns an estimate of the number of bytes that can be read from
IOException: the current input stream.

3) public void close()throws is used to close the current input stream.


IOException:
Fil
eInputStream and FileOutputStream (File Handling)
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In another
words, they are used for file handling in java.

Java FileOutputStream class


Java FileOutputStream is an output stream for writing data to a file.

If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer
FileWriter.But you can write byte-oriented as well as character-oriented data.

Example of Java FileOutputStream class


1. import java.io.*;  
2. class Test{  
3.   public static void main(String args[]){  
4.    try{  
5.      FileOutputstream fout=new FileOutputStream("abc.txt");  
6.      String s="Sachin Tendulkar is my favourite player";  
7.      byte b[]=s.getBytes();//converting string into byte array  
8.      fout.write(b);  
9.      fout.close();  
10.      System.out.println("success...");  
11.     }catch(Exception e){system.out.println(e);}  
12.   }  
13. }  
Output:success...

Java FileInputStream class


Java FileInputStream class obtains input bytes from a file.It is used for reading streams of raw bytes such as
image data. For reading streams of characters, consider using FileReader.

It should be used to read byte-oriented data for example to read image, audio, video etc.

Example of FileInputStream class


1. import java.io.*;  
2. class SimpleRead{  
3.  public static void main(String args[]){  
4.   try{  
5.     FileInputStream fin=new FileInputStream("abc.txt");  
6.     int i=0;  
7.     while((i=fin.read())!=-1){  
8.      System.out.println((char)i);  
9.     }  
10.     fin.close();  
11.   }catch(Exception e){system.out.println(e);}  
12.  }  
13. }  
Output:Sachin is my favourite player.
Example of Reading the data of current java file and writing it into another
file

We can read the data of any file using the FileInputStream class whether it is java file, image file, video file
etc. In this example, we are reading the data of C.java file and writing it into another file M.java.

1. import java.io.*;  
2. class C{  
3. public static void main(String args[])throws Exception{  
4. FileInputStream fin=new FileInputStream("C.java");  
5. FileOutputStream fout=new FileOutputStream("M.java");  
6. int i=0;  
7. while((i=fin.read())!=-1){  
8. fout.write((byte)i);  
9. }  
10. fin.close();  
11. }  
12. }  

Java ByteArrayOutputStream class


Java ByteArrayOutputStream class is used to write data into multiple files. In this stream, the data is written
into a byte array that can be written to multiple stream.

The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.

The buffer of ByteArrayOutputStream automatically grows according to data.


Closing the ByteArrayOutputStream has no effect.

Constructors of ByteArrayOutputStream class


Constructor Description

ByteArrayOutputStream() creates a new byte array output stream with the initial capacity of 32 bytes,
though its size increases if necessary.

ByteArrayOutputStream(int creates a new byte array output stream, with a buffer capacity of the specified
size) size, in bytes.

Methods of ByteArrayOutputStream class


Method Description

1) public synchronized void writes the complete contents of this byte array output
writeTo(OutputStream out) throws IOException stream to the specified output stream.

2) public void write(byte b) throws IOException writes byte into this stream.

3) public void write(byte[] b) throws IOException writes byte array into this stream.

4) public void flush() flushes this stream.

5) public void close() has no affect, it doesn't closes the bytearrayoutputstream.

Java ByteArrayOutputStream Example

Let's see a simple example of java ByteArrayOutputStream class to write data into 2 files.

1. import java.io.*;  
2. class S{  
3.  public static void main(String args[])throws Exception{  
4.   FileOutputStream fout1=new FileOutputStream("f1.txt");  
5.   FileOutputStream fout2=new FileOutputStream("f2.txt");  
6.   
7.   ByteArrayOutputStream bout=new ByteArrayOutputStream();  
8.   bout.write(139);  
9.   bout.writeTo(fout1);  
10.   bout.writeTo(fout2);  
11.   
12.   bout.flush();  
13.   bout.close();//has no effect  
14.   System.out.println("success...");  
15.  }  
16. }   
success...

Ja
va SequenceInputStream class
Java SequenceInputStream class is used to read data from multiple streams. It reads data of streams one by
one.

Constructors of SequenceInputStream class:


Constructor Description

1) SequenceInputStream(InputStream s1, creates a new input stream by reading the data of two
InputStream s2) input stream in order, first s1 and then s2.

2) SequenceInputStream(Enumeration e) creates a new input stream by reading the data of an


enumeration whose type is InputStream.

Simple example of SequenceInputStream class

In this example, we are printing the data of two files f1.txt and f2.txt.

1. import java.io.*;  
2. class Simple{  
3.   public static void main(String args[])throws Exception{  
4.    FileinputStream fin1=new FileinputStream("f1.txt");  
5.    FileinputStream fin2=new FileinputStream("f2.txt");  
6.   
7.    SequenceinputStream sis=new SequenceinputStream(fin1,fin2);  
8.    int i;  
9.    while((i=sis.read())!=-1){  
10.     System.out.println((char)i);  
11.    }  
12.    sis.close();  
13.    fin1.close();  
14.    fin2.close();  
15.   }  
16. }  

Example of SequenceInputStream that reads the data from two files

In this example, we are writing the data of two files f1.txt and f2.txt into another file named f3.txt.

1. //reading data of 2 files and writing it into one file  
2.   
3. import java.io.*;  
4. class Simple{  
5.   public static void main(String args[])throws Exception{  
6.   
7.    FileinputStream fin1=new FileinputStream("f1.txt");  
8.    FileinputStream fin2=new FileinputStream("f2.txt");  
9.   
10.    FileOutputStream fout=new FileOutputStream("f3.txt");  
11.   
12.    SequenceinputStream sis=new SequenceinputStream(fin1,fin2);  
13.    int i;  
14.    while((i.sisread())!=-1)  
15.    {  
16.      fout.write(i);      
17.    }  
18.    sis.close();  
19.    fout.close();    
20.    fin.close();    
21.    fin.close();    
22.   
23.   }  
24. }  

Example of SequenceInputStream class that reads the data from multiple files using
enumeration
If we need to read the data from more than two files, we need to have these information in the
Enumeration object. Enumeration object can be get by calling elements method of the Vector class. Let's
see the simple example where we are reading the data from the 4 files.
1. import java.io.*;  
2. import java.util.*;  
3.   
4. class B{  
5. public static void main(String args[])throws IOException{  
6.   
7. //creating the FileInputStream objects for all the files  
8. FileInputStream fin=new FileInputStream("A.java");  
9. FileInputStream fin2=new FileInputStream("abc2.txt");  
10. FileInputStream fin3=new FileInputStream("abc.txt");  
11. FileInputStream fin4=new FileInputStream("B.java");  
12.   
13. //creating Vector object to all the stream  
14. Vector v=new Vector();  
15. v.add(fin);  
16. v.add(fin2);  
17. v.add(fin3);  
18. v.add(fin4);  
19.   
20. //creating enumeration object by calling the elements method  
21. Enumeration e=v.elements();  
22.   
23. //passing the enumeration object in the constructor  
24. SequenceInputStream bin=new SequenceInputStream(e);  
25. int i=0;  
26.   
27. while((i=bin.read())!=-1){  
28. System.out.print((char)i);  
29. }  
30.   
31. bin.close();  
32. fin.close();  
33. fin2.close();  
34. }  
35. }  
download this example of SequenceInputStream

Java BufferedOutputStream and BufferedInputStream

Java BufferedOutputStream class


Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency than to write
data directly into a stream. So, it makes the performance fast.
Example of BufferedOutputStream class:

In this example, we are writing the textual information in the BufferedOutputStream object which is
connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into
another. It is required if you have connected the one stream with another.

1. import java.io.*;  
2. class Test{  
3.  public static void main(String args[])throws Exception{  
4.    FileOutputStream fout=new FileOutputStream("f1.txt");  
5.    BufferedOutputStream bout=new BufferedOutputStream(fout);  
6.    String s="Sachin is my favourite player";  
7.    byte b[]=s.getBytes();  
8.    bout.write(b);  
9.   
10.    bout.flush();  
11.    bout.close();  
12.    fout.close();  
13.    System.out.println("success");  
14.  }  
15. }   

Output:

success...

Java BufferedInputStream class


Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism
to make the performance fast.

Example of Java BufferedInputStream

Let's see the simple example to read data of file using BufferedInputStream.

1. import java.io.*;  
2. class SimpleRead{  
3.  public static void main(String args[]){  
4.   try{  
5.     FileInputStream fin=new FileInputStream("f1.txt");  
6.     BufferedInputStream bin=new BufferedInputStream(fin);  
7.     int i;  
8.     while((i=bin.read())!=-1){  
9.      System.out.println((char)i);  
10.     }  
11.     bin.close();  
12.     fin.close();  
13.   }catch(Exception e){system.out.println(e);}  
14.  }  
15. }  

Output:

Sachin is my favourite player

Java FileWriter and FileReader (File Handling in java)


Java FileWriter and FileReader classes are used to write and read data from text files. These are character-
oriented classes, used for file handling in java.

Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to read and
write the textual information.

Java FileWriter class


Java FileWriter class is used to write character-oriented data to the file.

Constructors of FileWriter class


Constructor Description

FileWriter(String file) creates a new file. It gets file name in string.

FileWriter(File file) creates a new file. It gets file name in File object.

Methods of FileWriter class


Method Description

1) public void write(String text) writes the string into FileWriter.

2) public void write(char c) writes the char into FileWriter.

3) public void write(char[] c) writes char array into FileWriter.

4) public void flush() flushes the data of FileWriter.

5) public void close() closes FileWriter.


Java FileWriter Example
In this example, we are writing the data in the file abc.txt.

1. import java.io.*;  
2. class Simple{  
3.  public static void main(String args[]){  
4.   try{  
5.    FileWriter fw=new FileWriter("abc.txt");  
6.    fw.write("my name is sachin");  
7.    fw.close();  
8.   }catch(Exception e){System.out.println(e);}  
9.   System.out.println("success");  
10.  }  
11. }  

Output:

success...

Java FileReader class


Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream
class.

Constructors of FileWriter class


Constructor Description

FileReader(String It gets filename in string. It opens the given file in read mode. If file doesn't exist, it
file) throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn't exist,
it throws FileNotFoundException.

Methods of FileReader class


Method Description

1) public int read() returns a character in ASCII form. It returns -1 at the end of file.

2) public void close() closes FileReader.


Java FileReader Example
In this example, we are reading the data from the file abc.txt file.

1. import java.io.*;  
2. class Simple{  
3.  public static void main(String args[])throws Exception{  
4.   FileReader fr=new FileReader("abc.txt");  
5.   int i;  
6.   while((i=fr.read())!=-1)  
7.   System.out.println((char)i);  
8.   
9.   fr.close();  
10.  }  
11. }  

Output:

my name is sachin

CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements the Appendable
interface. Its buffer automatically grows when data is written in this stream. Calling the close() method on
this object has no effect.

Example of CharArrayWriter class:

In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.

1. import java.io.*;  
2. class Simple{  
3.  public static void main(String args[])throws Exception{  
4.   
5.   CharArrayWriter out=new CharArrayWriter();  
6.   out.write("my name is");  
7.   
8.   FileWriter f1=new FileWriter("a.txt");  
9.   FileWriter f2=new FileWriter("b.txt");  
10.   FileWriter f3=new FileWriter("c.txt");  
11.   FileWriter f4=new FileWriter("d.txt");  
12.   
13.   out.writeTo(f1);  
14.   out.writeTo(f2);  
15.   out.writeTo(f3);  
16.   out.writeTo(f4);  
17.   
18.   
19.   f1.close();  
20.   f2.close();  
21.   f3.close();  
22.   f4.close();  
23.  }  
24. }  

Reading data from keyboard:


There are many ways to read data from the keyboard. For example:

 InputStreamReader
 Console
 Scanner
 DataInputStream etc.

InputStreamReader class:

InputStreamReader class can be used to read data from keyboard.It performs two tasks:

 connects to input stream of keyboard


 converts the byte-oriented stream into character-oriented stream

BufferedReader class:

BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by InputStreamReader and


BufferdReader class:

In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for
reading the line by line data from the keyboard.

1. //<b><i>Program of reading data</i></b>  
2.   
3. import java.io.*;  
4. class G5{  
5. public static void main(String args[])throws Exception{  
6.   
7. InputStreamReader r=new InputStreamReader(System.in);  
8. BufferedReader br=new BufferedReader(r);  
9.   
10. System.out.println("Enter your name");  
11. String name=br.readLine();  
12. System.out.println("Welcome "+name);  
13.  }  
14. }  
Output:Enter your name
Amit
Welcome Amit

Another Example of reading data from keyboard by InputStreamReader and


BufferdReader class until the user writes stop

In this example, we are reading and printing the data until the user prints stop.

1. import java.io.*;  
2. class G5{  
3. public static void main(String args[])throws Exception{  
4.   
5.  InputStreamReader r=new InputStreamReader(System.in);  
6.  BufferedReader br=new BufferedReader(r);  
7.   
8.  String name="";  
9.   
10.   while(name.equals("stop")){  
11.    System.out.println("Enter data: ");  
12.    name=br.readLine();  
13.    System.out.println("data is: "+name);  
14.   }  
15.   
16.  br.close();  
17.  r.close();  
18.  }  
19. }  
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop

Java Console class


The Java Console class is be used to get input from console. It provides methods to read text and password.

If you read password using Console class, it will not be displayed to the user.

The java.io.Console class is attached with system console internally. The Console class is introduced since
1.5.

Let's see a simple example to read text from console.

1. String text=System.console().readLine();  
2. System.out.println("Text is: "+text);  

Methods of Console class

Let's see the commonly used methods of Console class.

Method Description

1) public String readLine() is used to read a single line of text from the console.

2) public String readLine(String it provides a formatted prompt then reads the single line of text
fmt,Object... args) from the console.

3) public char[] readPassword() is used to read password that is not being displayed on the
console.

4) public char[] readPassword(String it provides a formatted prompt then reads the password that is
fmt,Object... args) not being displayed on the console.

How to get the object of Console

System class provides a static method console() that returns the unique instance of Console class.
1. public static Console console(){}  

Let's see the code to get the instance of Console class.

1. Console c=System.console();  

Java Console Example


1. import java.io.*;  
2. class ReadStringTest{  
3. public static void main(String args[]){  
4. Console c=System.console();  
5. System.out.println("Enter your name: ");  
6. String n=c.readLine();  
7. System.out.println("Welcome "+n);  
8. }  
9. }  

Output:

Enter your name: james gosling


Welcome james gosling

Java Console Example to read password


1. import java.io.*;  
2. class ReadPasswordTest{  
3. public static void main(String args[]){  
4. Console c=System.console();  
5. System.out.println("Enter password: ");  
6. char[] ch=c.readPassword();  
7. String pass=String.valueOf(ch);//converting char array into string  
8. System.out.println("Password is: "+pass);  
9. }  
10. }   

Output:

Enter password:
Password is: sonoo

Java Scanner class


There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It
provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular expression.

Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

Commonly used methods of Scanner class

There is a list of commonly used Scanner class methods:

Method Description

public String next() it returns the next token from the scanner.

public String nextLine() it moves the scanner position to the next line and returns the value as a string.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double nextDouble() it scans the next token as a double value.

Java Scanner Example to get input from console


Let's see the simple example of the Java Scanner class which reads the int, string and double value as an
input:

1. import java.util.Scanner;  
2. class ScannerTest{  
3.  public static void main(String args[]){  
4.    Scanner sc=new Scanner(System.in);  
5.      
6.    System.out.println("Enter your rollno");  
7.    int rollno=sc.nextInt();  
8.    System.out.println("Enter your name");  
9.    String name=sc.next();  
10.    System.out.println("Enter your fee");  
11.    double fee=sc.nextDouble();  
12.    System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);  
13.    sc.close();  
14.  }  
15. }   
download this scanner example

Output:

Enter your rollno


111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

Java Scanner Example with delimiter


Let's see the example of Scanner class with delimiter. The \s represents whitespace.

1. import java.util.*;  
2. public class ScannerTest2{  
3. public static void main(String args[]){  
4.      String input = "10 tea 20 coffee 30 tea buiscuits";  
5.      Scanner s = new Scanner(input).useDelimiter("\\s");  
6.      System.out.println(s.nextInt());  
7.      System.out.println(s.next());  
8.      System.out.println(s.nextInt());  
9.      System.out.println(s.next());  
10.      s.close();   
11. }}  

Output:

10
tea
20
coffee

java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream class automatically
flushes the data so there is no need to call flush() method. Moreover, its methods don't throw IOException.

Commonly used methods of PrintStream class:


There are many methods in PrintStream class. Let's see commonly used methods of PrintStream class:
 public void print(boolean b): it prints the specified boolean value.
 public void print(char c): it prints the specified char value.
 public void print(char[] c): it prints the specified character array values.
 public void print(int i): it prints the specified int value.
 public void print(long l): it prints the specified long value.
 public void print(float f): it prints the specified float value.
 public void print(double d): it prints the specified double value.
 public void print(String s): it prints the specified string value.
 public void print(Object obj): it prints the specified object value.
 public void println(boolean b): it prints the specified boolean value and terminates the line.
 public void println(char c): it prints the specified char value and terminates the line.
 public void println(char[] c): it prints the specified character array values and terminates the
line.
 public void println(int i): it prints the specified int value and terminates the line.
 public void println(long l): it prints the specified long value and terminates the line.
 public void println(float f): it prints the specified float value and terminates the line.
 public void println(double d): it prints the specified double value and terminates the line.
 public void println(String s): it prints the specified string value and terminates the line./li>
 public void println(Object obj): it prints the specified object value and terminates the line.
 public void println(): it terminates the line only.
 public void printf(Object format, Object... args): it writes the formatted string to the current
stream.
 public void printf(Locale l, Object format, Object... args): it writes the formatted string to the
current stream.
 public void format(Object format, Object... args): it writes the formatted string to the current
stream using specified format.

 public void format(Locale l, Object format, Object... args): it writes the formatted string to the
current stream using specified format.

Example of java.io.PrintStream class:


In this example, we are simply printing integer and string values.
1. import java.io.*;  
2. class PrintStreamTest{  
3.  public static void main(String args[])throws Exception{  
4.   
5.    FileOutputStream fout=new FileOutputStream("mfile.txt");  
6.    PrintStream pout=new PrintStream(fout);  
7.    pout.println(1900);  
8.    pout.println("Hello Java");  
9.    pout.println("Welcome to Java");  
10.    pout.close();  
11.    fout.close();  
12.       
13.  }  
14. }   
download this PrintStream example
Example of printf() method of java.io.PrintStream class:
Let's see the simple example of printing integer value by format specifier.
1. class PrintStreamTest{  
2.  public static void main(String args[]){  
3.    int a=10;  
4.    System.out.printf("%d",a);//Note, out is the object of PrintStream class  
5.       
6.  }  
7. }   
Output:10

Compressing and Uncompressing File


The DeflaterOutputStream and InflaterInputStream classes provide mechanism to compress and uncompress
the data in the deflate compression format.

DeflaterOutputStream class:

The DeflaterOutputStream class is used to compress the data in the deflate compression format. It provides
facility to the other compression filters, such as GZIPOutputStream.

Example of Compressing file using DeflaterOutputStream class

In this example, we are reading data of a file and compressing it into another file using DeflaterOutputStream
class. You can compress any file, here we are compressing the Deflater.java file

1. import java.io.*;  
2. import java.util.zip.*;  
3.   
4. class Compress{  
5. public static void main(String args[]){  
6.   
7. try{  
8. FileInputStream fin=new FileInputStream("Deflater.java");  
9.   
10. FileOutputStream fout=new FileOutputStream("def.txt");  
11. DeflaterOutputStream out=new DeflaterOutputStream(fout);  
12.   
13. int i;  
14. while((i=fin.read())!=-1){  
15. out.write((byte)i);  
16. out.flush();  
17. }  
18.   
19. fin.close();  
20. out.close();  
21.   
22. }catch(Exception e){System.out.println(e);}  
23. System.out.println("rest of the code");  
24. }  
25. }  
download this example

InflaterInputStream class:

The InflaterInputStream class is used to uncompress the file in the deflate compression format. It provides
facility to the other uncompression filters, such as GZIPInputStream class.

Example of uncompressing file using InflaterInputStream class

In this example, we are decompressing the compressed file def.txt into D.java .

1. import java.io.*;  
2. import java.util.zip.*;  
3.   
4. class UnCompress{  
5. public static void main(String args[]){  
6.   
7. try{  
8. FileInputStream fin=new FileInputStream("def.txt");  
9. InflaterInputStream in=new InflaterInputStream(fin);  
10.   
11. FileOutputStream fout=new FileOutputStream("D.java");  
12.   
13. int i;  
14. while((i=in.read())!=-1){  
15. fout.write((byte)i);  
16. fout.flush();  
17. }  
18.   
19. fin.close();  
20. fout.close();  
21. in.close();  
22.   
23. }catch(Exception e){System.out.println(e);}  
24. System.out.println("rest of the code");  
25. }  
26. }  
PipedInputStream and PipedOutputStream classes
The PipedInputStream and PipedOutputStream classes can be used to read and write data simultaneously.
Both streams are connected with each other using the connect() method of the PipedOutputStream class.

Example of PipedInputStream and PipedOutputStream classes using threads

Here, we have created two threads t1 and t2. The t1 thread writes the data using the PipedOutputStream
object and the t2 thread reads the data from that pipe using the PipedInputStream object. Both the piped
stream object are connected with each other.

1. import java.io.*;  
2. class PipedWR{  
3. public static void main(String args[])throws Exception{  
4. final PipedOutputStream pout=new PipedOutputStream();  
5. final PipedInputStream pin=new PipedInputStream();  
6.   
7. pout.connect(pin);//connecting the streams  
8. //creating one thread t1 which writes the data  
9. Thread t1=new Thread(){  
10. public void run(){  
11. for(int i=65;i<=90;i++){  
12. try{  
13. pout.write(i);  
14. Thread.sleep(1000);  
15. }catch(Exception e){}  
16. }  
17. }  
18. };  
19. //creating another thread t2 which reads the data  
20. Thread t2=new Thread(){  
21. public void run(){  
22. try{   
23. for(int i=65;i<=90;i++)  
24. System.out.println(pin.read());  
25. }catch(Exception e){}  
26. }  
27. };  
28. //starting both threads  
29. t1.start();  
30. t2.start();  
31. }}  

Internationalization and Localization in Java


1. Internationalization and Localization
2. Understanding the culturally dependent data
3. Locale class
4. Example of Local class that prints the informations of the default locale
5. Example of Local class that prints english in different languages
6. Example of Local class that print display language of many locales

Internationalization is also abbreviated as I18N because there are total 18 characters between the first
letter 'I' and the last letter 'N'.

Internationalization is a mechanism to create such an application that can be adapted to different languages
and regions.

Internationalization is one of the powerful concept of java if you are developing an application and want to
display messages, currencies, date, time etc. according to the specific region or language.

Localization is also abbreviated as I10N because there are total 10 characters between the first letter 'L' and
last letter 'N'. Localization is the mechanism to create such an application that can be adapted to a specific
language and region by adding locale-specific text and component.

Do You Know ?
 What is the use of Locale class ?
 How can we globalize the messages (or) What is the use of ResourceBundle class?
 How can we internationalize the date, time, number, currency and measurements?

Understanding the culturally dependent data before starting


internationalization
Before starting the internationalization, Let's first understand what are the informations that differ from one
region to another. There is the list of culturally dependent data:

 Messages
 Dates
 Times
 Numbers
 Currencies
 Measurements
 Phone Numbers
 Postal Addresses
 Labels on GUI components etc.
Importance of Locale class in Internationalization
An object of Locale class represents a geographical or cultural region. This object can be used to get the
locale specific information such as country name, language, variant etc.

Fields of Locale class


There are fields of Locale class:

1. public static final Locale ENGLISH


2. public static final Locale FRENCH
3. public static final Locale GERMAN
4. public static final Locale ITALIAN
5. public static final Locale JAPANESE
6. public static final Locale KOREAN
7. public static final Locale CHINESE
8. public static final Locale SIMPLIFIED_CHINESE
9. public static final Locale TRADITIONAL_CHINESE
10. public static final Locale FRANCE
11. public static final Locale GERMANY
12. public static final Locale ITALY
13. public static final Locale JAPAN
14. public static final Locale KOREA
15. public static final Locale CHINA
16. public static final Locale PRC
17. public static final Locale TAIWAN
18. public static final Locale UK
19. public static final Locale US
20. public static final Locale CANADA
21. public static final Locale CANADA_FRENCH
22. public static final Locale ROOT

Constructors of Locale class


There are three constructors of Locale class.They are as follows:

1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)

Commonly used methods of Locale class


There are given commonly used methods of Locale class.

1. public static Locale getDefault() it returns the instance of current Locale


2. public static Locale[] getAvailableLocales() it returns an array of available locales.
3. public String getDisplayCountry() it returns the country name of this locale object.
4. public String getDisplayLanguage() it returns the language name of this locale object.
5. public String getDisplayVariant() it returns the variant code for this locale object.
6. public String getISO3Country() it returns the three letter abbreviation for the current locale's
country.
7. public String getISO3Language() it returns the three letter abbreviation for the current locale's
language.

Example of Local class that prints the informations of the default locale

In this example, we are displaying the informations of the default locale. If you want to get the informations
about any specific locale, comment the first line statement and uncomment the second line statement in the
main method.

1. import java.util.*;  
2. public class LocaleExample {  
3. public static void main(String[] args) {  
4. Locale locale=Locale.getDefault();  
5. //Locale locale=new Locale("fr","fr");//for the specific locale  
6.   
7. System.out.println(locale.getDisplayCountry());  
8. System.out.println(locale.getDisplayLanguage());  
9. System.out.println(locale.getDisplayName());  
10. System.out.println(locale.getISO3Country());  
11. System.out.println(locale.getISO3Language());  
12. System.out.println(locale.getLanguage());  
13. System.out.println(locale.getCountry());  
14.       
15. }  
16. }  
download this example
Output:United States
English
English (United States)
USA
eng
en
US
Example of Local class that prints english in different languages

In this example, we are displaying english language in different language. Let's see how english is written in
french and spanish languages.

1. import java.util.*;  
2. public class LocaleExample2 {  
3.     public static void main(String[] args) {  
4.         Locale enLocale = new Locale("en", "US");  
5.         Locale frLocale = new Locale("fr", "FR");  
6.         Locale esLocale = new Locale("es", "ES");  
7.         System.out.println("English language name (default): " +   
8.                             enLocale.getDisplayLanguage());  
9.   
10.         System.out.println("English language name in French: " +   
11.                             enLocale.getDisplayLanguage(frLocale));  
12.         System.out.println("English language name in spanish: " +   
13.                 enLocale.getDisplayLanguage(esLocale));  
14.     }  
15.   
16. }  

Example of Local class that print display language of many locales


In this example, we are displaying the display lanuage of many locales.
1. import java.util.*;  
2. public class LocaleEx {  
3. public static void main(String[] args) {  
4. Locale[] locales = { new Locale("en", "US"),  
5.  new Locale("es", "ES"), new Locale("it", "IT") };   
6.   
7. for (int i=0; i< locales.length; i++) {   
8.  String displayLanguage = locales[i].getDisplayLanguage(locales[i]);   
9.  System.out.println(locales[i].toString() + ": " + displayLanguage);   
10. }   
11. }  
12.   
13. }  
Output:en_US: English
es_ES: espa?ol
it_IT: italiano
ResourceBundle class in Java
1. ResourceBundle class
2. Commonly used methods of ResourceBundle class
3. Example of ResourceBundle class

The ResourceBundle class is used to internationalize the messages. In other words, we can say that it
provides a mechanism to globalize the messages.

The hardcoded message is not considered good in terms of programming, because it differs from one country
to another. So we use the ResourceBundle class to globalize the massages. The ResourceBundle class loads
these informations from the properties file that contains the messages.

Conventionally, the name of the properties file should be filename_languagecode_country code for


exampleMyMessage_en_US.properties.

Commonly used methods of ResourceBundle class

There are many methods in the ResourceBundle class. Let's see the commonly used methods of the
ResourceBundle class.

 public static ResourceBundle getBundle(String basename) returns the instance of the


ResourceBundle class for the default locale.
 public static ResourceBundle getBundle(String basename, Locale locale) returns the instance
of the ResourceBundle class for the specified locale.
 public String getString(String key) returns the value for the corresponding key from this resource
bundle.

Example of ResourceBundle class

Let's see the simple example of ResourceBundle class. In this example, we are creating three files:

 MessageBundle_en_US.properties file contains the localize message for US country.


 MessageBundle_in_ID.properties file contains the localize message for Indonaisa country.
 InternationalizationDemo.java file that loads these properties file in a bundle and prints the
messages.
MessageBundle_en_US.properties

MessageBundle_in_ID.properties

InternationalizationDemo.java
1. import java.util.Locale;  
2. import java.util.ResourceBundle;  
3. public class InternationalizationDemo {  
4.  public static void main(String[] args) {  
5.   
6.   ResourceBundle bundle = ResourceBundle.getBundle("MessageBundle", Locale.US);  
7.   System.out.println("Message in "+Locale.US +":"+bundle.getString("greeting"));  
8.   
9.   //changing the default locale to indonasian   
10.   Locale.setDefault(new Locale("in", "ID"));  
11.   bundle = ResourceBundle.getBundle("MessageBundle");  
12.   System.out.println("Message in "+Locale.getDefault()+":"+bundle.getString("greeting"));  
13.   
14.  }  
15. }  
Output:Message in en_US : Hello, how r u?
Message in in_ID : halo, apa kabar?

Internationalizing Date (I18N with Date)


1. Internationalizing Date
2. Commonly used methods of the DateFormat class
3. Example of Inernationalizing Date

The format of the dates differ from one region to another that is why we internationalize the dates.

We can internationalize the date by using the getDateInstance()method of the DateFormat class. It


receives the locale object as a parameter and returns the instance of the DateFormat class.
Commonly used methods of DateFormat class for internationalizing date

There are many methods of the DateFormat class. Let's see the two methods of the DateFormat class for
internationalizing the dates.

 public static DateFormat getDateInstance(int style, Locale locale) returns the instance of the
DateFormat class for the specified style and locale. The style can be DEFAULT, SHORT, LONG etc.
 public String format(Date date) returns the formatted and localized date as a string.

Example of Internationalizing Date

In this example, we are displaying the date according to the different locale such as UK, US, FRANCE etc. For
this purpose we have created the printDate() method that receives Locale object as an instance. The format()
method of the DateFormat class receives the Date object and returns the formatted and localized date as a
string.

1. import java.text.DateFormat;  
2. import java.util.*;  
3. public class InternationalizationDate {  
4.       
5. static void printDate(Locale locale){  
6. DateFormat formatter=DateFormat.getDateInstance(DateFormat.DEFAULT,locale);  
7. Date currentDate=new Date();  
8. String date=formatter.format(currentDate);  
9. System.out.println(date+" "+locale);  
10. }  
11.   
12. public static void main(String[] args) {  
13.     printDate(Locale.UK);  
14.     printDate(Locale.US);  
15.     printDate(Locale.FRANCE);  
16. }  
17. }  
download this example
Output:01-Mar-2012 en_GB
Mar 1, 2012 en_US
1 mars 2012 fr_FR

Internationalizing Time (I18N with Time)


1. Internationalizing Time
2. Example of Internationalizing Time

The display format of the time differs from one region to another, so we need to internationalize the time.
For internationalizing the time, the DateFormat class provides some useful methods.

The getTimeInstance() method of the DateFormat class returns the instance of the DateFormat class for
the specified style and locale.

Syntax of the getTimeInstance() method is given below:

Example of Internationalizing Time

In this example, we are displaying the current time for the specified locale. The format() method of the
DateFormat class receives date object and returns the formatted and localized time as a string. Notice that
the object of Date class prints date and time both.

1. import java.text.DateFormat;  
2. import java.util.*;  
3.   
4. public class InternationalizingTime {  
5.   
6. static void printTime(Locale locale){  
7. DateFormat formatter=DateFormat.getTimeInstance(DateFormat.DEFAULT,locale);  
8. Date currentDate=new Date();  
9. String time=formatter.format(currentDate);  
10. System.out.println(time+" in locale "+locale);  
11. }  
12.   
13. public static void main(String[] args) {  
14. printTime(Locale.UK);  
15. printTime(Locale.US);  
16. printTime(Locale.FRANCE);  
17. }  
18. }  
download this example
Output:16:22:49 in locale en_GB
4:22:49 PM in locale en_US
16:22:49 in locale fr_FR

Internationalizing Number (I18N with Number)


1. Internationalizing Number
2. Example of Internationalizing Number

The representation of the numbers differ from one locale to another. Internationalizing the numbers is good
approach for the application that displays the informations according to the locales.

The NumberFormat class is used to format the number according to the specific locale. To get the instance
of the NumberFormat class, we need to call eithergetInstance() or getNumberInstance() methods.

Syntax of these methods is given below:

1. public static NumberFormat getNumberInstance(Locale locale)  
2. public static NumberFormat getInstance(Locale locale)//same as above  
3. </textareaa></div>  
4.   
5. <hr/>  
6. <a id="numberex"></a>  
7. <h3 class="h3ex">Example of Internationalizing Number</h3>  
8. <p>In this example, we are internationalizing the number. The format method of the NumberFormat 
class formats the double value into the locale specific number.  
9. </p>  
10.   
11. <div class="codeblock"><textarea name="code" class="java">  
12.   
13. import java.text.NumberFormat;  
14. import java.util.*;  
15.   
16. public class InternalizationNumber {  
17.   
18. static void printNumber(Locale locale){  
19.  double dbl=105000.3245;  
20.  NumberFormat formatter=NumberFormat.getNumberInstance(locale);  
21.  String number=formatter.format(dbl);  
22.  System.out.println(number+" for the locale "+locale);  
23. }  
24.   
25. public static void main(String[] args) {  
26.     printNumber(Locale.UK);  
27.     printNumber(Locale.US);  
28.     printNumber(Locale.FRANCE);  
29.     printNumber(Locale.JAPAN);  
30.   
31. }  
32. }  
download this example
Output:105,500.324 for the locale en_GB
105,000.324 for the locale en_US
105,a000,324 for the locale fr_FR
105,000.324 for the locale ja_JP
Internationalizing Currency (I18N with Currency)
1. Internationalizing Currency
2. Example of Internationalizing Currency

As we have internationalize the date, time and numbers, we can internationalize the currency also. The
currency differs from one country to another so we need to internationalize the currency.

The NumberFormat class provides methods to format the currency according to the locale.


ThegetCurrencyInstance() method of the NumberFormat class returns the instance of the NumberFormat
class.

The syntax of the getCurrencyInstance() method is given below:

1. public static NumberFormat getCurrencyInstance(Locale locale)  
2. </pre></div>  
3. <a id="currencyex"></a>  
4. <h3 class="h3ex">Example of Internationalizing Currency</h3>  
5. <p>In this example, we are internationalizing the currency. The format method of the NumberFormat 
class formats the double value into the locale specific currency.  
6. </p>  
7.   
8. <div class="codeblock"><textarea name="code" class="java">  
9. import java.text.NumberFormat;  
10. import java.util.*;  
11. public class InternalizationCurrency {  
12.   
13. static void printCurrency(Locale locale){  
14.  double dbl=10500.3245;  
15.  NumberFormat formatter=NumberFormat.getCurrencyInstance(locale);  
16.  String currency=formatter.format(dbl);  
17.  System.out.println(currency+" for the locale "+locale);  
18. }  
19.   
20. public static void main(String[] args) {  
21.     printCurrency(Locale.UK);  
22.     printCurrency(Locale.US);  
23.     printCurrency(Locale.FRANCE);  
24. }  
25. }  
download this example
Output:?10,500.32 for the locale en_GB
$10,500.32 for the locale en_US
10 500,32 ? for the locale fr_FR

You might also like