JAVA Full Notes
JAVA Full Notes
JAVA Full Notes
[email protected]
What is a class in Java
• Class defines a new data type. Once a class is defined it can be used
to create objects of that type.
• A class is a template for an object and object is an instance of a class.
It is a logical entity.
• Definition: A class is a set of objects that share a common structure
and a common behaviour.
• The properties and actions of the objects are written in the class.
• While defining a class we declare its form and nature by specifying
the data it contains and code that operates on that data.
• A class in Java can contain:
• Fields
• Methods
Syntax
• A class is defined using class keyword
Syntax: class classname{
type instance-variable1;
class class_name type instance-variable2;
{ ...
field; type instance-variableN;
method; type methodname1(parameter-list){
} //body of method
}
type methodname2(parameter-list){
//body of method
}
...
type methodnameN(parameter-list){
//body of method
}
NOTE }
A class declaration only creates a template, it does not create and actual object.
Instance Variable
• The data or variables defined within a class but outside the method
are called instance variables.
• Instance variable doesn't get memory at compile time. It gets
memory at run time when object (instance) is created.
• Each instance (object) of the class contains its own copy of these
variables.
• The data of one object is separate and unique from the data for other.
• Both variables and methods within a class are called members of the
class. Example Class Box{
double width;
double height;
double depth;
}
• To create an object of Box class use the following code:
Creating object of a class:
• Every Box object will contain its own copies of the instance variables
width, height and depth of each instance variable defined by the
class.
• To access the instance variables and methods within an object we
need the dot(.) operator.
Example
mybox.height
Method
• A method is like function used to expose behavior of an object.
Syntax
returnType methodName (parameter list) {
statements ; // Code for definition of the method.
}
Note
When a method uses an instance variable that is defined by its class, it does so directly,
without preceding them with an object name or the dot operator.
Object
• An object is a real-world entity.
• An object is a run time entity.
• The object is an entity which has identity, state and behavior.
• The object is an instance or variable of a class.
An object has three characteristics:
DriverSum.java
Method Overloading with Type Promotion
class Test{
void add(int a){
a++; output
System.out.println(a);
}
void add(float a){ 100
a++; 6.3
System.out.println(a);
}
}
class ABC{
public static void main(String []args){
Test obj=new Test();
obj.add('c’);
obj.add(5.3f);
} ABC.java
}
class Test{
void add(int a,char b){ output
System.out.println(a+b);
} 22.0
void add(int a,double b){
System.out.println(a+b);
}
}
class DriverMain{
public static void main(String []args){
Test obj=new Test();
obj.add(11,11);
DriverMain.java
}
}
Overloading of Constructors
• The static variable can be used to refer to the common property of all
objects (which is unique for each object)
• i.e. the company name of Employee, college name of Student class, etc.
• The static variable gets memory only once in the class area, at the
time of class loading.
• Advantages:
1. It makes your program memory efficient (i.e., it saves memory).
2. It is used to share data between the object.
class Student{
int rollno;
String name;
static String college ="Silicon"; output
Student(int r,String n){
rollno = r; 111 Karan Silicon
name = n; 222 Aryan Silicon
}
void display (){
System.out.println (rollno+" "+name+" "+college);
}
}
class TestStudent{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student (222,"Aryan");
s1.display();
s2.display();
}
}
• Static variable will get memory only once. If any object changes the
value of static variable, it will retain its value.
class Counter{
static int count=0;//will get memory only once and retain its value
Counter(){
count++;
System.out.println(count);
} output
public static void main(String args[]){ 1
Counter c1=new Counter(); 2
Counter c2=new Counter(); 3
Counter c3=new Counter();
}
}
What will be the output?
class Test {
static int x = 10;
Option
public static void main(String[] args) {
Test t1 = new Test(); A) 10 10
Test t2 = new Test(); B) 20 20
t1.x = 20; C) 10 20
System.out.print(t1.x + " "); D) 20 10
System.out.println(t2.x);
}
}
Static Methods
• we can make method as static.
• Static method belongs to class rather than object of a class
• static methods can be invoked without creating any instance of the
class
• it can be called by class name ( i.e. Test.fun() )
• NOTE All the methods in Math class are static, so they are
independent of specific instance.
Rules
• Methods declare static have several restriction
1. Static method can directly access static data member and can change value
of it.
2. Static method can not call non static method directly. It can call static
method only.
• A non static method can call both static and non static method
class Student{
int rollno; String name;
static String college ="Silicon";
Student(int r,String n){
rollno = r; name = n; output
}
static void change(){ 111 Karan Silicon
college = "SIT"; 222 Aryan Silicon
} 111 Karan SIT
void display (){ 222 Aryan SIT
System.out.println(rollno+" "+name+" "+college);
}
}
class TestStudent{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display(); s2.display();
Student.change();
s1.display(); s2.display();
}
}
static block
• It is used to initialize static variables. The static block executed exactly
once when the class is loaded in the main memory.
• The code inside static block is executed only once, the first time you
make an object of the class or first time you access static member of
the class.
• JVM executed before main method at the time of class loading
• Syntax:
static{
list of statements...
}
class Example
{
static int num;
static String mystr;
static output
{
num = 97; Value of num: 97
mystr = "Static keyword in Java"; Value of mystr: Static
keyword in Java
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
• A class can have any number of static blocks
• static blocks are called inorder they appear in the source code.
What will be the output ?
class Test {
static{
int y = 100;
System.out.println("static block y= " + y);
}
public static void main(String[] args) {
int x = 300;
System.out.println(x);
}
static{
int x = 200;
System.out.println("static block x= " + x);
}
}
class Example2
{
static int num;
static String mystr;
static
{
System.out.println("Static Block 1"); output
num = 68;
mystr = "Block1"; Static Block 1
} Static Block 2
static Value of num: 98
{ Value of mystr: Block2
System.out.println("Static Block 2");
num = 98;
mystr = "Block2";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
this keyword
• ‘this’ is a reference variable that refers to the currently invoking
object.
class A5 output
{
void m() A5@15db9742
{ A5@15db9742
System.out.println(this);//prints same reference ID
}
public static void main(String args[])
{
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
• Important uses of this keyword.
1. this keyword can be used to refer current class instance
variables.
• this keyword is used to access the instance variable inside a
function, when local variable name is same as instance
variable name.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this: to pass as argument in the constructor call
6. this keyword can be used to return current class instance
this keyword can be used to refer current class instance variables.
class Student{
int rollno; String name; float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno; output
this.name=name;
this.fee=fee; 111 ankit 5000
} 112 sumit 6000
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
this: to invoke current class method
• You may invoke the method of the current class by using the this
keyword. If you don't use the this keyword, compiler automatically
adds this keyword while invoking the method. Let's see the example.
class A{
void m(){
System.out.println("hello m");
}
void n(){
System.out.println("hello n");
this.m(); //m();//same as this.m()
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
this(): to invoke current class constructor
• this() can be used to invoke current class constructor
• It is used to reuse constructor
• It is used for constructor chaining
• this() constructor call should be used to reuse the constructor from
the constructor.
• NOTE: Call to this() must be the first statement in constructor.
Otherwise java shows compile time error.
this can be used to invoke current class constructor.
class Example{
int x,y;
Example(){
x =0; y =0;
this(5,10);
}
Example(int a, int b){
x =a; y = b;
}
void display()
{
Sop(x + “ “ + y);
}
}
class TestExample{
public static void main(String args[]){ Calling Parameterized constructor from default
Example ob=new Example(); constructor.
ob.display();
}
}
class Student{
int rollno; String name,course; float fee;
Student(int rollno,String name,String course){
this.rollno=rollno; this.name=name; this.course=course;
}
Student(int rollno,String name,String course,float fee) {
this(rollno,name,course);//reusing constructor
this.fee=fee; output
}
void display() 111 ankit java null
{ 112 sumit java 6000
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display(); s2.display();
}
}
this can be passed as an argument in the method call.
class Example{
int x,y;
Example(){ class TestExample{
this(5,10); public static void main(String args[]){
} Example ob=new Example();
Example(int a, int b){ display(ob);
x =a; y = b; ob.modify();
} }
display(Example ob) { }
Sop(ob.x + “ “ + ob.y);
}
void modify(){
x = x +10;
display(this);
}
}
The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling.
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
this: to pass as argument in the constructor call
• We can pass the this keyword in the constructor also. It is useful if we
have to use one object in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this); b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
this keyword can be used to return current class
instance
• We can return this keyword as a statement from the method. In such
case, return type of the method must be the class type). Let's see the
example: Syntax:
class A{ return_type method_name(){
A getA(){ return this;
return this; }
}
void msg(){
System.out.println("Hello java"); output
}
} Hello Java
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Access Specifier
• The access specifier in java specifies accessibility (scope) of a data member,
method, constructor or class.
• It is a keyword that specifies how to access the member of a class or class
itself.
• There are 4 types of access specifier in java
1. public: public member of a class are accessible everywhere including outside the
class. Classes, methods, and fields declared as public can be accessed from any
class in the Java program, whether these classes are in the same package or in
another package. Any other program can read and use them Achieves highest
level of accessibility.
2. private: private member of a class are not accessible anywhere outside the class.
They are only accessible only within the class by the method of that class
3. default: If no access specifier is specified by the programmer, then java compiler
uses default access specifier. Default member are accessible outside the class but
within the same directory.
4. protected: protected members of a class are accessible outside the class, but
generally within the same directory. (will discuss in inheritance chapter)
class Person {
private String name = “Raju”;
private int age = 30;
void talk() {
System.out.println(name + “ “ + age);
}
}
Class TestPerson{
public static void main(String [] args) {
Person ob = new Person();
ob.talk();
ob.name = “xyz”;
}
}
class Hello {
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
class Demo {
public static void main(String args[]) {
Hello obj=new Hello();
System.out.println(obj.a); //Compile Error, you can't access private data here
obj.show();//Compile Time Error, you can't access private methods here
}
}
Inheritance
Inheritance
• Inheritance is a process in which object of one class can acquire the properties of
object of another class.
• The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes.
• When you inherit from an existing class, you can reuse methods and data
members of the parent class. You can also add new methods and fields in your
current class also.
• Objective: Inheritance supports the concept of “code re-usability”
• i.e when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class from
the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Advantages of using Inheritance
1. Code reusability
2. Cost cutting
3. reduce redundancy
Terms used in Inheritance
}
class DriverCar{
public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object
myCar.display(); // Call the display() method (from the Vehicle class) on the myCar
object
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Types of inheritance in java
Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
Method overloading is a compile time Method overriding is a run time polymorphism.
polymorphism.
Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
In method overloading ,return type can or Return type must be same or covariant in
cannot be same, but we must have to change method overriding.
the parameter
Here, methods must have same name but While in this, methods must have same name
different signature. and same signature.
Static Binding Vs Dynamic Binding
• Static/Early Binding: The binding which can be resolved at compile
time by compiler is known as static or early binding. Binding of all the
static, private and final methods is done at compile-time .
• Why binding of static, final and private methods is always a static
binding?
• Static binding is better performance wise (no extra overhead is required).
Compiler knows that all such methods cannot be overridden and will always
be accessed by object of local class. Hence compiler doesn’t have any
difficulty to determine object of class (local class for sure). That’s the reason
binding for such methods is static.
Dynamic/Late Binding
• In Dynamic binding compiler doesn’t decide the method to be called. Overriding
is a perfect example of dynamic binding. Binding is done at run time.
classABC{
void print() { class Test{
SOP("print in superclass."); public static void main(String args[]){
} ABC ob = new XYZ( );
} ob.print();
class XYZ extends ABC{ }
void print() { }
SOP("print in superclass.");
}
}
Dynamic Method Dispatch
• Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.
• Through Dynamic method dispatch Java implements run-time polymorphism.
• A superclass reference variable can refer to a subclass object. Java uses this fact
to resolve calls to overridden methods at runtime.
• When an overridden method is called through the reference variable of a
superclass, Java determines which version of that method to execute based
upon the type of the object being referred to at the time the call occurs.
• The type of the object being referred to (not the type of the reference variable)
that determines which version of an overridden method will be executed.
• if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable,
different versions of the method are executed.
class Animal { //Driver Class...
public void move() { public class TestDog {
SOP("Animals can move");
public static void main(String args[]) {
}
// Animal reference and object
} Animal a = new Animal();
class Dog extends Animal { // Animal reference but Dog object
public void move() { Animal b = new Dog();
SOP("Dogs can walk and run"); a.move();//call method of Animal class
b.move();// call method in Dog class
}
}
} }
Output:
output
Inside A's callme method
Inside B's callme method
Inside C's callme method
Upcasting
• Substituting a subclass instance for its superclass is called upcasting.
• The compiler checks for valid upcasting and issues error "incompatible
types" otherwise.
• Upcasting is always safe because a subclass instance possesses all the
properties of its superclass and can do whatever its superclass can do.
class parent{
void display(){
System.out.println("Parent class Method");
}
}
class child extends parent{ Output
void display(){ Child class Method
System.out.println("Child class Method"); Parent class Method
}
}
class Upcasting{
public static void main(String args[]){
parent ob = new child();
ob.display();
parent ob1 = new parent();
ob1.display();
}
}
Final keyword
• The java final keyword can be used in many context.
• Following are different contexts where final is used.
• final variable ( used create a constant variable )
• final method ( Prevent method overriding )
• final class ( Prevent inheritance )
Final Variables
• If you make any variable as final, you cannot change the value of final variable (It
will be constant).
• final variables must be used only for the values that we want to remain constant
throughout the execution of program.
• Example:
• final int THRESHOLD = 5;
• static final double PI = 3.14159;
• It is good practice to represent final variables in all uppercase, using underscore
to separate words.
• We must initialize a final variable, otherwise compiler will throw compile-time error. A
final variable can only be initialized once, either via an initializer or an assignment
statement.
• There are three ways to initialize a final variable :
1. You can initialize a final variable when it is declared.
2. If it is not initialized while declaration( blank final variable).There are two ways to
initialize a blank final variable.
• A blank final variable can be initialized inside instance-initializer block or
initialized inside constructor. If you have more than one constructor in your
class then it must be initialized in all of them, otherwise compile time error will
be thrown.
• A blank final static variable can be initialized inside static block.
• A final variable can be assigned value later, but only once
class FinalDemo{
final int THRESHOLD = 5; // a final variable direct initialize
final int CAPACITY; // a blank final variable
final int MINIMUM; // another blank final variable
static final double PI = 3.141592653589793; // a final static
variable PI
static final double EULERCONSTANT; // a blank final static
variable
// instance initializer block for initializing CAPACITY
{
CAPACITY = 25;
}
// static initializer block for initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3; class Test{
} public static void main(String []args){
// constructor for initializing final variable FinalDemo obj=new FinalDemo();
FinalDemo() { SOP("CAPACITY= "+obj.CAPACITY);
MINIMUM = -1; SOP("EULERCONSTANT= "+obj.EULERCONSTANT);
} SOP("MINIMUM= "+obj.MINIMUM);
} }
}
• A variable can be final and static.
• example:
• final static collegeName=”Silicon”
• The blank final variable can be static, which can be initialized in the static block.
• When a final variable is created inside a method/constructor/block, it is called
local final variable, and it must initialize once where it is created.
class FD{
public static void main(String args[]) {
// local final variable
final int i;
i = 20;
System.out.println(i);
}
}
Final Method
• When a method is declared with final keyword, it is called a final
method.
• A final method cannot be overridden.
• We must declare methods with final keyword for which we required
to follow the same implementation throughout all the derived
classes.
• Since final methods cannot be overridden, a call to one can be
resolved at compile time. This is called early binding. In this way final
provides a performance enhancement.
class Bike {
final void r1() {
System.out.println("running");
}
}
class Honda extends Bike {
output
void r1() { // error since final methods can not be overridden
System.out.println("running safely with 100kmph");
ERROR
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.r1();
}
}
Final class
• When a class is declared as final then it cannot be subclassed i.e. no any other
class can extend it.
• This is particularly useful for creating an immutable class like the predefined
String class.
• Declaring a class as final implicitly declares all of its methods as final too.
• It is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete
implementations. final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Object class
• Object is a special class in java which is the parent/ super class of all
the classes in java by default. In other words, it is the topmost class
of java.
• This means that a reference variable of type Object can refer to an
object of any other class.
• The Object class provides some common behaviors to all the objects
Object class defines the following methods, which means that they are available in every
object:
Example of toString()
class A {
A() {
System.out.println("Constructed A");
}
public String toString() {
return "This is A";
}
}
class B extends A {
B() {
super();
System.out.println("Constructed B");
}
public String toString() {
return "This is B";
}
}
class C extends B {
C() {
super();
System.out.println("Constructed C");
}
public String toString() {
return "This is C";
}
}
1. When it is declared as public, the interface can be used by any other code. In this case, the interface must be
the only public interface declared in the file, and the file must have the same name as the interface.
2. Each class that includes an interface must implement all of the methods.
3. Variables can be declared inside of interface declarations. They are implicitly final and static, meaning they
cannot be changed by the implementing class. They must also be initialized. All methods and variables are
implicitly public.
Implementing Interface
• Keywords : implements
• To implement an interface, include the implements clause in a class definition,
and then override the methods defined by the interface.
class classname extends superclass implements interface1 ,interface2, ...
{
// class-body
}
• If a class implements more than one interface, the interfaces are separated with a
comma.
• If a class implements two interfaces that declare the same method, then the
same method will be used by clients of either interface.
• The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature
specified in the interface definition.
Example-1
interface Callback {
void callback(int param);
}
class Client implements Callback
{ NOTE: When you implement an
// Implement Callback's interface interface method, it must be declared
public void callback(int p) { as public.
System.out.println("callback called with " + p);
}
}
class Test {
psvm(String args [] ){
client c = new Client();
c.callback(20);
}
}
interface Shape {
double getArea();
}
class Rectangle implements Shape {
private int length;
private int width;
Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public String toString() {
return "Rectangle[length=" + length + ",width=" + width + "]";
}
public double getArea() {
return length * width;
}
}
class Triangle implements Shape {
private int base;
private int height;
Triangle(int base, int height) {
this.base = base;
this.height = height;
}
public String toString() {
return "Triangle[base=" + base + ",height=" + height + "]";
} Rectangle[length=1,width=2]
public double getArea() { Area is 2.0
return 0.5 * base * height; Triangle[base=3,height=4]
} Area is 6.0
}
class TestShape {
public static void main(String[] args) {
Shape s;
s = new Rectangle(1, 2); // upcast
System.out.println(s);
System.out.println("Area is " + s.getArea());
s = new Triangle(3, 4); // upcast
System.out.println(s);
System.out.println("Area is " + s.getArea());
//Shape s3 = new Shape("green"); // Compilation Error!!
}
}
• It is permissible for classes that implement interfaces to define
additional members of their own.
• It is possible to create a reference variable of type interface. Any
instance of any class that implements the declared interface can be
referred to by such a variable.
• When you call a method through one of these references, the correct
version will be called based on the actual instance of the interface being
referred to.
• The method to be executed is looked up dynamically at run time.
• Dynamic lookup of a method at run time incurs a significant overhead
when compared with the normal method invocation in Java
interface Callback {
void callback(int param); output
}
callback called with 42
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
Note: In the above program although ‘c’ is
void example(){
System.out.println("Inside Example"); used to access the callback() method, it
} cannot access any other members of the
} Client class. An interface reference variable
class TestIface { only has knowledge of the methods
public static void main(String args[]) { declared by its interface declaration.
Callback c = new Client();
c.callback(42);
//c.example();
}
}
class AnotherClient implements Callback
{
// Implement Callback's interface output
public void callback(int p) {
callback called with 42
System.out.println("Another version of callback");
Another version of callback
System.out.println("p squared is " + (p*p)); p squared is 1764
}
}
class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient(); Note: As you can see, the version of
c.callback(42); callback( ) that is called is determined by
c = ob; // c now refers to AnotherClient object the type of object that c refers to at run
c.callback(42); time.
}
}
Partial Implementation
• If a class includes an interface but does not fully implement the
methods defined by that interface, then that class must be declared as
abstract.
abstract class Incomplete implements Callback {
int a, b; Note: The class Incomplete does not
void show() { implement callback( ) and must be declared
System.out.println(a + " " + b); as abstract. Any class that inherits the class
} Incomplete must implement callback( ) or be
// ... declared abstract itself.
}
Nested Interface
• An interface can be declared a member of a class or another
interface. Such an interface is called a member interface or a nested
interface.
• A nested interface can be declared as public, private, or protected.
This differs from a top-level interface, which must either be declared
as public or use the default access level.
• When a nested interface is used outside of its enclosing scope, it
must be qualified by the name of the class or interface of which it is
a member.
class A {
interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
output
public boolean isNotNegative(int x) {
return x < 0 ? false : true; 10 is not negative
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
A.NestedIF nif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}
• We can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired
values. When you include that interface in a class, all of those variable names
will be in scope as constants.
Extending Interface
• One interface can inherit another by using the keyword extends. The
syntax is the same as for inheriting classes.
• When a class implements an interface that inherits another
interface, it must provide implementations for all methods defined
within the interface inheritance chain.
interface A {
void meth1();
void meth2();
}
interface B extends A {
void meth3();
}
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1(); ob.meth2(); ob.meth3();
}
}
Default interface Method
• Before Java 8, interfaces could have only abstract methods .
• The implementation of these methods has to be provided in a
separate class. So, if a new method is to be added in an interface then
its implementation code has to be provided in the class implementing
the same interface.
• To overcome this issue, Java 8 has introduced the concept of default
methods which allow the interfaces to have methods with
implementation without affecting the classes that implement the
interface.
interface TestInterface {
// abstract method
public void square(int a);
// default method
default void show() {
System.out.println("Default Method Executed");
}
}
class TestClass implements TestInterface {
// implementation of square abstract method
public void square(int a) {
System.out.println(a*a);
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.square(4);
d.show();// default method executed
}
}
static method in interface
• JDK 8 added another new capability to interface: the ability to define one or
more static methods. Like static methods in a class, a static method defined by
an interface can be called independently of an object.
• Syntax of calling a static method: InterfaceName.staticMethodName
interface TestInterface {
// abstract method
public void square (int a);
// static method
static void show() {
System.out.println("Static Method Executed");
}
}
class TestClass implements TestInterface {
public void square (int a) {
System.out.println(a*a);
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.square(4);
// Static method executed
TestInterface.show();
}
}
Packages
• A java package is a group of similar types of classes, interfaces and
sub-packages.
• Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces.
• Package in java can be categorized in two form, built-in package and
user-defined package.
• We should put related classes into packages.
• There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Advantage of java package
• Java package removes naming collision.
• Example: We can be two classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee.
• For example there can be two classes with same name in two packages.
• Making searching/locating and usage of classes, interfaces are easier
• Java package provides access protection: protected and default have package
level access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access specifier) is
accessible by classes in the same package only.
• Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
• Packages can be considered as data encapsulation (or data-hiding).
Defining Packages
• To create 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.
• The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default package, which has no
name.
• This is the general form of the package statement:
Syntax: package pkgName;
Example: package MyPackage;
• Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.
• More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong.
• We can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled package
statement is shown here: package pkg1.pkg2.pkg3;
Steps to create a Java package
• Come up with a package name
• Pick up a base directory
• Make a subdirectory from the base directory that matches your package name.
• Place your source java files into the package subdirectory.
• Use the package statement in each source file.
• Compile your source files from the base directory.
• Run your program from the base directory.
Cont….
• Step1: Make a subdirectory from the base directory that matches your package
name.
• Step2: Define a class in a java file say A.java and include the first instruction as
package package-name;
package myPkg;
public class A{
……
A.java
…..
}
• Save this file under the directory myPkg, which is the subdirectory of base
directory
Cont….
• Step3: Compile the A.java File( Objective is to place the A.class file
inside the package myPkg)
• Step4:Create the source file under the base directory
(say pp.java)
• Step5: Import the package myPkg.A inside the file(pp.java)
• Step6: Compile and execute the source file
Easy Way to Run: The easiest way to run a program having package is to simply create
the package directories below your current development directory, put the .class files
into the appropriate directories, and then execute the programs from the development
directory.
package MyPack;
class Balance {
String name; double bal;
Balance(String n, double b) {
name = n;
Compile the program under the current directory
bal = b;
in normal way. Create a directory with the name
}
MyPack. Keep the .class files (both Balance.class
void show() {
and AccountBalance.class) of this program under
if(bal<0)
the folder MyPack. Run the program using
System.out.print("--> ");
command java MyPack.AccountBalance by staying
System.out.println(name + ": $" + bal);
just above MyPack folder.
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
output
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33); K. J. Fielding: $123.23
for(int i=0; i<3; i++) Will Tell: $157.02
current[i].show(); --> Tom Jackson: $-12.33
}
}
Access package from another package?
• There are three standard ways to access the package from outside the package.
• import package.*;
• import package.classname;
import myPkg.subPkg.MyClass;
class Driver{
public static void main(String args[]){
MyClass ob=new MyClass();
ob.fun();
}
}
Note
1. Every class is part of some package.
2. If no package is specified, the classes in the file goes into a special unnamed package (the same
unnamed package for all files).
3. All classes/interfaces in a file are part of the same package. Multiple files can specify the same
package name.
4. If package name is specified, the file must be in a subdirectory called name (i.e., the directory
name must match the package name).
5. We can access public classes in another (named) package using: package-name.class-name.
Exception Handling
Dr. Kasturi Dhal
Department of CSE
Silicon Institute of Technology
[email protected]
Error
• While we are solving any problem, we generally come across the following three
types of error.
1. Syntax Error : During compilation
2. Runtime Error : It occurs at run time ( i.e. Input error )
3. Logic Error: Poor understanding of the problem.
Exception
• Exception is a run time error, which arises during the execution of program.
• When an exception occurs the normal flow of the program is interrupted and the
program is terminate abnormally.
• Exception can occur in many different reasons:
1. User entered invalid data
2. File not found
3. Network connection has been lost
4. JVM has run out of memory
• An exception is an unwanted or unexpected event, which occurs during the execution of
a program i.e. at run time, which disrupts the normal flow of the program’s instructions.
• A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
Exception Handling
• The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors such as ClassNotFound, IO, SQL, Remote etc.
• so that the normal flow of the application can be maintained.
• Advantage of exception handling is to maintain normal flow of application.
• Example: Suppose there are 5 statements in a program and there occurs an
exception at statement number 3, rest of the code will not be executed i.e.
statement 4, 5 will not run. If we perform exception handling, rest of the
statement will be executed. That is why we use exception handling in java.
• All exception types are subclasses of the built-in class Throwable.
• Below Throwable there are two subclasses that partition exceptions into two distinct
branches. One branch is headed by Exception.
• This class is used for exceptional conditions that user programs should catch. This is also
the class that you will subclass to create your own custom exception types.
• One of the important subclass of Exception, called Runtime Exception. Exceptions of this
type are automatically defined for the programs that you write and include things such
as division by zero and invalid array indexing etc.
• The other branch (of Throwable) is topped by Error, which defines exceptions that are
not expected to be caught under normal circumstances by your program. Exceptions of
type Error are used by the Java run-time system to indicate errors having to do with the
run-time environment, itself. Stack overflow is an example of such an error.
All exception classes are subtypes of the
java.lang.Exception class.
The exception class is a subclass of the
Throwable class.
Other than the exception class there is
another subclass called Error which is
derived from the Throwable class. Errors
are abnormal conditions that happen in
case of severe failures, these are not
handled by the java programs. Errors are
generated to indicate errors generated by
the runtime environment.
The Exception class has two main
subclasses: IOException class and
RuntimeException Class.
Exception describes errors caused by your program
and external circumstances. These errors can be Runtime Exception is caused by
caught programming errors, such as bad
and handled by your program. casting, accessing an out-of-bounds
• When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception.
• This causes the execution to stop, because once an exception has been thrown, it must be caught
by an exception handler and dealt with immediately.
• As we have not supplied any exception handlers of our own, so the exception is caught by the
default handler provided by the Java run-time system.
• Any exception that is not caught by your program will ultimately be processed by the default
handler. The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program.
Using try and catch
The user should handle his/her exceptions because of two reasons:
o it allows you to fix the error.
o it prevents the program from automatically terminating.
class Test{
public static void main(String []args){
int d,a; output
try {
Division by zero.
d=0;
After catch statement.
a=20/d;
}
catch(ArithmeticException ob){
System.out.println(“Divided by zero”);
}
System.out.println(“After catch exception block”);
}
}
• Enclose the code that you want to monitor inside a try block.
• Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
• Once an exception is thrown, program control transfers out of the try block into
the catch block.
• Once the catch statement has executed, program control continues with the next
line in the program following the entire try/catch block.
• A try and its catch statement form a unit.
• A catch statement cannot catch an exception thrown by another try statement
(except in the case of nested try statements).
• The statements that are protected by try must be surrounded by curly braces.
• The goal of most well-constructed catch clauses should be to resolve the
exceptional condition and then continue on as if the error had never happened.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Multiple Catch clause
• In some cases, more than one exception could be raised by a single piece of code.
• To handle this type of situation, we can specify two or more catch clauses, each catching a
different type of exception.
• A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
• When an exception is thrown, each catch statement is inspected in order, and the first one whose
type matches that of the exception is executed.
• After one catch statement executes, the others are bypassed, and execution continues after the
try/catch block.
• When you use multiple catch statements, it is important to remember that exception subclasses
must come before any of their superclasses. Otherwise a catch statement that uses a superclass
will catch exceptions of that type plus any of its subclasses.
• Thus, a subclass would never be reached if it came after its superclass. In that case Java will show
error since unreachable code is an error in Java.
• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
ArrayIndexOutOfBounds Exception occurs rest of the code
class Test{
public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
FileReader() method which throws a checked exception FileNotFoundException. It also uses readLine()
and close() methods, and these methods also throw checked exception IOException.
Checked Exception in java.lang
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class
or interface.
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Unchecked Exception
• These exceptions are not checked at compiled time but they are checked at
runtime.
• The classes which inherit RuntimeException are known as unchecked exceptions
e.g.ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.
• In Java exceptions under Error and RuntimeException classes are unchecked
exceptions, everything else under Throwable is checked.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Unchecked Exception in java.lang
Creating your own Exception
• To create the custom exception , it must be derived from Exception class
• If we want to create our own exception types to handle situations specific to our
applications, we need to just define a subclass of Exception (which is, of course, a
subclass of Throwable).
• All exceptions, including those that we create, have methods defined by
Throwable available to them.
Creating your own Exception
class MyException extends Exception {
public MyException(String s) {
// Call constructor of parent Exception
super(s);
}
}
Multiprocessing MultiThreading
Process are heavy weight task Thread are light weight task
Each process has own address Threads are executed under
space, so they do not share the the address space of the
address space process
Context switching between the Context switching between the
process are slow threads are faster
IPC is required to communicate No IPC is required to
between the process communicate between the
threads
Multithreading in Java
• Multithreading in java is a process of executing multiple threads simultaneously.
• Java provides built-in support for multithreaded programming.
• A multithreaded program contains two or more parts (thread) that can run
concurrently.
• Multithreading is a specialized form of multitasking.
• Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
• In a singled-threaded environment, when a thread blocks (that is, suspends execution)
because it is waiting for some resource, the entire program stops running.
• The benefit of Java’s multithreading is that one thread can pause without stopping other
parts of your program. For example, Multithreading allows animation loops to sleep for
a second between each frame without causing the whole system to pause.
Life Cycle of a Thread(Thread State)
• A thread can be running. It can be ready to run as soon as it gets CPU time.
• A running thread can be suspended, which temporarily suspends its activity.
• A suspended thread can then be resumed, allowing it to pick up where it left off.
• A thread can be blocked when waiting for a resource.
• At any time, a thread can be terminated, which halts its execution immediately. Once terminated,
a thread cannot be resumed.
• In java a thread exists in any one of the following state
1. New
2. Runnable
3. Running
4. Blocked:
5. Dead /Terminated.
1. New state: The thread is in new state if you create an instance of Thread class
but before the invocation of start() method. At this State, we can do by using
start() method. Whenever a new thread is created, it is always in the new state.
For a thread in the new state, the code has not been run yet and thus has not
begun its execution.
• Active :When a thread invokes the start() method, it moves from the new state to
the active state. The active state contains two states within it: one is runnable,
and the other is running.
2. Runnable state: It means that the thread is ready for execution and it is waiting
for the availability of the processor. The thread is in runnable state after
invocation of start() method, but the thread scheduler has not selected it to be
the running thread. It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread to the running state.
3. Running state : The thread is in running state if the thread scheduler has
selected it. When the thread gets the CPU, it moves from the runnable to the
running state. It means that the processor has given its time to the thread for its
execution. The thread runs until it relinquishes control on its own or it is
preempted by a higher priority thread.
4. Blocked state :In this state the thread is temporarily inactive, but the thread is
alive. This is the state when the thread is still alive, but is currently not eligible
to run.
5. Dead state :A running thread ends its life when it has completed executing its
run() method. It is a natural death. We can kill the thread by using stop()
method. A thread reaches the termination state because of the following
reasons:
• When a thread has finished its job, then it exists or terminates normally.
• Abnormal termination: It occurs when some unusual events such as an unhandled exception
or segmentation fault.
Java Thread Class
• Java’s multithreading system is built upon the Thread class, its methods, and
interface, Runnable.
• To create a new thread, your program should either extend Thread class or
implement the Runnable interface.
• Java provides Thread class to achieve thread programming. Thread class
provides Constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
• The Thread class defines several methods that help manage threads.
Commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
• public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user
thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been
interrupted.
Creating a Thread
• We can create a thread either by:
1. Implementing the Runnable interface or by
2. Extending the Thread class
• Commonly used Constructors of Thread class
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r, String name)
• The start() method of Thread class is used to start a newly created
thread. It performs the following tasks:
1. A new thread starts(with new callstack).
2. The thread moves from New state to the Runnable state.
3. When the thread gets a chance to execute, its target run() method will run.
Implementing 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().
• To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
• public void run( ) : is used to perform action for a thread.
• Inside run( ), we will define the code that constitutes the new thread.
• The run( ) establishes the entry point for another, concurrent thread of execution within our
program. This thread will end when run( ) returns.
• Once you create a class that implements Runnable, you will instantiate an object of type Thread
from within that class
• Thread defines several constructors. The used one has the following signature:
• Thread(Runnable threadOb, String threadName)
• In this constructor, threadOb is an instance of a class that implements the Runnable
interface.
• This defines where execution of the thread will begin. 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. In essence, start( ) executes a call to run( ).
• The start( ) method is shown here:
• void start( )
class Multi3 implements Runnable{
public void run(){
SOP("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
thread is running...
If you are not extending the Thread class, your class object would not be treated as a
thread object.
Need to explicitly create the Thread class object. We are passing the object of your
class that implements Runnable so that your class run() method may execute.
public class MyThread2 implements Runnable {
public void run() {
System.out.println("Now the thread is running ...");
}
public static void main(String argvs[]) {
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}
}
My new thread
Using the Constructor Thread(Runnable r, String name) Now the thread is running ...
Extending a Thread class
• We can create a thread by creating a new class that extends Thread,
and then to create an instance of that class.
• The extending class must override the run( ) method, which is the
entry point for the new thread.
• It must also call start( ) to begin execution of the new thread.
class Multi3 extends Thread{
public void run(){
SOP("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
t1.start();
}
}
thread is running...
My first thread
My first thread
public class MyThread1 {
public static void main(String args[]) {
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
My first thread
} Thread-1 2
}
} Thread-0 2
class BTest {
public static void main(String args[]) { Thread-1 3
System.out.println(Thread.currentThread().getName());
A a1=new A();
Thread t1=new Thread(a1); Thread-0 3
Thread t2=new Thread(a1);
t1.start(); Thread-1 4
t2.start();
} Thread-0 4
}
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500);
1
}
1
catch(InterruptedException e){
2
System.out.println(e);
2
}
3
System.out.println(i);
3
}
4
}
4
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
At a time only one thread is executed. If you sleep a thread for the specified time, the thread scheduler picks up
another thread and so on.
getName(): To get the name of the thread
class MyThread extends Thread {
public void run() {
System.out.println("hello");
}
} Main thread starts
public class NewThread { Name of t1:Thread-2
public static void main(String[] args){ Name of t2:Thread-3
System.out.println("Main thread starts"); Main thread is finished
MyThread r1 = new MyThread(); hello
MyThread r2=new MyThread(); hello
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
System.out.println("Main thread is finished");
}
}
Change the Thread Name using Constructor
class MyThread extends Thread {
public void run() {
System.out.println("hello");
System.out.println(Thread.currentThread().getName());
}
} Main thread starts
public class NewThread { Main thread is finished
public static void main(String[] args){ hello
System.out.println("Main thread starts"); gopal
MyThread r1 = new MyThread(); hello
MyThread r2=new MyThread(); ram
Thread t1 = new Thread(r1,"ram");
Thread t2 = new Thread(r2,"gopal");
// System.out.println("Name of t1:"+t1.getName());
//System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
System.out.println("Main thread is finished");
}
}
Run Method for different Thread
class MyThread1 extends Thread {
public void run() {
System.out.println("First thread");
System.out.println(Thread.currentThread().getName());
}
} Main thread starts
class MyThread2 extends Thread { Main thread is finished
public void run() { First thread
System.out.println("Second Thread"); Second Thread
System.out.println(Thread.currentThread().getName());
ram
}
} ssgopal
class NewThread {
public static void main(String[] args){
System.out.println("Main thread starts");
MyThread1 r1 = new MyThread1();
MyThread2 r2=new MyThread2();
Thread t1 = new Thread(r1,"ram");
Thread t2 = new Thread(r2,"gopal");
t1.start();
t2.start();
System.out.println("Main thread is finished");
}
}
Different Task to same Thread
class Thread1 implements Runnable {
public void run()
{
System.out.println("first thread is running");
f1();
f2();
}
void f1() first thread is running
{ 5
System.out.println(2+3); 20
}
void f2()
{
System.out.println(5*4);
}
}
class NewThread1
{
public static void main(String args[])
{ Thread1 a1=new Thread1();
Thread t1=new Thread(a1);
t1.start();
}
}
The join() method
• It is a method of java.lang.Thread class that permits one thread to
wait until the other thread to finish its execution.
• Suppose th be the object the class Thread whose thread is doing its
execution currently, then the th.join(); statement ensures that th is
finished before the program does the execution of the next
statement.
• The join() method waits for a thread to die. In other words, it causes
the currently running threads to stop executing until the thread it
joins with completes its task.
• Syntax:
• public void join()throws InterruptedException
• public void join(long milliseconds)throws InterruptedException
class MyThread extends Thread{ class Driver{
public void run(){ psvm(String args[]){
for(int i=1;i<=4;i++){ MyThread t1=new MyThread();
try{ MyThread t2 = new MyThread();
Thread.sleep(500); MyThread t3 = new MyThread();
} t1.start();
catch(InterruptedException e){ try{
System.out.println(e); t1.join();
} }
SOP("Childthread: "+ i); catch(Exception e){
} System.out.println(e);
} }
} t2.start();
try{
Childthread: 1 t2.join();
Childthread: 2 }
Childthread: 3
Childthread: 4 catch(Exception e){
Childthread: 1 System.out.println(e);
Childthread: 2 }
Childthread: 3
Childthread: 4
t3.start();
Childthread: 1 }
Childthread: 2 }
Childthread: 3
Childthread: 4
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
1
}
catch(Exception e){
2
System.out.println(e); 3
} 4
System.out.println(i); 5
} 1 when t1 completes its task then t2 and t3
} 1 starts executing.
public static void main(String args[]){ 2
TestJoinMethod1 t1=new TestJoinMethod1();
2
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
3
t1.start(); 3
try{ 4
t1.join(); 4
} 5
catch(Exception e){ 5
System.out.println(e);
}
t2.start();
t3.start();
}
}
String
How to create String object
• In java, string is basically an object that represents sequence of
char values. An array of characters works same as java string
• There are two ways to create String object:
• By string literal
• By new keyword
• String literal: Java String literal is created by using double
quotes.
• For Example: String s = "welcome";
• String literal are anonymous objects of the String class
• 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 is returned. If string doesn't exist in the pool, a
new string instance is created and placed in the pool.
• For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
Note: String objects are stored in a special memory area known as
string constant pool.
By using new keyword
• new Keyword : String s=new String("Welcome");
• It creates two objects and one reference variable
• Such case, JVM will create a new string object in normal(non pool) heap memory
and the literal "Welcome" will be placed in the string constant pool. The variable
s will refer to the object in heap(non pool).
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");
//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Immutability
• Once created, a string cannot be changed: none of its methods
changes the string.
• Such objects are called immutable.
• Immutable objects are convenient because several references can
point to the same object safely: there is no danger of changing an
object through one reference without the others being aware of the
change.
Advantage of Immutability
• An empty String has no characters. It’s length is 0.
• Creating empty string: To create an empty String, we need to call the default
constructor.
• String s = new String();
• String s1 = “”;
• Not the same as an initialized string.
• String Msg; MSG is NULL
• Creating string initialized by an array of characters: To create a String initialized by an
array of characters, use the constructor String(char chars[ ])
• char chars[] = { 'a', 'b', 'c' };
String s = new String(chars); // s is initialized with abc
• Creating string initialized with a subrange of a character array: To create a String,
initialized with a subrange of a character array use the constructor String(char chars[ ],
int startIndex, int numChars)
• char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3); // s is initialized with cde
• Creating string object that contains the same character sequence as
another String object: To create a String object that contains the
same character sequence as another String object use the constructor
String(String strObj)
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c); // s1 is initialized with Java
String s2 = new String(s1); // s2 is initialized with Java
• The java.lang.String class implements Serializable, Comparable and
CharSequence interfaces.
Method –length()
• int length(); : Returns the number of characters in the string
• It is method of String class.
”Problem".length(); Returns 7
String s="Sachin";
s.concat(" Tendulkar");
System.out.println(s); //print Sachin because strings are immutable objects
Now it can be understood by the diagram given. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why string is known as immutable.
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); // prints true
System.out.println((s1 == s2)); // prints false
class Test {
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
SOP(s1==s2); //true (because both refer to same instance)
SOP(s1==s3); //false(because s3 refers to instance created in nonpool)
}
}
True
false
compareTo() method
• int compareTo(String str): This method compares String str with the
invoking String.
• The String class compareTo() method compares values
lexicographically and returns an integer value that describes if first
string is less than, equal to or greater than second string.
• Suppose s1 and s2 are two String objects. If:
• s1 == s2 : The method returns 0.
• s1 > s2 : The method returns a positive value.
• s1 < s2 : The method returns a negative value.
• int diff = word1.compareTo(word2); : returns the “difference” word1 - word2
• int diff = word1.compareToIgnoreCase(word2); : returns the “difference”
word1 - word2, Ignoring the case
Usually programmers don’t care what the numerical “difference” of word1 - word2 is,
just whether the difference is negative (word1 comes before word2), zero (word1 and
word2 are equal) or positive (word1 comes after word2). Often used in conditional
statements.
0
1
-1
Methods — Find (indexOf)
Method: trim()
• The trim() method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed.
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//Prints 3010
• Three ways to convert a number into a string:
1. String s = "" + num;
s = “” + 123;//”123” Integer and Double are “wrapper” classes
2. String s = Integer.toString (i); from java.lang that represent numbers as
objects. They also provide useful static methods.
String s = Double.toString (d);
s= Integer.toString(123);//”123”
s = Double.toString(3.14); //”3.14”
3. String s = String.valueOf (num);
s = String.valueOf(123);//”123”
The output of the following fraction of code is
public class Test{
public static void main(String args[]){
String s1 = new String("Hello");
String s2 = new String("Hellow");
System.out.println(s1 = s2);
}
}
Hellow
class LogicalCompare{
public static void main(String args[]){
String str1 = new String("OKAY");
String str2 = new String(str1);
System.out.println(str1 == str2);
}
}
false
public class Test{
public static void main(String args[]){
String x = "hellow";
int y = 9;
System.out.println(x += y);
}
} hellow9
public class Test{
public static void main(String args[]){
String s1 = "java";
String s2 = "java"; true
System.out.println(s1.equals(s2)); true
System.out.println(s1 == s2);
}
}
How many objects will be created?
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Method
HelloJava
Method
• The replace() method replaces the given String from the
specified beginIndex and endIndex.
class StringBufferExample3{
PSVM(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
SOP(sb);//prints HJavalo
}
}
Method
• The delete() method of the StringBuffer class deletes the String
from the specified beginIndex to endIndex.
class StringBufferExample4{
PSVM(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
SOP(sb);//prints Hlo
}
}
Method
• The reverse() method of the StringBuilder class reverses the
current String.
class Example{
PSVM(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Method
• The capacity() method of the StringBuffer class returns the
current capacity of the buffer.
• The default capacity of the buffer is 16.
• If the number of character increases from its current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if
your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
psvm(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
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
}
}
16
16
34
Method
• The ensureCapacity() method of the StringBuffer class ensures that the given
capacity is the minimum to the current capacity.
• If it is greater than the current capacity, it increases the capacity by
(oldcapacity*2)+2.
• For example if your current capacity is 16, it will be (16*2)+2=34.
class Example{
PSVM(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
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
}
}
16
16
34
34
70
String Builder
• Java StringBuilder class is used to create mutable (modifiable) string.
• The Java StringBuilder class is same as StringBuffer class except that it is non
synchronized.
• It is available since JDK 1.5.
• Constructor:
1. StringBuilder() : creates an empty string Builder with the initial capacity of
16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified
capacity as length.
Commonly Used Method
• public int length(): is used to return the length of the string i.e. total number of
characters.
• public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
• public StringBuilder insert(int offset, String s): is used to insert the specified
string with this string at the specified position.
• The insert() method is overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.
class Example{
PSVM(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
• The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.
class StringBuilderExample3{
PSVM(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
• The reverse() method of StringBuilder class reverses the current string.
class Example{
PSVM(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Difference between StringBuffer and StringBuilder
StringBuffer StringBuilder
StringBuffer is synchronized i.e. thread safe. It StringBuilder is non- synchronized i.e. not
means two threads can‘ t call the methods of thread safe. It means two threads can call
StringBuffer simultaneously. the methods of StringBuilder
simultaneously.
StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than
StringBuffer.
StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
Difference between String and StringBuffer
String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more memory StringBuffer is fast and consumes less
when you concat too many strings because memory when you concat strings.
every time it creates new instance.
String class overrides the equals() method of StringBuffer class doesn't override the
Object class. So you can compare the equals() method of Object class.
contents of two strings by equals() method.
Java Tokenizer
• The java.util.StringTokenizer class allows you to break a String into tokens. It is
simple way to break a String.
• Parsing is the division of text into a set of discrete parts, or tokens
• The StringTokenizer class provides the first step in this parsing process, often
called the lexer (lexical analyzer) or scanner.
• To use StringTokenizer, we specify an input string and a string that contains
delimiters. Delimiters are characters that separate tokens.
• Each character in the delimiters string is considered a valid delimiter—for
example, “,;:” sets the delimiters to a comma, semicolon, and colon.
• The default set of delimiters consists of the whitespace characters: space, tab,
newline, and carriage return.
Constructor of StringTokenizer class
• There 3 constructors of StringTokenizer class
1. StringTokenizer(String str): It creates StringTokenizer with specified string.
2. StringTokenizer(String str, String delim): It creates StringTokenizer with
specified string and delimiter.
3. StringTokenizer(String str, String delim, boolean returnValue): It creates
StringTokenizer with specified string, delimiter and returnValue. If return
value is true, delimiter characters are considered to be tokens. If it is false,
delimiter characters serve to separate tokens.
Methods of StringTokenizer class
Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.
title
Java: The Complete Reference
author
Schildt
publisher
Osborne/McGraw-Hill
copyright
2007
AWT
• Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
• Java AWT components are platform-dependent.
• Components are displayed according to the view of operating system.
• AWT is heavyweight. (Its components are using the resources of OS.)
• The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• Application developed in AWT have different look and feel when executed on
different platform.
• The java.awt package contains the core AWT graphics classes:
• GUI Component classes, such as Button, TextField, and Label.
• GUI Container classes, such as Frame and Panel.
• Layout managers, such as FlowLayout, BorderLayout and GridLayout.
• Custom graphics classes, such as Graphics, Color and Font.
• The java.awt.event package supports event handling:
• Event classes, such as ActionEvent, MouseEvent, KeyEvent and
WindowEvent,
• Event Listener Interfaces, such as ActionListener, MouseListener,
MouseMotionListener, KeyListener and WindowListener,
• Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and
WindowAdapter.
AWT Hierarchy
• There are two types of GUI elements:
1. Component
2. Container
1. Component: All the elements like the button, text fields, scroll bars, etc. are
called components.
• In Java AWT, there are classes for each component.
• In order to place every component in a particular position on a screen, we need
to add them to a container.
• Component is an abstract class that encapsulates all of the attributes of a visual
component.
• All user interface elements that are displayed on the screen and that interact with
the user are subclasses of Component.
2. 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 such as Frame,
Dialog and Panel.
• It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
• A container itself is a component, therefore we can add a container inside
container.
• It is a subclass of components
• It has additional methods that allow other Component objects to be nested
within it. Other Container objects can be stored inside of a Container.
• There are four types of container in java awt
• Window: The window is the container that have no borders and menu bars. 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 menu bars. It
can have other components like button, textfield etc. An instance of Panel class
creates a container, in which we can add components.
• Frame: The Frame is the container that contain title bar and border and can have
menu bars. It can have other components like button, text field, scrollbar etc. It is
the widely used container.
• Dialog :
• The class Component is the abstract base class for the non-menu
user-interface controls of AWT.
• A component represents an object with graphical representation.
• The class Container is the superclass for the containers of AWT.
• The container object can contain other AWT components.
In the above figure, there are three containers: a Frame and two Panels.
A Frame is the top-level container of an AWT program. A Frame has a title bar (containing an icon, a title, and
the minimize/maximize/close buttons), an optional menu bar and the content display area.
The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements
Container. A Panel is a rectangular area used to group related GUI components in a certain layout. In the above
figure, the top-level Frame contains two Panels. There are five components: a Label (providing description), a
TextField (for users to enter text), and three Buttons (for user to trigger certain programmed actions).
Component class
• It is a subclass of Object class.
• In order to have a particular component in a window, you must add the
component to the window.
• Component add(Component obj)
• The method return the reference of the obj
• Example:
• Button red=new Button(“red”);
• add(red);
• Remove a button:
• void remove(Component ob);
• The object of the component removed., which has passed as an argument.
• //Constructor of the Button class
• Button(); //Create Button without level
• Button(String str); // //Create Button level
• Example:
• Button obj= new Button(str);
• add(obj);
Methods of Component class
• public void add(Component c) :Inserts a component on this
component.
• public void setSize(int width,int height) : Sets the size (width and
height) of the component.
• public void setLayout(LayoutManager m) : Defines the layout
manager for the component.
• public void setVisible(boolean status): Changes the visibility of the
component, by default false.
Container class
Frame and Window: A Frame provides the "main window" for your GUI application. It
has a title bar (containing an icon, a title, the minimize, maximize/restore-down and close
buttons), an optional menu bar, and the content display area. To write a GUI program, we
typically start with a subclass extending from java.awt.Frame.
Dialog
Dialog: An AWT Dialog is a "pop-up window" used for interacting with the users. A Dialog
has a title-bar (containing an icon, a title and a close button) and a content display area.
Secondary containers are placed inside a top-level container or another secondary
container. AWT provides these secondary containers:
1. Panel: a rectangular box used to layout a set of related GUI components in pattern
such as grid or flow.
2. ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child
component others.
A Container has a LayoutManager to layout the components in a certain pattern.
Frame
• There are two ways to create a frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)
By extending Frame class (inheritance)
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 manager
setVisible(true);//now frame will be visible, by default not visible
}
} class Demo{
public static void main(String args[]){
First f=new First();
}
}
Cont...
• The setBounds(int xaxis, int yaxis, int width, int height): This method
is used in the above example that sets the position of the awt button.
Creating a Frame by Association
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
class Demo{
public static void main(String args[]){
First2 f=new First2();
}
}
TextField
• 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.
• public class TextField extends TextComponent
• The object of a TextField class is a text component that allows the
editing of a single line text. It inherits TextComponent class
Constructor
• TextField() : Constructs a new text field.
• TextField(int columns): Constructs a new empty text field with the
specified number of columns.
• TextField(String text) : Constructs a new text field initialized with the
specified text.
• TextField(String text, int columns): Constructs a new text field
initialized with the specified text to be displayed, and wide enough to
hold the specified number of columns.
Important Methods
• void setText(String t) : Sets the text that is presented by this text
component to be the specified text.
}
import java.awt.*;
import java.awt.event.*;
class MyFrameCheckBox extends Frame implements ItemListener{ public void itemStateChanged(ItemEvent ie) {
String msg=""; repaint();
Checkbox c1,c2; }
MyFrameCheckBox() { public void paint(Graphics g) {
c1 = new Checkbox("Bold",true); g.drawString("Curent state:",10,100);
c1.setBounds(100,100, 50,50); msg="Bold"+c1.getState();
c2 = new Checkbox("Itaic"); g.drawString(msg,10,120);
c2.setBounds(100,150, 50,50); msg="Italic:"+c2.getState();
add(c1); g.drawString(msg,10,140);
add(c2); }
c1.addItemListener(this); public static void main(String args[]){
c2.addItemListener(this); new MyFrameCheckBox();
setSize(400,400); }
setLayout(null); }
setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Panel
import java.awt.*;
public class PanelExample {
PanelExample() {
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel); f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
• The Dialog control represents a top level window with a border and a
title used to take some form of input from the user. It inherits the
Window class.
• Unlike Frame, it doesn't have maximize and minimize buttons.
• Frame vs Dialog
1. Frame and Dialog both inherits Window class.
2. Frame has maximize and minimize buttons but Dialog doesn't have.
import java.awt.*;
import java.awt.event.*;
public cla DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[]) {
new DialogExample();
}
}
Mouse Listener Interface
• The Java MouseListener is notified whenever you change the state of
mouse.
• It is notified against MouseEvent.
• The MouseListener interface is found in java.awt.event package. It has
five methods.
Methods of Mouse Listener Interface
• public abstract void mouseClicked(MouseEvent e);
• public abstract void mouseEntered(MouseEvent e);
• public abstract void mouseExited(MouseEvent e);
• public abstract void mousePressed(MouseEvent e);
• public abstract void mouseReleased(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label(); public void mousePressed(MouseEvent e) {
l.setBounds(20,50,100,20); l.setText("Mouse Pressed");
add(l); }
setSize(300,300); public void mouseReleased(MouseEvent e) {
setLayout(null); l.setText("Mouse Released");
setVisible(true); }
} public static void main(String[] args) {
public void mouseClicked(MouseEvent e) { new MouseListenerExample();
l.setText("Mouse Clicked"); }
} }
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
KeyListener Interface
• The Java KeyListener is notified whenever you change the state of key.
• It is notified against KeyEvent.
• The KeyListener interface is found in java.awt.event package. It has
three methods.
Methods of KeyListener interface
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){
l=new Label(); public void keyTyped(KeyEvent e) {
l.setBounds(20,50,100,20); l.setText("Key Typed");
area=new TextArea(); }
area.setBounds(20,80,300, 300);
area.addKeyListener(this); public static void main(String[] args) {
add(l);add(area); new KeyListenerExample();
setSize(400,400); }
setLayout(null); }
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
Closing the Frame
• We have to attach a listener to the frame component.
• f.addwindowListener(WindowListener obj);
• Implement all the methods of WindowListener interface.
• Public void windowActivated(WindowEvent e)
• Public void windowClosed(WindowEvent e)
• Public void windowClosing(WindowEvent e)
• Public void windowDeactivated(WindowEvent e)
• Public void windowDeiconified(WindowEvent e)
• Public void windowIconified (WindowEvent e)
• Public void windowOpened (WindowEvent e)
import java.awt.*;
import java.awt.event.*;
class MyFrameClosing extends Frame {
public static void main(String args[]) {
MyFrameClosing f1=new MyFrameClosing();
f1.setTitle("my AWT");
f1.setSize(300,250);
f1.setVisible(true);
f1.addWindowListener(new Myclass());
}
}
class Myclass implements WindowListener {
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified (WindowEvent e){}
public void windowOpened (WindowEvent e){}
}
Java Adapter Classes
• An adapter class is an implementation class of a listener interface
which contains all the methods with empty body.
• For example WindowAdapter is an adapter class of WindowListener
interface.
• If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves
code.
class Myclass extends WindowAdapter {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
Java Adapter Classes
• Java adapter classes provide the default implementation of
listener interfaces.
• If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves
code.
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
Layout
• 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.
• The layout manager is associated with every Container object. Each
layout manager is an object of the class that implements the
LayoutManager interface.
•
• LayoutManager- The LayoutManager interface declares those
methods which need to be implemented by the class whose object
will act as a layout manager.
•
AWT Layout Manager Classes:
import java.util.*;
class LearnArrayList{
output:
public static void main(String args[]){
[10, 20]
ArrayList<Integer> l=new ArrayList<Integer>(); [10, 100, 20]
l.add(10);
l.add(20);
System.out.println(l);
l.add(1,100); //Adding at specific index
System.out.println(l);
}
}
Example
import java.util.*;
class Test {
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Pradipta");//Adding object in arraylist
list.add("Hrisikesh");
list.add("Pryanshu"); output:
list.add("Pravid");
//Traversing list through Iterator Pradipta
Iterator itr=list.iterator(); Hrisikesh
Pryanshu
while(itr.hasNext()){
Pravid
System.out.println(itr.next());
}
}
}
import java.util.*;
class ArrayListDemo {
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
import java.util.*;
class ArrayListToArray {
public static void main(String args[]) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(3);
al.add(4); Contents of al: [1, 2, 3, 4]
System.out.println("Contents of al: " + al); Sum is: 10
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
int sum = 0;
for(int i : ia)
sum += i;
System.out.println("Sum is: " + sum);
}
}
Sometimes we need to obtain an actual array that contains the contents of the list. We can do this by calling toArray( ),
which is defined by Collection.
Linked List class
• Java LinkedList class uses doubly linked list to store the elements. It
provides a linked-list data structure.
• It inherits the AbstractList class and implements List and Deque
interfaces.
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• In Java LinkedList class, manipulation is fast because no shifting
needs to be occurred.
• Java LinkedList class can be used as list, stack or queue.
Traversing
import java.util.*;
class Test{
public static void main(String args[]){
LinkedList<Integer> list=new LinkedList<Integer>(); //Creating
arraylist
list.add(10);//Adding object in arraylist
list.add(20);
list.add(30);
list.add(40);
//Traversing list through Iterator
System.out.println(list);
}
}
output: [10, 20, 30, 40]
Three different way we can traverse the
list
1.
output:
for(int i=0;i<list.size();i++){ The elements are: 10
System.out.println("The elements are: "+list.get(i)); The elements are: 20
The elements are: 30
} The elements are: 40
2.
for(Integer ele:list){ output:
System.out.println("The elements are: "+ele); The elements are: 10
The elements are: 20
} The elements are: 30
The elements are: 40
Traverse the list using iterator
Iterator<Integer> it=list.iterator();
output:
while(it.hasNext()){ The elements are: 10
System.out.println("The elements are: "+it.next()); The elements are: 20
} The elements are: 30
The elements are: 40
Operation on list
• list.add(ele)
• list.add(index,ele) # add the eleement into the specific index O(n)time
• Updating eleement:
• list.set(2,55);
• Remove eleement
• list.remove(1)
• list.remove(Integer.valueOf(30)) //remove the specified value...
• Delete the entire list:
• list.clear()
• Search element avilable or not:
• list.contains(40) #return true/false
import java.util.*;
class Test{
public static void main(String args[]){
LinkedList<String> list=new LinkedList<String>();
//Creating arraylist
list.add("PKP");//Adding object in arraylist
list.add("Hrisikesh"); output:
Pradipta
list.add("Pryanshu");
Hrisikesh
list.add("Pravid"); Pryanshu
//Traversing list through Iterator Pravid
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); Original contents of ll: [A, A2,
ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2"); F, B, D, E, C, Z]
Contents of ll after deletion: [A,
System.out.println("Original contents of ll: " + ll);
A2, D, E, C, Z]
ll.remove("F");
ll after deleting first and last:
ll.remove(2); [A2, D, E, C]
System.out.println("Contents of ll after deletion: " + ll); ll after change: [A2, D, E
ll.removeFirst(); Changed, C]
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
String val = ll.get(2);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
OUTPUT:
this.publisher = publisher; 101 Let us C Yashwant Kanetkar BPB 8
this.quantity = quantity; 102 Data Communications & Networking
Forouzan Mc Graw Hill 4
} 103 Operating System Galvin Wiley 6
}
public class LinkedListDemo {
public static void main(String[] args) {
List<Book> list=new LinkedList<Book>();
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System", "Galvin","Wiley",6);
list.add(b1);
list.add(b2);
list.add(b3);
for(Book b:list) {
System.out.println(b.id+" "+b.name+" "+b.author+ " "+b.publisher+" "+b.quantity);
}
}
}
Difference between array list and Linked list
Vector
• Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods
that are not the part of Collection framework.
import java.util.*;
class Test{
public static void main(String args[]){
Vector<String> vec=new Vector<String>();
vec.add("PKP"); //Adding object in arraylist
vec.add("Hrisikesh");
vec.add("Pryanshu");
vec.add("Pravid"); output:
Pradipta
//Traversing list through Iterator Hrisikesh
Iterator itr=vec.iterator(); Pryanshu
Pravid
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Stack
• The stack is the subclass of Vector. It implements the last-in-first-out
data structure, i.e., Stack. The stack contains all of the methods of
Vector class and also provides its methods like boolean push(),
boolean peek(), boolean push(object o), which defines its properties.
import java.util.Stack;
import java.util.*;
class Test{
public static void main(String args[]){
Stack<String> st= new Stack<String>();
st.push("Ayush");
st.push("Garvit");
st.push("Amit");
st.push("Ashish");
st.push("Garima");
st.pop();
Iterator itr=st.Iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
• The Queue interface present in the java.util package and extends
the Collection interface is used to hold the elements about to be
processed in FIFO(First In First Out) order.
• It is an ordered list of objects with its use limited to insert elements at
the end of the list and deleting elements from the start of the list.
• It follows the FIFO or the First-In-First-Out principle
• Since Queue is an interface, objects cannot be created of the type
queue. We always need a class which extends this list in order to
create an object.
import java.util.*;
class Test{
public static void main(String args[]){
Queue<Integer> q= new LinkedList<Integer>();
q.add(20);
q.add(30);
q.add(50);
System.out.println(q);
int rem = q.remove(); //Remove element
System.out.println("removed element-"+ rem );
int head = q.peek(); // To view the head of queue
System.out.println("head of queue-"+ head);
System.out.println(q)
}
}
PriorityQueue
• The PriorityQueue class implements the Queue interface. It holds the
elements or objects which are to be processed by their priorities.
PriorityQueue doesn't allow null values to be stored in the queue.
• A PriorityQueue is used when the objects are supposed to be processed based
on the priority.
• The PriorityQueue is based on the priority heap. The elements of the priority
queue are ordered according to the natural ordering, or by a Comparator
provided at queue construction time, depending on which constructor is used.
• PriorityQueue doesn’t permit NULL pointers.
• We can’t create PriorityQueue of Objects that are non-comparable.
• PriorityQueue are unbound queues.
• It inherits methods from AbstractQueue, AbstractCollection, Collection and
Object class.
import java.util.*;
class Test{
public static void main(String args[]){
Queue<Integer> q= new PriorityQueue<Integer>();
q.add(100); //While adding, it create the min-priority queue
q.add(30);
output:
q.add(55); [30, 70, 55, 100]
q.add(70); removed element-30
System.out.println(q); head of queue-30
[30, 70, 55, 100]
System.out.println("removed element-"+ q.peek());
int head = q.peek();
System.out.println("head of queue-"+ head);
System.out.println(q);
}
}
Remove elements from queue
• queue.remove();
• queue.poll();
import java.util.*;
class Test{
public static void main(String args[]){
Queue<Integer> q= new PriorityQueue<Integer>();
q.add(100); //While adding, it create the min-priority queue
q.add(30);
q.add(55);
q.add(70);
[30, 70, 55, 100]
System.out.println(q); head of queue-30
int head = q.poll(); [55, 70, 100]
System.out.println("head of queue-"+ head);
System.out.println(q);
}
}
class Exercise {
public static void main(String[] args){
PriorityQueue<String> pq1 = new PriorityQueue<String>();
pq1.add("Red"); pq1.add("Green"); //While adding, it create the priority queue
pq1.add("Black"); pq1.add("White");
System.out.println("First Priority Queue: "+pq1);
PriorityQueue<String> pq2 = new PriorityQueue<String>();
pq2.add("Red"); pq2.add("Pink");
pq2.add("Black"); pq2.add("Orange");
System.out.println("Second Priority Queue: "+pq2);
//comparison output in Priority Queue
for (String element : pq1){
System.out.println(pq2.contains(element) ? "Yes" : "No");
}
}
}
First Priority Queue: [Black, Red, Green,
White]
Second Priority Queue: [Black, Orange,
Pink, Red]
Yes
Yes
No
No
import java.util.*;
class Example {
public static void main(String args[]) {
PriorityQueue<String> pQueue = new PriorityQueue<String>();
pQueue.add("C");
pQueue.add("C++");
pQueue.add("Java");
pQueue.add("Python");
System.out.println("Head value using peek function:"+ pQueue.peek());
System.out.println("The queue elements:"+pQueue);
pQueue.poll();
System.out.println("After removing an element with poll function, the queue elements: "+pQueue);
pQueue.remove("Java");
System.out.println("After removing Java with remove function:"+pQueue);
boolean b = pQueue.contains("C");
System.out.println ( "Priority queue contains C or not?: " + b);
Object[] arr = pQueue.toArray();
System.out.println ( "Value in array: ");
for (int i = 0; i<arr.length; i++)
System.out.println ( "Value: " + arr[i].toString()) ;
}
Head value using peek function:C
The queue elements:[C, C++, Java, Python]
After removing an element with poll function, the queue
elements: [C++, Python, Java]
After removing Java with remove function:[C++, Python]
Priority queue contains C or not?: false
Value in array:
Value: C++
Value: Python
Set Interface
• Set Interface in Java is present in java.util package.
• It extends the Collection interface.
• It represents the unordered set of elements which doesn't allow us to
store the duplicate items.
• We can store at most one null value in Set.
• Set is implemented by HashSet, LinkedHashSet, and TreeSet.
• Set<data-type> s1 = new HashSet<data-type>();
• Set<data-type> s2 = new LinkedHashSet<data-type>();
• Set<data-type> s3 = new TreeSet<data-type>();
import java.util.*;
class Test{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator(); output:
while(itr.hasNext()){ Vijay
System.out.println(itr.next());
}
Ajay
} Ravi
}
• LinkedHashSet class represents the LinkedList implementation of Set
Interface. It extends the HashSet class and implements Set interface.
Like HashSet, It also contains unique elements. It maintains the
insertion order and permits null elements.
import java.util.*;
class Test{
public static void main(String args[]){
LinkedHashSet<String> set=new
LinkedHashSet<String>(); output
set.add("Ravi"); :
set.add("Vijay"); Ravi
set.add("Ravi");
set.add("Ajay");
Vijay
Iterator<String> itr=set.iterator(); Ajay
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
SortedSet Interface
• SortedSet is the alternate of Set interface that provides a total
ordering on its elements. The elements of the SortedSet are arranged
in the increasing (ascending) order. The SortedSet provides the
additional methods that inhibit the natural ordering of the elements
• SortedSet<data-type> set = new TreeSet();
TreeSet
• Java TreeSet class implements the Set interface that uses a tree for
storage. Like HashSet, TreeSet also contains unique elements.
However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.
import java.util.*;
class Test{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi"); output:
set.add("Vijay");
Ajay
set.add("Ravi");
set.add("Ajay"); Ravi
Iterator<String> itr=set.iterator(); Vijay
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Write a Java program to create a new tree set, add some colors
(string) and print out the tree set.
import java.util.TreeSet;
class Exercise {
public static void main(String[] args) {
TreeSet<String> tree_set = new
TreeSet<String>(); output:
tree_set.add("Red"); Tree set:
tree_set.add("Green"); [Black, Green, Orange, Red, White]
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
System.out.println("Tree set: ");
System.out.println(tree_set);
}
}
Get the first and last elements in a tree
set.