Core Java
Core Java
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.
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
Ex: BASIC
10 begin
20 let a=30,b=20,c;
30 c=a+b;
40 goto 30:print c
50 end
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
Ex: BASIC
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
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
2. The Different part of the program connects with each other by parameter passing & using operating system.
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.
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.
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.
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?
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:
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.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
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).
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.
Now a day 8 versions of java are released, which is listed below with realizing date.
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.
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
dependent.
Note: Java is platform Independent but JVM is platform dependent because every Operating system have different-
Class loader subsystem will load the .class file into java stack and later sufficient memory will be allocated for all the
Heap area
Method area
Java stack
PC register
Native stack
Heap area:
Method area
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
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 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
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
In java we have eight data type which are organized in four groups. They are
These category data types are used for storing integer data in the main memory of computer by allocating sufficient
Integer category data types are divided into four types which are given in following table
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.
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
Float category data type are used for representing float values. This category contains two data types, they are in the
given table
Boolean category data type is used for representing or storing logical values is true or false. In java programming to
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
Note: In C, C++ (Turbo) Boolean data type is not available for representing true false values but a true value can
ata Conversion
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
Example:
String s1="100";
int x=Integer.parseInt(s1);
Example:
String s2="100.75f";
Float y=Float.parseFloat(s2);
In order to convert numeric / fundamental type values into string values, we use the following predefined static
overloaded method.
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
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.
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
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.
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
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
int a=10;
String is=String.valueOf(a);
int x=io.intValue();
String so=io.toString();
int x=Integer.parseInt(so);
Boxing and Unboxing
The process of implicitly converting fundamental type value into equivalent wrapper class object is known as auto
boxing.
In order to convert the fundamental data into equivalent wrapper class object type data we use the following
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.
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
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;
Every variable name should start with either alphabets or underscore ( _ ) or dollar ( $ ) symbol.
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.
Variable declarations
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
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
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment 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
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 " ?: "
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
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
available like javap, javah, jar, javac, java, appletviewer etc. These all tools are used for different-different
purpose.
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
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
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
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
static
* The keyword static indicates that the method is a class
void
* The keyword void indicates that the method doesn’t
args
* The formal parameter args is an array of type String,
or not the code in – Write the method signature for the main
main() method is starting execution block of a java program or any java program start their execution from main
Syntax
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.
String[] args
String args[]
String []args
Syntax
Syntax
Syntax
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
Output
Sun micro system was given following conversions by declaring class, variable, method etc. So that it is highly
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
Example
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
Example
class Student
{
final String COLLEGE_NAME="abcd";
....
....
}
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
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
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>
class Test1
{
public static void main(String[]args)
{
System.out.print("Welcome to Java");
}
}
press ctrl+s
press alt+tab
Execution
java Test1
Note: The filename and the class name must be the same.
Note:
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.
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.
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
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 :
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.......*;
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.
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
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
Scanner(InputStream)
Example
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.
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
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
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
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));
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;
}
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;
}
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 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
Using Ternary Operator reduce the number of line codes and improve the performance of
application.
Syntax
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
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);
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;
}
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.
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
*/
Outer:
{
Inner:
{
if(intArray[intOuter][intInner] == 30)
{
blnFound = true;
break Outer;
}
}
}
if(blnFound == true)
else
}
}
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);
}
}
}
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);
}
}
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”.
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int n3 = Integer.parseInt(args[2]);
int n4=n1+n2+n3;
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
Types of Array
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
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.
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
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
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
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]);
}
}
}
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);
}
}
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.
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
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.
If string is not immutable, changing the string with one reference will lead to the wrong value for the other
references.
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.
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.
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.}
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
Output
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.
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
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
/*
This Java String Array example how to create and use String array or array of Strings in Java.
*/
/*
*/
/*
* This method is particularly useful when we are dealing with very small size array.
*/
String[] myFirstStringArray = new String[]{"String 1", "String 2", "String 3"};
/*
*/
//Observe that giving size is mandatory here. While there was no size given in the first method.
//Note that, like every other arrays, String array starts with index 0 and not index 1.
/*
* String array elements can be retrieved by directly accessing using index. You may also iterate
*/
System.out.println(myFirstStringArray[1]);
System.out.println(mySecondStringArray[i]);
}
}
/*
String 2
String 1
String 2
String 3
*/
}
}
}
}
}
-------------------------------------------------------------------------------------------------------
sortedArray = bubbleSortDescending(unsortedArray);
}
}
return unsortedArray; // which is now sorted
}
}
}
System.out.println();
}
}
StringBuffer
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 ;
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
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.
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.
OutPut
splits.size: 5
Gold
Stocks
Fixed Income
Commodity
Interest Rates
]
Output:
placeSplits.size: 2
London
Switzerland.Europe.Australia
String[] splits = assetTrading.split("\\|"); // two \\ is required because "\" itself require escaping
OutPut:
Gold Trading
Stocks Trading
Fixed Income Trading
Commodity Trading
FX trading
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.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.
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.
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.
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
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
5 [a-z&&[def]] d, e, or f (intersection)
Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex Description
Regex Metacharacters
The regular expression metacharacters work as a short codes.
Regex Description
\b A word boundary
Test it Now
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.
Data Member
Method
Constructor
Block
Class and Interface
State
Behavior
Identity
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.
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.
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)
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.
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. }
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:
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.
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.
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. }
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. }
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within
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.
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.
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
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.
Only two access modifiers is allowed, public and no modifier for classes in java.
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
Private
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
Note: protected members of class is accessible within the same class and other class of same package and also
private: private members of class in not accessible any where in program these are only accessible within the class.
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
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");
}
}
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
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
//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
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 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).
public class AccessModifiersExample {
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.
*/
***********************************************************
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);
}
}
***********************************************************
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;
}
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
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.
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.
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.
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.
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
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
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
1. Dog d=(Dog)new Animal();
2. //Compiles successfully but ClassCastException is thrown at runtime
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. }
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. }
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
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:
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
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
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).
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
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
Syntax
class className
{
..... // Call default constructor
clsname ()
{
Block of statements; // Initialization
}
.....
}
parameterized constructor
If any constructor contain list of variable in its signature is known as paremetrized constructor. A parameterized
Syntax
class ClassName
{
.......
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}
OR
In any class maximum one default constructor but 'n' number of parameterized constructors.
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.
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)
{
..........
..........
}
}
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:
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
As for as real time application are concern overloaded method should exists with same name but with different
implementation part.
class MyVals
{
int a;
double b;
String c;
char d;
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 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);
}
}
}
Overriding
Whenever same method name is existing in both base class and derived class with same types of parameters or
Method Overriding is used to provide specific implementation of a method that is already provided
by its super class.
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
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
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.
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");
}
}
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.
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.
Java programming does not support static polymorphism because of its limitations and java always supports
dynamic polymorphism.
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.
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.
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.
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.
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
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.
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
Advantage of inheritance
If we develop any application using concept of Inheritance than that application have following advantages,
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
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.
An intermediate base class is one in one context with access derived class and in another context same class
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
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.
In order to inherit the feature of base class into derived class we use the following syntax
Syntax
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.
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
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.
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.
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;
}
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;
}
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;
}
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.
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 1 : Program that shows the default execution of constructor when classes are inherited
class Person
{
Person()
{
System.out.println("Constructor of person 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
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.
abstract method
A method that is declared as abstract and does not have implementation is known as 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..
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
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 %
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.
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
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.
Whenever we compile any Interface program it generate .class file. That means the bytecode of an interface appears
in a .class file.
Interface can not contain instance fields. Interface only contains public static final variables.
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
Declaring Interfaces:
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
public static final datatype variable name=value; ----> for data member
Implementing Interfaces:
A class uses the implements keyword to implement an interface. The implements keyword appears in the class
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
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.
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();
}
Output
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
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.
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 */
}
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.
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
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. }
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
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
1. Non-static methods
2. Static methods
In some cases static methods not only can access with class reference but also can access with object reference.
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
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
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
Output
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.
Note: static variable not only can be access with class reference but also some time it can be accessed with object
reference.
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.
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.
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.
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.
example:
Here abstract keyword always makes the jvm to understand the following points.
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.
Here operation is one of the abstract class whose object can’t be created directly but it can be created indirectly.
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();
}
}
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
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 method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Syntax to define the abstract method
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
Output:running safely..
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.
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
Output:running safely..
gear changed
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();
}
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();
}
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
class Test{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
}
}
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.
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:
An abstract base class is one which is containing physical representation of abstract methods which are inherited by
various sub classes.
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
{
......
......
}
......
}
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.
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 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()
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 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.
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.
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.
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 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>
class MyClass {
class ClassA {
class ClassA {
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.
class ClassA {
static int a;
static int b;
ClassA() {
a = 7;
b = 8;
}
}
ClassB() {
super();
}
}
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 {
class ClassA {
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.
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
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
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");
}
}
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");
}
}
}
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.
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.
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
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.
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!...
class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a);
}
else
{
System.out.println(a+b);
}
}
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);
}
}
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.*;
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;
-------------------------------------------------------------------------------------------------------------------------------------------
-
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:
//statements
}
The user defined exceptions must be explicitly thrown using the throw statement whose syntax is
throw ThrowableInstance
Example:
For example the below program creates an user defined exception when the second argument is less than or
equal to zero
D:\java>java userexcep 6 0
The second number should be greater than 0
Invalid Number
D:\java>
---------------------------------------------------------------------------------------------------------------------
public MyException(){
super();
}
public MyException(String expSrt){
super(expSrt);
}
public String toString(){
return "Exception: Age should be 18 to 35 years only";
}
}
}
}
-------------------------------------------------------------------------------------------------------------------------------------------
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
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.
nm=s;
return ("you are not permitted to enter inside "+nm);
}
}
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
Advantage of Applet
Some applets require a specific JRE. If it required new JRE then it take more time to download new
JRE.
init()
start()
stop
destroy
init(): Which will be executed whenever an applet program start loading, it contains the logic to initiate the applet
properties.
destroy(): It will be executed whenever applet window or browser is going to be closed (at the time of destroying the
We can design our own applet program by extending applet class in the user defined class.
Syntax
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.
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>
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>
Some browser does not support <applet> tag so that Sun MicroSystem was introduced a special tool
In this Scenario java program should contains <applet> tag in the commented lines so that appletviewer tools can
import java.applet.*;
import java.awt.*;
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 (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.
Mobile Applications
Navigation Systems
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.
AWT classes.
Class Description
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
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:
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.
public class FirstApplet extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}
<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800" HEIGHT="500"></APPLET>
</BODY>
</HTML>
Applet Code
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.
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.
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.
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.
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.*;
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:
The font setting specified with font method can be implemented using the
setFont()method of the graphics class.
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. 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.
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.
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.
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:
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
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.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
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
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.
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.
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.
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){}
Class declaration
Following is the declaration for java.awt.Label class:
Field
Following are the fields for java.awt.Component class:
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.
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.
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:
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.
void removeActionListener(ActionListener l)
11
Removes the specified action listener so that it no longer receives action events from this button.
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:
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.
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.
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.
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.
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:
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.
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:
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.
Class methods
S.N. Method & Description
void addActionListener(ActionListener l)
3
Adds the specified action listener to receive action events from this list.
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().
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.
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 getPreferredSize()
22
Gets the preferred size of this scrolling list.
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 isMultipleMode()
32
Determines whether this list allows multiple selections.
Dimension minimumSize()
35
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
Dimension preferredSize()
38
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
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 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:
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.
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 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).
Dimension preferredSize()
16
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
void removeActionListener(ActionListener l)
20
Removes the specified action listener so that it no longer receives action events from 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:
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_NONE -- Do not create or display any scrollbars for the text area.
Class constructors
S.N. Constructor & Description
TextArea()
1
Constructs a new text area with the empty string as text.
TextArea(String text)
3
Constructs a new text area with the specified text.
void addNotify()
1
Creates the TextArea's peer.
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 getPreferredSize()
8
Determines the preferred size of this text area.
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.
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).
Dimension preferredSize()
17
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
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:
Class constructors
S.N. Constructor & Description
Choice() ()
1
Creates a new choice menu.
Class methods
S.N. Method & Description
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.
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 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.
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:
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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
controlPanel.add(new MyCanvas());
mainFrame.setVisible(true);
}
public MyCanvas () {
setBackground (Color.GRAY);
setSize(300, 300);
}
Introduction
Image control is superclass for all image classes representing graphical images.
Class declaration
Following is the declaration for java.awt.Image class:
Field
Following are the fields for java.awt.Image class:
static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling algorithm.
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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
controlPanel.add(new ImageComponent("resources/java.jpg"));
mainFrame.setVisible(true);
}
BufferedImage img;
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
Class declaration
Following is the declaration for java.awt.Scrollbar class:
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.
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 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 setValueIsAdjusting(boolean b)
26
Sets the valueIsAdjusting property.
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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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:
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(Frame owner)
5
Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title.
Dialog(Window owner)
10
Constructs an initially invisible, modeless Dialog with the specified owner Window and an empty title.
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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
controlPanel.add(showAboutDialogButton);
mainFrame.setVisible(true);
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
dispose();
}
});
}
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:
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.
FileDialog(Frame parent)
4
Creates a file dialog for loading 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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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
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.
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.
Now the object of concerned event class is created automatically and information about the source and the event get populated
with in same object.
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.
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:
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
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:
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.
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.
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.
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.
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.
A default layout is present in each container which can be overridden using setLayout method.
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.
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.
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.
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);
}
}
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.*;
/*
<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
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.
1) It doesn't block the user because threads are independent and you can perform multiple operations at
same 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.
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.
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 ?
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
Creating a Thread:
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:
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:
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( );
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() //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)
{
System.out.println(Thread.currentThread());
}
}
Note- If you make a thread by using Runnable Interface then it must override the 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
2) NORM_PRIORITY
3) MIN_PRIORITY
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
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
-- 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.
-- Used to test weather a Thread is still running or dead(completed its execution). returns a boolean value based on
the thread working state.
-- To set a thread as Daemon thread. This method should be applied to a thread before starting it. Otherwise it will
throw IllegalThreadStateException.
-- Used to test a thread is daemon or not and returns a boolean value based on it.
-- Pauses the curently executing thread temporarly, and allows other threads to execute.
-- 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
-- Returns the current thread state. This method is introduced from jdk 1.5 onwards.
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.
thread1.start();
thread2.start();
do {
t1IsAlive = false;
System.out.println("t1 is dead.");
t2IsAlive = false;
System.out.println("t2 is dead.");
void randomWait() {
try {
System.out.println("Interrupted!");
synchronized (System.out)
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.
while (true) {
synchronized (o1) {
synchronized (o2) {
System.out.println(o1 + o2);
});
while (true) {
synchronized (o2) {
synchronized (o1) {
System.out.println(o2 + o1);
}
}
});
dLock.t1.start();
dLock.t2.start();
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:
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:
3)notifyAll() method:
Syntax:
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();
}
}
}
// 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 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.
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.
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 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.
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.
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.
read(byte[] b)
read(byte[] b, int off, int len)
readFully(byte[] b)
readDouble()
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.
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.
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.
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:
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.
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
and creates another InputStream instance for the input object and OutputStream instance for the output object
passed as parameter
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.
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
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
if (!success){
System.out.println("Deletion failed.");
System.exit(0);
}
else{
System.out.println("File deleted.");
}
}
switch(args.length){
System.exit(0);
case 1: deletefile(args[0]);
System.exit(0);
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.
Please note that Collection and Map are two top level interfaces.
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.
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.
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 :
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).
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);
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
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;
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
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.
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.
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;
java
cd..
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);
}
}
javac –d . Demo.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.
Let us assume C:\snr is the current directory where we would like to create the
package.
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.
Let us assume D:\sumathi is the target directory. Let us access Tiger.class in forest
package from here.
3rd Step: Now finally, write a program from the target directory D:/sumathi and
access the package.
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.
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
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.
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:
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.
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.
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
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.
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);
}
}
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(...)
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.
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?
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.
which can be used to differentiate variable of class and formal parameters of method or constructor.
To differentiate between formal parameter and data member of the class, the data members of the class must be
preceded by “this.”.
Syntax
Note: If any variable is preceded by “this.” JVM treated that variable as class variable.
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 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() 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
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:
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.
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
}
}
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:
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
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
Example
It makes a method final, meaning that sub classes can not override this method. The compiler checks and gives an
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
}
}
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
Example
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
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.
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).
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
className.variableName=10;
className.methodName();
Example
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
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
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
Static or class 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.
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.
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
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the
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
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
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.
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
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
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
class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
public static void main(String args[])
{
System.out.println("This is main()");
}
}
Output
This is main()
class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
}
Output
Output:
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:
This is main()
Note: "Here static block run according to there order (sequence by) from top to bottom.
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
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
To differentiate between formal parameter and data member of the class, the data member of the class must be
preceded by "this".
which can be used to differentiate variable of class and formal parameters of method or constructor.
preceded by "this".
Syntax
class Employee
{
int id;
String name;
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
class Employee
{
int id;
String name;
Output
111 Harry
112 Jacy
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
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
By using this keyword you can invoke the method of the current class. If you do not use the this keyword, compiler
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+
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
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
Syntax
super.baseclass features.
Whenever the derived class inherit base class data members there is a possibility that base class data member are
In order to differentiate between the data member of base class and derived class, in the context of derived class the
Syntax
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
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");
}
}
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}
Output
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
class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
void display()
{
message();//will invoke or call parent class message() method
}
Output
Good Morning Sir
The super keyword can also be used to invoke or call the parent class constructor. Constructor are calling from
To establish the connection between base class constructor and derived class constructors JVM provides two
Super()
Super(...)
Super()
Super() It is used for calling super class default constructor from the context of derived class constructors.
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
HR class Constructor
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.
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
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
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
Note: Volatile variable means its value keep on changing where as final variable means its value never changes.
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
.....
.....
.....
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
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
.....
Note:No outer class made as private class otherwise this is not available for JVM at the time of execution.
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.
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()
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
2. If inner class is static the object reference can be created with the following syntax
Syntax
class Outer_class
.....
.....
class External_Class
}
Example
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.
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
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.
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
Syntax
......
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.
To make the class as abstract class, whose definition must be preceded by a abstract keyword.
Example
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
Output
An object of abstract class can not be created directly but it can be created indirectly. It means you can create an
Example
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.
More performance
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.
An abstract base class is one which is containing physical representation of abstract methods which are inherited by
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
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
Output
Mileage is 60 km/ltr..
Output
constructor is invoked
running safely..
40
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
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
Type of package
Package are classified into two type which are given below.
These are the package which are already designed by the Sun Microsystem and supply as a part of java API, every
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.
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
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
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");
}
}
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
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,
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
Un-Checked Exception
These are the exception both identifies or raised at run time, these can be handle using RunTimeException class.
Error Exception
1 Can be handle. Can not be handle.
Example: Example:
2 NoSuchMethodError ClassNotFoundException
OutOfMemoryError NumberFormateException
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.
try
catch
finally
throws
throw
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".
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
try block
Inside try block we write the block of statements which causes executions at run time in other words 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.
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".
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
You can write multiple catch blocks for generating multiple user friendly error messages to make your application
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
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.
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.
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
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.
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.
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.
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:
o If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent 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
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.
By the help of custom exception, you can have your own exception and message.
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. }
Understanding Type
Let's understand the type of instance.
1. int data=30;
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.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
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.
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.
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
1. Dog d=new Animal();//Compilation error
1. Dog d=(Dog)new Animal();
2. //Compiles successfully but ClassCastException is thrown at runtime
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 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
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
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.
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
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.
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. }
Output:
nice fruits
Output:
nice fruits
Internal working of given 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.
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. }
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.
50
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.
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
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.
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. }
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
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:
2) public static Class forName(String className)throws loads the class and returns
ClassNotFoundException the reference of Class class.
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
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
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
Here T is the generic version. You can think it like Object class. You will learn about generics later.
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. }
1. javap fully_class_name
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. }
Option Description
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.
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.
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.
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.
The String class and all the wrapper classes implementsjava.io.Serializable interface by default.
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.
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
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.
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.
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.
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. }
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.
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.
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.
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. }
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
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 ?
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.
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.
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
Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket
and DatagramPacket classes are used for connection-less socket programming.
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.
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.
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
Method Description
public URLConnection it returns the instance of URLConnection i.e. associated with this
openConnection() URL.
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.
The openConnection() method of URL class returns the object of URLConnection class. Syntax:
1. public URLConnection openConnection()throws IOException{}
By the help of HttpURLConnection class, you can information of any HTTP URL such as header information,
status code, response code etc.
The openConnection() method of URL class returns the object of URLConnection class. Syntax:
1. public URLConnection openConnection()throws IOException{}
1. URL url=new URL("http://www.javatpoint.com/java-tutorial");
2. HttpURLConnection huc=(HttpURLConnection)url.openConnection();
Output:
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.
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:
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
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. }
JButton class:
The JButton class is used to create a button that have plateform-independent implementation.
To create the executable jar file, you need to create .mf file, also known as 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.
The jar tool provides many switches, some of them are as follows:
Now, let's write the code to generated the executable jar using mf file.
1. jar -cvmf myfile.mf myjar.jar First.class
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.
Note: The JRadioButton class extends the JToggleButton class that extends AbstractButton class.
ButtonGroup class:
The ButtonGroup class can be used to group multiple buttons so that at a time only one button can be
selected.
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)
JColorChooser class:
The JColorChooser class is used to create a color chooser dialog box so that user can select any color.
JColorChooser(Color initialColor): is used to create a color chooser pane with the specified color
initially.
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.
JSlider class:
The JSlider is used to create the slider. By using JSlider a user can select a value from a specific range.
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
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. }
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.
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. }
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. }
RMI
next →← prev
The RMI provides remote communication between the applications using two objects 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:
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:
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.
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. }
Now provide the implementation of the remote interface. For providing the implementation of the Remote
interface, we need to
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
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
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. 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. }
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. }
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.
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. }
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. }
4) Compile the class rmic tool and start the registry service by rmiregistry tool
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.
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.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 ?
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.
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.
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.
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.
It should be used to read byte-oriented data for example to read image, audio, video etc.
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. }
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.
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.
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.
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.
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. }
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
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...
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:
Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to read and
write the textual information.
FileWriter(File file) creates a new file. It gets file name in File object.
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...
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.
1) public int read() returns a character in ASCII form. It returns -1 at the end of 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.
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. }
InputStreamReader
Console
Scanner
DataInputStream etc.
InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
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
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
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.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
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.
System class provides a static method console() that returns the unique instance of Console class.
1. public static Console console(){}
1. Console c=System.console();
Output:
Output:
Enter password:
Password is: sonoo
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.
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.
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:
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.
public void format(Locale l, Object format, Object... args): it writes the formatted string to the
current stream using specified 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.
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.
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.
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 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?
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.
1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)
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. }
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.
There are many methods in the ResourceBundle class. Let's see the commonly used methods of the
ResourceBundle class.
Let's see the simple example of ResourceBundle class. In this example, we are creating three files:
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?
The format of the dates differ from one region to another that is why we internationalize the dates.
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.
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
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.
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
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.
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.
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