Java Tpoint
Java Tpoint
James Gosling
What is Java?
Java is a programming language and a platform.
Platform Any hardware or software environment in which a program runs, known as a platform. Since
Java has its own Runtime Environment (JRE) and API, it is called platform.
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used.
Some of them are as follows:
1.
2.
3.
4.
Mobile
5.
Embedded System
6.
Smart Card
7.
Robotics
8.
Games etc.
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.
History of Java
1.
2.
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.
At that time, it was a advanced concept for the green team. But, it was good for internet
programming. Later, Netscape Navigator incorporated Java technology.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
Let's see 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.
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why they choosed java name for java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique,
and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was so
unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).
2.
3.
4.
5.
6.
7.
8.
9.
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:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. 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 softwarebased 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:
1. Runtime Environment
2. API(Application Programming Interface)
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
Classloader- adds security by separating the package for the classes of the local
file system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate
access right to objects.
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.
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.
We will learn how to write the hello java program. We can write a simple hello java program
easily.
Here, we have created a class named Simple that contains only main method which prints a
message hello java.
install the JDK if you don't have installed it, download the JDK and install it.
3.
System.out.println("Hello Java");
4.
5. }
To compile:
javac Simple.java
To execute:
java Simple
Output:Hello Java
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
void is the return type of the method, it means it doesn't return any value.
String[] args is used for command line argument. We will learn it later.
class A{
static public void main(String... args){
System.out.println("hello java4");
}
};
In the previous page, we have learned about the first program, how to compile and how to run
the first java program. Here, we are going to learn, what happens while compiling and running
the java program. Moreover, we will see some question based on the first 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
2. permanent
1)Setting temporary Path of JDK in Windows:
For setting the temporary path of JDK, you need to follow these steps:
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
For Example:
1)Go to MyComputer properties
2)click on advanced tab
3)click on environment variables
4)click on new tab of user variables
5)write path in variable name
export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under Root (/home).
Understanding the difference between JDK, JRE and JVM is important in Java. We will
have brief overview of JVM here. If you want to gain the detailed knowledge of JVM,
move to the next page. Firstly, let's see the basic differences between the JDK, JRE
and JVM.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
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 (i.e.JVM is plateform
dependent).
The JVM performs four main tasks:
Loads code
Verifies code
Executes code
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.
Loads code
Verifies code
Executes code
Memory area
Register set
Garbage-collected heap
1) Classloader:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
PC (program counter) register. It contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack:
Variable
Variable is name of reserved area allocated in memory.
Types of Variable
There are three types of variables in java
local variable
instance variable
static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called
System.out.println("Factorial of 5="+result);
}
rev=rev*10+a;
n=n/10;
}
if(rev==b)
System.out.println("it is Palindrome");
else
System.out.println("it is not palinedrome");
}
}
In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm
that provides many concepts such as inheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object, is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
When one object acquires all the properties and behaviours of parent object i.e. known as
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier where as in Procedureoriented programming language it is not easy to manage if code grows as project
size grows.
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language
a global data can be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.
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.
Name
class
name
Convention
should begin with uppercase letter and be a noun
e.g.String,System,Thread etc.
In this page, we will learn about the objects and classes. In object-oriented
programming, we design a program using objects and classes. Object is
the physical entity whereas class is the logical entity. A class works as a
template from which we create the objects.
Object
A runtime entity that has state and behaviour is known as an object. For example:
chair, table, pen etc. It can be tengible or intengible (physical or logical).
An object has three characterstics:
For Example: Pen is an object. Its name is Reynolds, color is white etc.
known as its state. It is used to write, so writing is its behaviour.
Object is an instance of a class.Class is a template or blueprint from
which objects are created.So object is the instance(result) of a class.
Class
A class is a group of objects that have common property. It is a template or
blueprint from which objects are created.
A class in java can contain:
data member
method
constructor
block
}
Simple Example of Object and Class
In this example, we have created a Student class that have two data
members id and name. We are creating the object of the Student class by
new keyword and printing the objects value.
class Student
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id+" "+s1.name);
}
}
Output:0 null
Instance variable
A variable that is created inside the class but outside the method, is
known as instance variable.Instance variable doesn't get memory at
compile time.It gets memory at runtime when object(instance) is
created.That is why, it is known as instance variable.
Method
In java, a method is like function i.e. used to expose behaviour of an
object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
void displayInformation(){System.out.println(rollno+"
"+name);}//method
s1.displayInformation();
s2.displayInformation();
}
}
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and
reference variable refers to the object allocated in the Heap memory area.
Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
By new keyword
By newInstance() method
By clone() method
Annonymous object
Annonymous simply means nameless.An object that have no reference is
known as annonymous object.
If you have to use an object only once, annonymous object is a good
approach.
class Calculation{
jects
Let's see the example:
class Rectangle{
int length;
int width;
void calculateArea(){System.out.println(length*width);}
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
In java, Methood Overloading is not possible by changing the return type of the method.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
class Calculation
{
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[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
Output:30
40
10.
11.
class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
12.
13.
14.
15.
16.
17.
18.
19.
}
}
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of
method?
In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity. Let's see how ambiguity may occur:
because there was problem:
10.
11.
12.
13.
14.
15.
16.
17.
18.
class Calculation
{
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[])
{
}
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be
called
{
10.
11.
12.
13.
System.out.println(a);
}
public static void main(String args[])
System.out.println("main() method invoked");
main(10);
}
}
Output:main() method invoked
10
As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.
class Calculation
{
void sum(int a,long b)
{System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
10.
11.
12.
13.
14.
15.
16.
17.
18.
}
}
Output:40
60
10.
11.
12.
13.
14.
15.
16.
17.
{
System.out.println("a method invoked");
}
void sum(long a,int b)
{
System.out.println("b method invoked");
}
public static void main(String args[])
{
}
Output:Compile Time Error
Constructor in Java
Constructor is a special type of method that is used to initialize the object.
Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Types of constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor.
<class_name>(){}
Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
}
Output:111 Karan
222 Aryan
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors
by taking into account the number of parameters in the list and their type.
name = n;
}
Student(int i,String n,int a)
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
Output:111 Karan 0
222 Aryan 25
Method
By constructor
In this example, we are going to copy the values of one object into another using
constructor.
class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
Student(Student s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
}
Output:111 Karan
111 Karan
Student(int i,String n)
id = i;
name = n;
}
Student()
{
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
}
Output:111 Karan
111 Karan
static keyword
The static keyword is used in java mainly for memory management. We may apply static
keyword with variables, methods, blocks and nested class. The static keyword belongs to
the class than instance of the class.
1) static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees,college name of
students etc.
The static variable gets memory only once in class area at the time of class loading.
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so
instance data member is good.Here, college refers to the common property of all objects.If
we make it static,this field will get memory only once.
Student(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
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.
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:1
1
1
2
3
2) static method
If you apply static keyword with any method, it is known as static method
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student.change();
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
memory allocation.
3)static block
super keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is refered by instance bydefault, but I have to refer parent class
instance variable that is why we use super keyword to distinguish between parent class
instance variable and current class instance variable.
Solution by super keyword
//example of super keyword
class Vehicle{
int speed=50;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
} Output:50
As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement.If you are creating your own constructor and you
don't have either this() or super() as the first statement, compiler will provide super() as
Output:Vehicle is created
10
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class
In case there is no method in subclass as parent, there is no need to use super. In the
example given below message() method is invoked from Student class but Student class
does not have message() method, so you can directly call message() method.
Que) What is the use of instance initializer block while we can directly assign a
value in instance data member? For example:
class Bike{
int speed=100;
}
}
}
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
In the above example, it seems that instance initializer block is firstly invoked but NO.
Instance intializer block is invoked at the time of object creation. The java compiler
copies the instance initializer block in the constructor after the first statement super().
So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in every
constructor.
There are mainly three rules for the instance initializer block. They are as follows:
1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is invoked
(i.e. after super() constructor call).
3. The instance initializer block comes in the order in which they appear.
{
System.out.println("instance initializer block is invoked");
}
public static void main(String args[])
{
B b1=new B();
B b2=new B(10);
}
}
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
2) final method
If you make any method as final, you cannot override it.
}
Output:Compile Time Error
3) final class
If you make any class as final, you cannot extend it.
class Bike
{
final int speedlimit;//blank final variable
{
Bike()
speedlimit=70;
System.out.println(speedlimit);
}
}
}
new Bike();
Output:70
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
class B extends A{}
A a=new B();//upcasting
}
Output:running safely with 60km.
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Output:90
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk
Understanding Type
Let's understand the type of instance.
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.
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
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.
}
}
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.
Let's see the real use of instanceof keyword by the example given below.
interface Printable{}
class A implements Printable{
public void a(){System.out.println("a method");}
}
class B implements Printable{
public void b(){System.out.println("b method");}
}
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
class Call{
void invoke(Printable p){//upcasting
if(p instanceof A){
A a=(A)p;//Downcasting
a.a();
}
if(p instanceof B){
B b=(B)p;//Downcasting
b.b();
}
}
}//end of Call class
class Test{
public static void main(String args[]){
Printable p=new B();
Call c=new Call();
c.invoke(p);
}
}
Output: b method
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.
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.
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
Output:drawing circle
obj.run();
obj.changeGear();
}
}
Output:running safely..
gear changed
//example of abstract class having constructor, field and method
abstract class Bike
{
int limit=30;
Bike(){System.out.println("constructor is invoked");}
void getDetails(){System.out.println("it has two wheels");}
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
}
Output:constructor is invoked
running safely..
it has two wheels
30
Rule: If there is any abstract method in a class, that class must be abstract.
class Bike{
abstract void run();
}
Output:compile time error
Rule: If you are extending any abstact class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:I am a
I am b
I am c
I am d
nterface 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 is a blueprint of a class. It has static constants and abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only
abstract methods in the interface. It is used to achieve fully abstraction and multiple
inheritance in Java.
Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
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.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}
Output:Hello
Welcome
}
interface Showable{
void print();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}
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.
Note: A class implements interface but One interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class A implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}
Output:Hello
Welcome
Nested Interface
Note: An interface can have another interface i.e. known as nested interface. We will learn it
in detail in the nested classes chapter. For example:
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
Package in Java
A package is a group of similar types of classes, interfaces and sub-packages.
Package can be categorized in two form, built-in package and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Package
Package is used to categorize the classes and interfaces so that they can be easily
maintained.
1.
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Output:Hello
Output:Hello
Note: Sequence of the program must be package then import then class.
Subpackage
Package inside the package is called the subpackage. It should be created to categorize
the package further.
Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related
classes in io package, Server and ServerSocket classes in net packages and so on.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Temporary
o
By -classpath switch
Permanent
o
By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
//save as C.java otherwise Compilte Time Error
class A{}
class B{}
public class C{}
Access Modifiers
1. private access modifier
2. Role of private constructor
3. default access modifier
4. protected access modifier
5. public access modifier
6. Applying access modifier with method overriding
There are two types of modifiers in java: access modifier and non-access modifier. The
access modifiers specifies accessibility (scope) of a datamember, method, constructor or
class.
There are 4 types of access modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within class.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
6.
7.
8.
9.
10.
11.
12.
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
7.
8.
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.
4) public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
within class
within package
outside package
Private
Default
Protected
Public
Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g.
capsule i.e mixed of several medicines.
We can create a fully encapsulated class by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
Java Bean is the example of fully encapsulated class.
Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or writeonly.
It provides you the control over the data. Suppose you want to set the value of id i.e.
greater than 100 only, you can write the logic inside the setter method.
Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Description
Example of clone()
method (Object cloning)
Let's see the simple example of object
cloning
class Student implements Cloneable{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
Output:101 amit
101 amit
As you can see in the above example, both reference variables have the same value. Thus,
the clone() copies the values of an object to another. So we don't need to write explicit code
to copy the value of an object to another.
If we create another object by new keyword and assign the values of another object to this
one, it will require a lot of processing on this object. So to save the extra processing task we
use clone() method.
Array in Java
Normally, array is a collection of similar type of elements that have contiguous memory
location.
In java, array is an object the contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed elements in an array.
Array is index based, first element of the array is stored at 0 index.
Advantage of Array
Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
Types of Array
There are two types of array.
Multidimensional Array
Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
Copying an array
We can copy an array to another by the arraycopy method of System class.Syntax
arraycopy method
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
Output:caffein
Addition 2 matrices
Let's see a simple example that adds two matrices.
class AE{
public static void main(String args[]){
//creating two matrices
of
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:2 6 8
6 8 10
strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you
perform operations in the floating-point variable. The precision may differ from platform
to platform that is why java programming language have provided the strictfp keyword,
so that you get same result on every platform. So, now you have better control over the
floating-point arithmetic.
So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
1.
String literal
2.
new keyword
String
Generally string is a sequence of characters. But in java, string is an object. String class is
used to create string object.
Do You Know ?
What code is written by the compiler if you concat any string by + (string
concatenation operator) ?
1) String literal
String literal is created by double quote.For Example:
String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance returns. If the string
does not exist in the pool, a new String object instantiates, then is placed in the pool.For
example:
String s1="Welcome";
String s2="Welcome";//no new object will be created
In the above example only one object will be created.First time JVM will find no string
object with the name "Welcome" in string constant pool,so it will create a new
object.Second time it will find the string with the name "Welcome" in string constant
pool,so it will not create new object whether will return the reference to the same
instance.
Note: String objects are stored in a special memory area known as string constant
pool inside the Heap memory.
2) By new keyword
1.
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:
class Simple{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
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:
class Simple{
public static void main(String args[]){
String
String
String
String
s1="Sachin";
s2="Sachin";
s3=new String("Sachin");
s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
Output:true
true
false
//Example of equalsIgnoreCase(String) method
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
Output:false
true
2) By == operator
The = = operator compares references not values.
//<b><i>Example of == operator</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Output:true
false
3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values
compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:
s1 == s2 :0
s1 > s2
:positive value
s1 < s2
:negative value
}
}
Output:Sachin Tendulkar
2) By concat() method
concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}
//<b><i>Example of concat(String) method</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Output:Sachin Tendulkar
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is
inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex,int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.
In case of string:
}
}
Output:Tendulkar
Sachin
Description
First seven methods have already been discussed.Now Let's take the example of other
methods:
trim() method
class Simple{
public static void main(String args[]){
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
}
Output:Sachin
Sachin
}
}
Output:true
true
charAt() method
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}
Output:S
h
length() method
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.length());//6
}
}
Output:6
intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this
String object as determined by the equals(Object) method, then the string from the pool
is returned. Otherwise, this String object is added to the pool and a reference to this
String object is returned.
class Simple{
public static void main(String args[]){
String s=new String("Sachin");
String s2=s.intern();
System.out.println(s2);//Sachin
}
}
Output:Sachin
StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class is same as String except it is mutable i.e. it can be changed.
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK1.5.
capacity as length.
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
The instance variable of the class is final i.e. we cannot change the value of it
after creating an object.
There is no setter methods i.e. we have no option to change the value of the
instance variable.
These points makes this class as immutable.
calls toString() method, overriding this method will return the specified values. Let's
understand it with the example given below:
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple
way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Description
StringTokenizer(String str)
Description
boolean hasMoreTokens()
String nextToken()
boolean hasMoreElements()
Object nextElement()
int countTokens()
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
name
is
khan
}
}
Output:Next token is : my
Checked Exception
2.
Unchecked Exception
3.
Error
Exception
In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors.
Do You Know ?
What are the 4 rules for using exception handling with method overriding ?
Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3)Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
int a=50/0;//ArithmeticException
try block
Enclose the code that might throw an exception in try block. It must be used within the
method and must be followed by either catch or finally block.
catch block
Catch block is used to handle the Exception. It must be used after the try block.
As displayed in the above example, rest of the code is not executed i.e. rest of the
code... statement is not printed. Let's see what happens behind the scene:
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
Prints the stack trace (Hierarchy of methods where the exception occurred).
But if exception is handled by the application programmer, normal flow of the application
is maintained i.e. rest of the code is executed.
Rule:At a time only one Exception is occured and at a time only one catch block is
executed.
Rule:All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:Compile-time error
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Example:
<b><i>Example of nested try block</i></b>
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
finally block
The finally block is a block that is always executed. It is mainly used to perform some
important tasks such as closing connection, stream etc.
finally block can be used to put "cleanup" code such as closing a file,closing
connection etc.
case 1
Program in case exception does not occur
class Simple{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
case 2
Program in case exception occured but not handled
class Simple{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
case 3
Program in case exception occured and handled
class Simple{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit()
or by causing a fatal error that causes the process to abort).
throw keyword
The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used
to throw custom exception. We will see custom exceptions later.
}
Output:Exception in thread main java.lang.ArithmeticException:not valid
Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method,If not caught there, the exception again
drops down to the previous method, and so on until they are caught or until they reach
the very bottom of the call stack.This is called exception propagation.
In the above example exception occurs in m() method where it is not handled,so it is
propagated to previous n() method where it is not handled, again it is propagated to p()
method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p()
method,n() method or m() method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
throws keyword
The throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
In case you handle the exception, the code will be executed fine whether exception
occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Test{
public static void main(String args[]){
try{
Test t=new Test();
t.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
A)In case you declare the exception, if exception does not occur, the code will be
executed fine.
B)In case you declare the exception if exception occures, an exception will be thrown
at runtime because throws does not handle the exception.
System.out.println("normal flow...");
}
Output:device operation performed
normal flow...
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
System.out.println("normal flow...");
}
Output:Runtime Exception
throws keyword
2) Rule: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but can declare unchecked exception.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");} }
class Child extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new Child();
p.msg();
}
}
Output:child
}
Output:Compile Time Error
Output:child
}
Output:child
}
Output:child
Custom Exception
If you are creating your own Exception that is known as custom exception or user-
defined exception.
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class Excep13{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
}
}
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
class Nested_class_Name{
...
}
...
}
Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Do You Know ?
What is the internal code generated by the compiler for member inner class ?
Can we access the non-final local variable inside the local inner class ?
Output:nice fruits
Emp$1(){}
void eat()
{
System.out.println("nice fruits");
}
{
Emp$1(){}
void eat(){System.out.println("nice fruits");}
}
static nested class cannot access non-static (instance) data member or method.
}
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.
}
Output:data is 30
Nested Interface
An interface which is declared within another interface or class is known as nested
interface. The nested interfaces are used to group related interfaces so that they can be
easy to maintain. The nested interface must be referred by the outer interface or class.
It can't be accessed directly.
Nested interface must be public if it is declared inside the interface but it can
have any access modifier if declared within the class.
}
class Test implements A.Message{
public void msg(){System.out.println("Hello nested interface");}
public static void main(String args[]){
A.Message message=new Test();//upcasting here
message.msg();
}
}
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
Multithreading is a process of executing multiple threads simultaneously.
Thread is basically a lightweight subprocess, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking. But we use
multithreading than mulitprocessing because threads share a common memory area.
They don't allocate separate memory area so save memory, and context-switching
between the threads takes less time than processes.
Multithreading is mostly used in games, animation etc.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
Each process have its own address in memory i.e. each process allocates separate
memory area.
Process is heavyweight.
Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
Thread is lightweight.
What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path
of execution. It shares the memory area of process.
As shown in the above figure, thread is executed inside the process. There is contextswitching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
Note:At a time only one thread is executed.
Do You Know ?
Why your class, which extends the Thread class, object is treated as thread ?
Who is responsible for it ?
What is the Thread Schedular and what is the difference between preemptive
scheduling and time slicing ?
Why JVM terminates the daemon thread if there is no user threads remaining ?
Multithreading
Thread Schedular
Sleeping a thread
Joining a thread
Naming a thread
Priority of a thread
Daemon Thread
ShutdownHook
Garbage collection
Synchronized block
Static synchronization
Deadlock
Inter-thread communication
1)New
The thread is in new state if you create an instance of Thread class but before the
2)Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3)Running
The thread is in running state if the thread scheduler has selected it.
4)Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5)Terminated
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Thread()
Thread(String name)
Thread(Runnable r)
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
When the thread gets a chance to execute, its target run() method will run.
The thread scheduler is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread
schedular.
The thread schedular mainly uses preemptive or time slicing scheduling to schedule
the threads.
time.Syntax:
Output:1
1
2
2
3
3
4
4
5
5
As you know well that at a time only one thread is executed. If you sleep a thread for
the specified time,the thread shedular picks up another thread and so on.
Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
//<b><i>Example of join() method</i></b>
class Multi extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
Multi t1=new Multi();
Multi t2=new Multi();
Multi t3=new Multi();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above example,when t1 completes its task then t2 and t3 starts
executing.
//<b><i>Example of join(long miliseconds) method</i></b>
class Multi extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then
t2 and t3 starts executing.
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
Syntax:
public static Thread currentThread()
//<b><i>Example of currentThread() method</i></b>
class Multi6 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
Multi6 t1=new Multi6();
Multi6 t2=new Multi6();
t1.start();
t2.start();
}
}
Output:Thread-0
Thread-1
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
thread.
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:running
running
running
running
thread
thread
thread
thread
name is:Thread-0
priority is:10
name is:Thread-1
priority is:1
Daemon Thread
There are two types of threads user thread and daemon thread. The daemon thread is a
service provider thread. It provides services to the user thread. Its life depends on the
user threads i.e. when all the user threads dies, JVM terminates this thread
automatically.
It provides services to user threads for background supporting tasks. It has no role
in life than to serve user threads.
Note: If you want to make a user thread as Daemon, it must not be started otherwise
it will throw IllegalThreadStateException.
class MyThread extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String[] args){
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t1.setDaemon(true);//will throw exception here
t2.start();
}
}
Output:exception in thread main: java.lang.IllegalThreadStateException
Where is it used?
It is used in Servlet and JSP where container creates a thread pool to process the request.
Output:
}
Output:task one
task one
task one
//<b><i>Program of performing single task by multiple threads</i></b>
class Multi3 implements Runnable{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
Thread t1 =new Thread(new Multi3());//passing annonymous object of Multi3 class
Thread t2 =new Thread(new Multi3());
t1.start();
t2.start();
}
}
Output:task one
task one
t1.start();
t2.start();
}
}
Output:task one
task two
Garbage Collection:
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically.
1) By nulling a reference:
Employee e=new Employee();
e=null;
3) By annonymous object:
1.
new Employee();
finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in System
class as:
1.
Note: The Garbage collector of JVM collects only those objects that are created
by new keyword. So if you have created any object without new, you can use
finalize method to perform cleanup processing (destroying remaining objects).
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
1.
Synchronization
Synchronization is the capability of control the access of multiple threads to any shared
resource. Synchronization is better in case we want only one thread can access the shared
resource at a time.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
15
300
20
400
25
500
When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the method returns.
class Use{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500
Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
200
300
400
500
100
200
300
400
500
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
public class Test {
public static void main(String[] args) {
Thread t1=new Thread(){
public void run(){
Table.printTable(1);
}
};
Thread t2=new Thread(){
public void run(){
Table.printTable(10);
}
};
Thread t3=new Thread(){
public void run(){
Table.printTable(100);
}
};
Thread t4=new Thread(){
public void run(){
Table.printTable(1000);
}
};
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other to release the
lock, the condition is called deadlock.
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
wait()
notify()
notifyAll()
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, so it must be called from the
synchronized method only otherwise it will throw exception.
Method
Description
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
6. After completion of the task, thread releases the lock and exits the monitor state of
the object.
sleep()
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets
the interrupt flag to true. Let's first see the methods provided by the Thread class for
thread interruption.
In this example, after interrupting the thread, we are propagating it, so it will stop
working. If we don't want to stop the thread, we can handle it where sleep() or wait()
method is invoked. Let's first see the example where we are propagating the exception.
class A extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
A t1=new A();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}
}
Output:Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
A t1=new A();
t1.start();
t1.interrupt();
}
}
Output:Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...
Let's understand the java reentrant monitor by the example given below:
class Reentrant {
public synchronized void m() {
n();
System.out.println("this is m() method");
}
public synchronized void n() {
System.out.println("this is n() method");
}
}
In this class, m and n are the synchronized methods. The m() method internally calls the
n() method.
Now let's call the m() method on a thread. In the class given below, we are creating thread
using annonymous class.
class ReentrantExample{
public static void main(String args[]){
final Reentrant re=new Reentrant();
Thread t1=new Thread(){
public void run(){
re.m();//calling method of Reentrant class
}
};
t1.start();
}}
Output: this is n() method
this is m() method
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.
Three streams are created for us automatically:
Do You Know ?
How to write a common data to multiple files using single stream only ?
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.
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.
Description
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an
input stream of bytes.
Description
FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for characteroriented data, prefer FileWriter.But you can write byte-oriented as well as character-oriented
data.
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}
Output:success...
FileInputStream class:
A FileInputStream obtains input bytes from a file.It is used for reading streams of raw bytes
such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data.For example, to read image etc.
}
Output:Sachin is my favourite player.
ByteArrayOutputStream class:
In this stream, the data is written into a byte array. The buffer automatically grows as data
is written to it.
Closing a ByteArrayOutputStream has no effect.
SequenceInputStream class:
SequenceInputStream class is used to read data from multiple streams.
System.out.println((char)i);
}
}
BufferedOutputStream class:
BufferedOutputStream used an internal buffer. It adds more efficiency than to write data
directly into a stream. So, it makes the performance fast.
}
}
Output:success...
FileWriter class:
FileWriter class is used to write character-oriented data to the file. Sun Microsystem has
suggested not to use the FileInputStream and FileOutputStream classes if you have to read
and write the textual information.
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}
Output:success...
FileReader class:
FileReader class is used to read data from the file.
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.
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.
Syntax:
1.
Console c=System.console();
System.out.println("Enter your name");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
import java.io.*;
class A{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password");
char[] ch=c.readPassword();
System.out.println("Password is");
for(char ch2:ch)
System.out.print(ch2);
}
}
java.util.Scanner class:
There are various ways to read input from the keyboard, the java.util.Scanner class is one
of them. The Scanner class breaks the input into tokens using a delimiter which is
whitespace bydefault. It provides many methods to read and parse various primitive values.
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.
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 print(char[] c): it prints the specified character array values.
public void println(boolean b): it prints the specified boolean value and
terminates the line.
public void println(char c): it prints the specified char value and terminates the
line.
public void println(char[] c): it prints the specified character array values and
terminates the line.
public void println(int i): it prints the specified int value and terminates the
line.
public void println(long l): it prints the specified long value and terminates the
line.
public void println(float f): it prints the specified float value and terminates the
line.
public void println(double d): it prints the specified double value and
terminates the line.
public void println(String s): it prints the specified string value and terminates
the line./li>
public void println(Object obj): it prints the specified object value and
terminates the line.
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.
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.
import java.util.zip.*;
class UnCompress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("def.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D.java");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}
Serialization
Serialization is a mechanism of writing the state of an object into a byte stream. It is
mainly used in Hibernate, JPA, EJB etc. The reverse operation of the serialization is called
deserialization. The String class and all the wrapper classes implements Serializable
interface bydefault.
Advantage of Serialization
It is mainly used to travel object's state on the network.
ObjectOutputStream class:
An ObjectOutputStream 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.
Example of Serialization
In this example, we are going to serialize the object of Student class. The writeObject()
method of ObjectOutputStream class provides the functionality to serialize the object.
We are saving the state of the object in the file named f.txt.
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
Output:success
Deserilization:
Deserialization is the process of reconstructing the object from the serialized state.It is
the reverse operation of serialization.
ObjectInputStream class:
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Example of Deserialization:
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}
}
Output:211 ravi
this.fee=fee;
}
}
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.
Externalizable interface:
The Externalizable interface provides the facility of writing the state of an object into a
byte stream in compress format. It is not a marker interface.
The Externalizable interface provides two methods:
Rule: In case of array or collection, all the objects of array or collection must be
serializable,if any object is not serialiizable then serialization will be failed.
Networking:
Networking is a concept of connecting two or more computing devices together so that
we can share resources.
Advantage:
sharing resources
Do You Know ?
URL class
InetAddress class
Networking Terminology:
There are some networking terminologies given below:
IP Address
Protocol
Port Number
MAC Address
Socket
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.
Protocol:
A protocol is a set of rules basically that is followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
Socket Programming:
Socket programming is performed for communication between the machines. Socket
programming can be connection-oriented or connectionless. Socket and ServerSocket
classes are used for connection-oriented socket programming. The client in socket
programming must know two information:
1. IPaddress of Server, and
2. Port number.
Socket class:
A socket is simply an endpoint for communications between the machines. The Socket
class can be used to create a socket.
ServerSocket class:
The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.
}catch(Exception e){System.out.println(e);}
}
}
To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.
URL class:
The URL class represents a 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/sonoojaiswal/index.jsp
A URL contains many informations:
File Name or directory name: In this case, index.jsp is the file name.
URLConnection class:
The 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:
public URLConnection openConnection()throws IOException{}
}
InetAddress class:
The java.net.InetAddress class represents an IP address. The Inet Address class provides
methods to get the IP of any host name.
DatagramPacket class:
The DatagramPacket is message that can be sent or received. If you send multiple
packet, it may arrive in any order. Moreover, packet delivery is not guaranteed.
Container:
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container.
Window:
The window is the container that have no borders and menubars. You must use frame,
dialog or another window for creating a window.
Panel:
The Panel is the container that doesn't contain title bar and MenuBars. It can have other
components like button, textfield etc.
Frame:
The Frame is the container that contain title bar and can have MenuBars. It can have
other components like button, textfield etc.
Creating a Frame:
There are two ways to create a frame:
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout now bydefault BorderLayout
setVisible(true);//now frame willbe visible, bydefault not visible
}
public static void main(String args[]){
First f=new First();
}
}
Listener Interfaces
ActionEvent
ActionListener
MouseEvent
MouseWheelEvent
MouseWheelListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
AdjustmentEvent
AdjustmentListener
WindowEvent
WindowListener
ComponentEvent
ComponentListener
ContainerEvent
ContainerListener
FocusEvent
FocusListener
For registering the component with the Listener, many classes provide the registration
methods. For example:
Button
o
MenuItem
o
TextArea
public void addTextListener(TextListener a){}
Checkbox
o
TextField
Choice
o
List
o
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
It is lightweight.
It has more powerful components like tables, lists, scroll panes, color chooser,
tabbed pane etc.
What is JFC ?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
It is lightweight.
It has more powerful components like tables, lists, scroll panes, color chooser,
tabbed pane etc.
What is JFC ?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Do You Know ?
Hierarchy of swing: