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

JAVA CMPLT

Java document

Uploaded by

das93814
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

JAVA CMPLT

Java document

Uploaded by

das93814
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

JAVA NOTE

ANANTA DEV PAL


9874040410

2016
JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NAT
NATH 9038664188

JAVA
History of Java

Java is a general purpose object oriented programming language developed by Sun


Microsystem(USA) in 1991. It was originally called OAK by Jeams Goshing.. Java was designed for
developing the software for consumer electronic devices
device such as TV, VCR, Toaster and other electronic
machine.

In 1994 the being developed a web browser called Hot Java to locate and run applet program on
the internet.

In 1995 OAK was renamed as Java. In 1997 Sun Microsystem releases JDK 1.1 (Java
Development Kit).

Difference
nce between C language and Java

C language Java

C language has #define, #include. Java does not have any header file.
C has Struct and Union. Java does not have Struct and Union.

C supports pointer. Java does not support pointer.


C supports auto extern register. Java does not support auto extern register.

C is a structure oriented programming. Java is true object oriented programming.


C supports “SizeOf” operator. Java does not support “SizeOf” operator.

Difference between C++ and Java

C++ Java

C++ is object oriented programming. Java is true object oriented programming.


C++ supports pointer. Java does not support pointer.
C++ supports template. Java does not support template..
C++ supports multiple inheritances. Java does not support multiple inheritances
inheritances.

C++ supports global and local data access.


access Java does not support global and local data access.
access

C++ supports operator overloading. Java does not support operator overloading.
overloading

Relationship between C, C++, Java

1 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

C++

C Java

Features of Java

The features are following

i) Compiled and interpreted.


ii) Platform independent and portable.
iii) Object oriented.
iv) Robust and secure.
v) Distributed.
vi) Multi threated.
vii) High performance.
viii) Dynamic.
ix) Easy to development.
x) Simple and small.

Compiled and Interpreted

Generally computer language is either compiled or interpreted. Java combines both these features.

First Java compilers translate source code into byte code. Byte code is not machine instruction.

Second Java interpreter generate machine code that can be directly executed by the machine that
is running the java program. Therefore we can say java is compiled and interpreted.

Compiler1 Object code or machine code

C Compiler2 Object code or machine code

Compiler3 Object code or machine code

JVM (Java Virtual Machine)

2 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Java Source Code Java Compiler Byte Code (Machine Independent Code)

Byte Code Java Interpreter Executable Code

Platform Independent & Portable

The most significant contribution of Java over other languages is portability.

Java program can be easily moved from one computer system to another anywhere and anytime.

Changes and upgrades in operating system processor & system resources will not any changes in
Java programming. This is the reason why Java has began popular language for programming on internet
which interconnects different kind of system worldwide.

Object oriented

Java is a true object oriented. Almost everything in java is object, all program code & data resident
during objects & classes.

Robust and secure

Java is a robust language. It provides much safe guard to ensure reliable code. It has strict
compiled time and run time checking for data type.

It is designed as garbage collected language.

Security becomes an important issue for a language that is used for programming on internet.
Thread of viruses and abuse of resources can be protected by java programs.

Distributed

Java is designed as distributed language for creating application and on it works. It has the ability to
share both data and program. Java application can open and access remote object on internet as they can
do in a local system.

Multi Threaded

Java is designed to be real world requirement of creating interacting network program.

Java supports multi threaded which allow us to program to do many things simultaneously.

Multi threaded means we need not wait for the application to finish before beginning another. For
example we can listen an audio clip while scrolling a page and at the same time download an applet from
the remote computer.

High performance

Java performance is impressive for an interpreted language due to the use of interpreted byte code.

Java architecture is also denied to reduce overhead during runtime

3 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Dynamic

Java is a dynamic language. Java is capable of dynamically linking in new class libraries method
and objects. Java can also determine the type of class through query, making it possible to either
dynamically link or abort the programming depending on the response.

Easy to develop

Java 2 standard edition supports easy to development tools.

Simple and small

Java was designed to be easy for the professional programmer to learn an use effectively. Java is a
small & simple language.

Many features of C, C++ either remove by java of create a new features to active new technology.

How Java is connected to the internet?

Java is strongly associated with internet because of a fact that the first application program written
in Java was Hot Java, web browser to run applet on internet. Internet uses can use java to run applet
program and run them locally using java enable browser. They can also use java enable browser to
download an applet located on computer anywhere in the internet.

Internet user can also set up their web sites containing java applet that could be use other remote
user form the internet. Consider the following diagram.

Remote Applet

Internet
Local Computer Remote Computer

How Java is connected to WWW?

WWW is an information retrieval system designed to be used in the internet. This system knows as
web pages. Web system is open indent and we can navigate to a new document in any direction. This is
made possible with the help of HTML. Java is meant to be use in distributed environment such as internet.
Seems java a web are connected to each other therefore Java can easily access web page.

The following steps are use for java inter connection to the web.

(i) The user sends a request for a HTML document to the remote computer’s web server. The web
server is a program that accept a request, process the request and sends the require document.
(ii) The HTML document is return to the user’s browser. The contents applet tags which identities
the objects.
(iii) The corresponding applet byte code is transfer to the user computer. This byte code had been
previously created by java compiler using java source code.
(iv) Java enable browser on the user’s computer interprets the byte code and provides output.

4 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

(v) The user may further interaction with applet but no further downloading form provider web
server. This is because byte code remains in the user computer to interpret the applet.

User’s Computer Remote Computer

Byte code 4 Applet source code

6 Byte code

5 3
Java web browser
Applet tag HTML
document
7
Request
2
Output 1 Web Browser

User

Write a program to add two numbers.

import java.util.Scanner.*;
import java.io.*;
Class ADD
{
public static void main(String args[])
{
System.out.println("Enter two numbers: ");
int a,b;
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
int c=a+b;
System.out.println("Result of addition: "+c);
}
}

Write a program to check a number is even or odd.

import java.util.Scanner.*;
import java.io.*;
Class even
{
public static void main(String args[])
{

5 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

System.out.println("Enter a number: ");


int a;
Scanner s=new Scanner(System.in);
a=s.nextInt();
if(a%2=0)
System.out.println("The number "+a+” is even”);
else
System.out.println("The number "+a+” is odd”);
}
}

Write a program to find factorial of a number.

import java.util.Scanner.*;
import java.io.*;
Class fact
{
public static void main(String args[])
{
System.out.println("Enter a limit: ");
int a;
long int f=1;
Scanner s=new Scanner(System.in);
a=s.nextInt();
for(int i=a;i>=1;i--)
{
f=f*i;
}
System.out.println("Factorial value is "+f);
}
}

WAP to find a number is Prime or not

import java.util.Scanner.*;
import java.io.*;
Class prime
{
public static void main(String args[])
{
System.out.println("Enter a number: ");
int a, flag=0;
Scanner s=new Scanner(System.in);
a=s.nextInt();
for(int i=2;i<a;i++)
{
if(a%2==0)

6 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("Number is not prime.");
}
else
{
System.out.println("Number is prime.");
}
}
}

WAP to find fibonacci series

import java.util.Scanner.*;
import java.io.*;
Class fibo
{
public static void main(String args[])
{
System.out.println("Enter a limit: ");
int a,b,c=0;
Scanner s=new Scanner(System.in);
a=s.nextInt();
for(int i=0;i<a;i++)
{
if(i==0)
System.out.println("0");
else if(i==1)
System.out.println("1");
else
{
c=a+b;
System.out.println(""+c);
a=b;
b=c;
}
}
}
}

7 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

WAP to add two number using java OOP


import java.util.Scanner.*;
import java.io.*;
Class ADD
{
int a,b;
Scanner s=new Scanner(System.in);
void input()
{
System.out.println("Enter two numbers: ");
a=s.nextInt();
b=s.nextInt();
}
void output()
{
int c=a+b;
System.out.println("Result of addition: "+c);
}
}
class addition
{
public static void main(String args[])
{
ADD A=new ADD();
A.input();
A.output();
}
}

WAP to find factorial of a number using java OOP


import java.util.Scanner.*;
import java.io.*;
Class FACT
{
int a;
Scanner s=new Scanner(System.in);
void input()
{
System.out.println("Enter a limit: ");
a=s.nextInt();
}
void output()
{
long int f=1;
for(int i=a;i>=1;i--)
{
f=f*i;

8 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

}
System.out.println("Factorial value is "+f);
}
}
class factorial
{
public static void main(String args[])
{
FACT A=new FACT();
A.input();
A.output();
}
}

Constructor is java

Java supports a special type of method called constructor that enables an object to initialize itself
when it is created.

Characteristics

1. Name of constructor is same as class name.


2. Constructor do not specify a return type not even void.
3. Constructor called automatically when the object is created. For example of two using constructor

import java.util.Scanner.*;
import java.io.*;
Class ADD
{
int a,b;
ADD()
{
x=10;
y=20;
}
ADD(int x,int y)
{
a=x;
b=y;
}
void addi()
{
int c;
c=a+b;
System.out.println("Result is: "+c);
}
}
class addition
{
9 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER
JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

public static void main(String args[])


{
addi A1=new addi();
addi A2=new addi(5,6);
A1.addi();
A2.addi();
}
}

WAP to calculate factorial of number using constructor


import java.util.Scanner.*;
import java.io.*;
Class FACT
{
int a;
FACT()
{
x=5;
}
ADD(int x)
{
a=x;
}
void factorial()
{
int f=1;
for(int i=a;i>=1;i--)
{
f=f*1;
}
System.out.println("Factorial is: "+f);
}
}
class res
{
public static void main(String args[])
{
FACT A1=new FACT();
int y;
System.out.println("Enter a number: ");
Scanner s=new Scanner(System.io);
y=nextInt();
FACT A2=new FACT(y);
A1.factorial();
A2.factorial();
}
}

10 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

What do you mean by constructor overloading?

What do you mean by method overloading? Write with example.

It is possible to create methods that have same name but different parameter and different
definition. This is called method overloading.

Method overloading is used when objects are require to perform similar task but using different
parameter.

When we call a method in a object java matches up the method name first and then number of and types of
parameters are checked. This process is known as polymorphism. For example

WAP to find area of a circle, rectangle, square.


import java.util.Scanner.*;
import java.io.*;
Class AREA
{
void calculation(float r)
{
float c;
c=3.14*r*r;
System.out.println("Area of circle: "+c);
}
float calculation()
{
float R;
R=l*b;
return(R);
}
float calculation(float a)
{
float S;
S=a*a;
return(S);
}
}
Class Areas
{
public static void main(String args[])
{
AREA A1=new AREA();
float p=A1.calculation(5.5);
float p=A1.calculation(7.5);
float q=A1.calculation(5.5,6.5);
System.out.println("Area of square: "+p);
System.out.println("Area of rectangle: "+q);
}
}

11 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

What is recursion?
When a method is called itself then it is called recursion. There are types of recursion.
a. Direct
b. Indirect

In direct recursion a method called itself. In indirect recursion a method called another method
which callback the first method.

WAP to find fact of a number


import java.util.Scanner.*;
import java.io.*;
Class FACT
{
long int facto(int x)
{
if(x==0)
return(1);
else
return(x*facto(x-1));
}
}
Class Factorial
{
public static void main(String args[])
{
FACT F1=new FACT();
long int y=F1.facto(5);
System.out.println(y);
}
}

WAP to generate Fibonacci series


import java.util.Scanner.*;
import java.io.*;
Class FIBO
{
int calc(int x)
{
if(x==0)
System.out.println(0);
elseif(x==1)
System.out.println(1);
else
return(FIBO(x-1)+FIBO(x-2));
}
}

12 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Class FIBONACCI
{
public static void main(String args[])
{
FIBO F1=new FIBO();
int x;
Scanner s=new Scanner();
n=s.nextInt();
for(int i=0;i<n;i++)
{
System.out.println(F1.FIBONACCI(i));
}
}
}

Inheritance

Reusability is one of the important topics of OOP. It is always nice if we could reuse something that already
exists rather than creating the same all over again. Java supports this concept. The mechanism of creating
new class from the old class is called inheritance. Old class is known as base or super class. New class is
derived or sub class.

The inheritance allow sub class to inherit all the variables and methods of there parent classes.
Types of inheritance:-

Single inheritance
In this type of inheritance sub class inherit from super class.

A B

Super class Sub class

Multilevel inheritance
In this type of inheritance sub class inherit the properties of another sub class.

A B C

Super class Sub class Sub class

Hierarchical inheritance
In this type of inheritance many sub classes can be created from one single super class.

B C D

13 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Multiple inheritances are not supports in java. However it is implements with the help of interface.

Syntax for inheritance:-


Class superclass name
{
--
--
}
Class subclassname extands superclassname

Example of inheritance

import java.util.Scanner.*;
import java.io.*;
Class A
{
int a,b;
void input()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a number");
a=s.nextInt();
b=s.nextInt();
}
void add()
{
int c=a+b;
System.out.println("Result of addition "+c);
}
}
class B extands A
{
int x,y;
void input()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a number");
x=s.nextInt();
y=s.nextInt();
}
void sub()
{
int z=x-y;
System.out.println("Result of addition "+z);
}
}

14 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

class inheritance
{
public static void main(String args[])
{
B M=new B();
M.input();
M.add();
M.input();
M.sub();
}
}

WAP to include inheritance where first class consist of to check a number is even or odd, Second
class consists of largest among two numbers.
import java.util.Scanner.*;
import java.io.*;
Class first
{
int a;
void input()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a number");
a=s.nextInt();
}
void evenodd()
{
if(a%2==0)
System.out.println("Number "+a+" is even");
else
System.out.println("Number "+a+" is odd");
}
}
class second extands first
{
int x,y;
void input()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a number");
x=s.nextInt();
y=s.nextInt();
}
void large()
{
if(x>y)
System.out.println("Number "+x+" is large");

15 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

else if(x==y)
System.out.println("Both are same");
else
System.out.println("Number "+y+" is large");
}
}
class inheritance
{
public static void main(String args[])
{
second M=new second();
M.input();
M.evenodd();
M.input();
M.large();
}
}

What do you mean by method overriding?


A method define in a super class is inherited by its subclass and its use by the objects created by
the subclass. Method inheritance enables us to define and use method repeatedly in subclasses without
having to define the method again in subclass. However there may be same situation when we want an
object to respond to the same method but have different behavior when that method is called that means
we should override the method defined in super class. This is possible by defining a method in the subclass
that has the same name, same argument, and same return type as a method in the super class. Then when
that method is called, the method defined a subclass is called and executed instead of one in the super
class. This technique is known as overriding.
What do you mean by final variables and methods? What you mean by final classes? What
is finalizing method? What do you mean by abstract method and classes?
All methods and variables can be over hidden by default in the sub classes if we wish to prevent
subclasses from overriding then you can declare them as final using the keyword final.
Making a method final ensure that the functionality defining the method will never be attend in any
way. Similarly the value of final variable can never be changed. Final variable behave like class variable
and they do not take any space on individual object of the class.
final int x=10;
final void display()
{
-----
-----
}
Final class: Sometimes we may like to prevent a class being further subclass for security reason, a class
that is cannot be subclass is called Final class. This is achieved using the keyword ‘Final’. Any attempt to
inherit these classes will cause an error and the compiles will not allow it. For ex…
final class A
{
---
16 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER
JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

---
}
class B extends A // error inheritance is not possible
{
---
}

Abstract method and classes: Any class that contains one or more abstract method must be to declare a
class abstract we use keyword abstract there is no object or abstract class in abstract class there is only
class definition no object is possible from the abstract class. For example,

abstract class ABCD


{
abstract void display()
void show()
{
System.out.println("Haldiram");
}
}
class XYZ extends ABCD
{
void display()
{
System.out.println("Motichur ke ladoo");
}
}
class abstract
{
public static void main(String args[])

WAP to implement abstract class in abstract method to calculate area of a circle, rectangle and
square

abstract class ABCD


{
float a,b;
ABCD(float, float)
{
a=x;
b=y;
}
abstract float area();
}
class circle extends ABCD
{
circle(int r)
{
super(r,r);
}
float area()
{
float c=3.14*a*a;
return(c);
}

17 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

}
class Rectangle extends ABCD
{
Rectangle(int m, int n)
{
super(m,n)
}
float area()
{
float R=a*b;
return(R);
}
}
class Abstract
{
public static void main(string args[])
{
circle c1=new circle(5,5);
float p1=c1.area();
System.out.println("Area is "+p1);
Ractangle R1=new Ractangle(6,7);
float p2=R1.area();
System.out.println("Area is +p2");
}
}

Finalizer: Constructor is use to initialize an object when it is declare this process is known initialization.
Similarly java supports finalization which is just opposite to initialization. We know java runtime is as
automatic garbage collection system, it automatically free of the memory resources use by the object, it is
similar to destructor in C++.

What do you mean by multi threaded programming?

Multithreaded is a conceptual programming structure where a program is divided into two or more
sub program which can be implemented at the same time parallel. For example, Once a program can be
display an animation in screen while another may build the next animation to be display.

In most of our computer we have only a single processor and therefore in reality the process is
doing only one thing at a time. However a processor switches between the process so first that it appears
to human being that all of them have being done simultaneously.

A thread is similar to a program that has a single flow of control if has a beginning a body and an
end and execute command sequentially. Java enables us to use multiple flow of control in developing
programs. It flows of control in developing programs. It flow of control may be thought of a separate
program known as thread.

A Program that contains multiple flow of control is known as multi threaded programming. For
example,

18 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Main() main()
{ {
}
Thread
}

End

Single Thread
Thread A Thread B Thread C

Life cycle of thread

During the life cycle of thread there are many state it can enter the include

a) New born state


b) Run able state
c) Running state
d) Blocked state
e) Dead state

The diagram is given below

New born state

start
stop
Queue

Active Runnable
Running Dead
state state stop
state

Suspend()
resume() stop
sleep()
notify()
wait()
Blocked state

19 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

New born state

When we create a thread object the thread is born and it is said to be new born state. The thread is
not yet schedule for running. At this state we can do only one of the following

i) Schedule it for running start method


ii) Kill it using stop method

The following diagram shows schedule of new born state.

New Born

Start Stop

Active state Dead state

Runnable state

The runnable state means the thread is execution and waiting for the availability of the processor
that is the thread is join the queue of threads that are waiting for execution if all thread have equal priority
then there given time slots for execution in round robin fusion that is first came first out manner.

yeild()

Running thread Run able thread

Running state

Running means that the processor that given its time for its executions. The threads run until it
releases control on its own or it is preempted by higher priority thread. A running thread may releases it
control is one of the following situation.

a) It has been suspended using suspend method this approach is used for when we want it
suspend a thread for some time due to certain reason but not want to kill it.

suspend()

resume()

Running thread Run able thread Blocked state

20 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

b) It has been made to sleep we can put a thread to sleep for a specified time period using sleep
where time is in millisecond this means there are the thread is out of the queue during this time
period. The thread reenters the runnable state as soon as the period is elapsed.

sleep(t)

after(t)

Running thread Run able thread Blocked state

c) It has been told to wait until some gives occurs this is done by wait() method the thread can be
schedule to run again using notify() method.

wait(t)

notify()

Running thread Run able thread Blocked state

Blocked state

A thread is said to blocked when it is prevented form entering into runable state and sub
sequentially the running state this happens when the thread is suspended, sleeping or waiting in order to
satisfy certain requirement a blocked thread is consider not runnable but not dead and therefore fully
qualified to run again.

Dead state
Every thread has a life cycle a running thread ends its life when it has completed executing a run
method it’s a natural death. However we can kill it by sending stop message to it at any state thus causing
a premature death to it. A thread can be killed as soon as it is born for while it is running.

Difference between multithreading and multitasking

Multithreading Multitasking
It is programming concept in which a program or
It is an operating system concept is which multiple
process is divided into two or more sub program or
task are perform simultaneously.
thread that are executed at the same time parallel.
It supports executing execution of multiple parts of a It supports execution of multiple program
single program simultaneously. simultaneously.
The processor has to switch between different parts The processor has to switch between different
or thread of program. program and process.

21 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

It is highly efficient. It is less efficient.

It helps in developing efficient program. It helps in developing efficient operating system.

It is less expensive in terms of context switching. It is more expensive in terms of context switching.

How to create a thread?

Creating threads in java is simple. Threads are implemented in the form of object that contains a
method called run(). The run() method is the heart and soul of any thread its make are entire body of thread
and is the only method in which threads behavior can be implemented. A thread can be created in two way

a) By creating a thread class: Define a thread class that extends that contains thread class and
override in run() method with the code required by the thread.
b) By converting a class called thread: Define a class that implements runnable interface that has
only one method run().

Example of thread
import java.io.*;

class A extends Thread


{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Within thread a "+i);
}
}
}
class B extends thread
{
public void run()
{
for(int j=1;j<5;j++)
{
System.out.println("Within thread b "+j);
}
}
}
class C extends thread
{
public void run()
{
for(int k=1;k<5;k++)
{
System.out.println("Within thread c "+k);
}
}
}
class thread test

22 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

{
public static void main(string args[])
{
A a=new A();
B b=new B();
C c=new C();
a.start();
b.start();
c.start();
}
}

WAP to show different method of thread


import java.io.*;

class A extends Thread


{
public void run()
{
for(int i=0;i<5;i++)
{
if(i==1) yield ();
System.out.println("Within thread a "+i);
}
}
}
class B extends thread
{
public void run()
{
for(int j=1;j<5;j++)
{
if(i==2) sleep();
System.out.println("Within thread b "+j);
}
}
}
class C extends thread
{
public void run()
{
for(int k=1;k<5;k++)
{
if(k==3) stop();
System.out.println("Within thread c "+k);
}
}
}
class thread test
{
public static void main(string args[])
{
A a=new A();
B b=new B();

23 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

C c=new C();
a.start();
b.start();
c.start();
}
}

What do you mean by thread priority?

In java each thread is assign a priority which affect the border in which it is schedule for running the
thread we have known are so far same priority. However we can assign different priority number for a
thread. The syntax for setting a priority number is

Threadname.setPriority(intnumber);

Here Threadname is the thread object to which we want to create priority number. “setPriority” is the
method through we assign priority number for a thread. “intnumber” is the integer variable assigned a
priority number generally any number between 1-10 there are few constant which indicate some priority
number. For example

MIN_PRIORITY=1
MAX_PRIORITY=10
NORM_PRIORITY=5

Most user label process should use NORM_PRIORITY background task such as network, io or stream
painting are the lower limit why assigning priority to thread we can ensure that there given the attention they
deserve. For example

import java.io.*;

class A extends Thread


{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Within thread a "+i);
}
}
}
class B extends thread
{
public void run()
{
for(int j=1;j<5;j++)
{
System.out.println("Within thread b "+j);
}
}
}
class C extends thread

24 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

{
public void run()
{
for(int k=1;k<5;k++)
{
System.out.println("Within thread c "+k);
}
}
}
class thread test
{
public static void main(string args[])
{
A a=new A();
B b=new B();
C c=new C();
a.setPriority(Thread.MAX_PRIORITY);
B.setPriority(Thread.NORM_PRIORITY);
C.setPriority(Thread.MIN_PRIORITY); / a.getPriority()-1
a.start();
b.start();
c.start();
}
}

What is synchronization?

In thread we use data and method inside the run() method. What happen when we try to use data
and method outside the run() on such situation they may complete for same resources and may lead to
serious problem. For example one thread may try to read a record from a file another is still writing to same
file. Depending on the situation we make strange result. Java enables us to overcome this problem using
the technique known as synchronization. There is a keyword Synchronized to solve such problem. For
example

Synchronized void display ()


{
---
--- Method
}

In synchronization there may be some problem such as deadlock where one thread wants to access
the data member that is already occupied by another thread. So the first thread is waiting for second thread
and there is an infinite waiting is possible.

What is error?

Rarely does a program run successfully at very first attempt. There is some common mistake while
developing as well as typing a program. A mistake might lead to an error causing two program to produce
unexpected error. Errors are the wrong that can make a program go wrong.
Error

Compile time error Run time error

25 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

There are two types of error 1) Compile time error, 2) Runtime error.

Compile time error: Syntax error will be detected and displayed by the java compile and therefore these
errors are known as compiler. Whenever the compiler displays an error it will not create .class file. It is
therefore necessary that we fixed all errors before we can successfully compile and run the program.

Most common compile type errors are

1) Missing semicolon
2) Missing brackets
3) Missing double quote in string
4) Use of undeclared variable
5) Use of = instead of==

Runtime error: Sometime a program may compile successfully creating the .class file, but may not run
properly. Most common runtime errors are.

1) Dividing an integer by 0
2) Accessing a element that is out of bound of an array.
3) Trying to store a value into an array of different type.
4) Attempting to use negative sign of an array.
5) Converting invalid string into number.
6) Trying to illegally change state of a thread.

import java.io.*;
import java.util.scanner.*;

Class Error1
{
public static void main(string args[])
{
float a,b,c;
a=20;
b=30 // missing semicolon
c=a+b;
System.out.println("Result is "+c) // missing semicolon;
}
}

import java.io.*;
import java.util.scanner.*;

Class Error2
{
public static void main(string args[])
{

26 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

float a,b,c;
a=20;
b=0;
c=a/b; // divided by zero error it is a runtime error
System.out.println("Result is "+c);
}
}

Exception handling: An exception is a condition that caused by runtime error in the program when the
java interpreter encounter an error such as dividing an integer by zero in creates exception object and
throws it. If the exception object not works properly the interpreter will display an error message. Exception
handling consist of following steps

1) Find the problem (Hit the exception).


2) Inform that an error has occur (Throw the exception).
3) Catch the exception (Receive the error information).
4) Take the corrective action.

The following diagram shows how exception handling can control.

Try block

Detect and Try


Throws {
Exception ______
______
}
Catch(Exception object)
{
______
______
Catch block }

Catch the
exception and
Display it

Some of the common java exception

Exception Meaning

ArithmeticException. Cause by math errors.

ArrayIndexOutofBound Cause by wrong array indexes.


ArrayStoreException Cause by wrong storage of data inside the array.

27 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

FileNotFoundException Cause by an attempt to accessing non existing file.


IOException Cause by IO devices.

OutofMemotyException Cause by memory out of space.

Example of exception handling in java

import java.io.*;
import java.util.scanner.*;

Class Error3
{
public static void main(string args[])
{
float a,b,c;
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
try
{
c=a/b;
System.out.println("Division is "+c);
}
catch(ArithematicException e)
{
System.out.println("Divide by zero");
}
}
}

Multiple catch statement: It is possible to have more than one catch statement in a program the
syntax of multiple catch statement is given below.

try
{
____
____
____
}
catch(Exceptiontype1 object1)
{
____
____
____
}
catch(Exceptiontype2 object2)
{

28 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

____
____
____
}
catch(Exceptiontype3 object3)
{
____
____
____
}

What do you bean by throw, throws and finally?

We have only catching exception that is thrown by java run time system. However it is possible for
our program to throw an exception explicitly using throw statement the syntax for throw statement is

throw throwable_instance;

throwable_instance must be an object the flow of execution stops immediately after the throw
statement. Any sub sequence statements are not executed. The nearest enclosing try block is inspected
and so on if no match found then default exception handler halts the program. For example

import java.io.*;
import java.util.scanner.*;

Class Error4
{
static void display()
{
try
{
throw new NullPointerException("Demo");
}
catch(NullPointerException e)
{
System.out.println("Caught into the method");
rethrow(e);
}
}
public static void main(String args[])
{
try
{
display();
}
catch(NullPointerException e)
{
System.out.println("Caught inside main");
}
}
}

29 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Throws: If a method is capable of causing an exception that it does not handle it must specify this
behavior so that caller of the method can guard themselves against the exception. A throws clause lists the
exception that might throw. This is necessary for all exception except those of type error or run time
exception or any of their subclasses all other exception that a method can throw must be declare in the
throws clause. If they are not a compile time error will produce. The syntax for throws clause is given below

type method_name(parameter) throws exceptionlist


{
Body of the method
}

Here exceptionlist is a comma separated list of exception that a method can throw. Consider the
example

import java.io.*;
import java.util.scanner.*;

Class Error5
{
static void display()
{
System.out.println("Inside display");
throw new IllegalAccessException("Demo");
}
public static void main(String args[])
{
display();
}

This program show compile time error because the program does not specify throws clause. The correct
program is given below

import java.io.*;
import java.util.scanner.*;

Class Error6
{
static void display() throws IllegalAccessException
{
System.out.println("Inside display");
throw new IllegalAccessException("Demo");
}
public static void main(String args[])
{
try
{
display();
}
catch(IllegalAccessException e)
{
System.out.println("Caught inside the main function”);

30 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

}
}

Finally: Java supports another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous catch statements; finally block can be used to handle
any exception generated within a try block it may be added after the try block or after the last catch block
the syntax for finally given below

try
{
____
____
____
}
catch(Exception1)
{
____
____
____
}
catch(Exception2)
{
____
____
____
}
finally
{
____
____
____
}

When finally block is define these is generated to execute regardless of whether or not in execution
is throw automatic.

Define Applet.
Applets are small Java programs that are primarily used in internet computing. They can be
transported over the internet one computer to another and run using applet viewer or any other web
browser that support Java. An Applet like any application program can do many things such as it can
perform arithmetic operation, display graphics, play sounds, accept user input, create animation and play
interactive sound.

Type of Applet
There are types of Applet
(a) Local Applet
(b) Remote Applet
31 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER
JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Local Applet
An Applet developed locally and stored in a local system. When a web page is trying to find a local
Applet it does not need to use the internet and therefore system does not require internet connection. It
simply searches the directory in the local system and locates and load the specify applet.

Remote Applet
A remote applet that is developed by someone and stored on a remote computer connected to the
internet. We can download the remote applet on to our system via internet.
In order to locate remote applet we must know the applet address. This address is known as URL.

Difference between Applet and Application program


Applet Application program
Applet does not use main method for initiating Application program use main method for
the executing of the code. Applet when located initiating the execution of the code.
automatically called certain method of applet
class to start an executing the applet code.
Applet cannot run independently. Application can run dependently.

Applet cannot read from or write to the files in Application program can read from or write to
the local computer. the files in the local computer.
Applet cannot run another application. Application program can run another
application.
Applets are embedded within HTML. Application program are not embedded within
Html.

Life cycle of Applet


Every Java applet inherits in set of default behavior from applet class. As a result when an applet is
loaded it undergoes a series of changes in its state. An applet consists of following states.

1) Born state
2) Running state
3) Idle state
4) Dead or destroyed state
The life cycle of applet is given below

32 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Begin Born Initialization


Applet State State

Start()
Stop()

Idle
Display Running
State
State State

Paint()
Start() Destroy()

Ending Dead
Applet State

Born state
Applet enters the initialization state when it is first loaded. This is achieved by calling the “init()”
method of the applet class the applet is born. At this stage we may do this following
1) Create object needed by the object
2) Set of the initial value
3) Load images and fonts
4) Setup color
The initialization occurs only once in the life cycle. The syntax for init method is given below
Public void init()
{
// Body of the initialization
}

Running state

Applet enter the running state when the system called start the start() method of applet class. This
occurs automatically after the applet is initialization starting can also occurs if the applet is already in stop
state. For e.g. We may leave the web page containing the applet temporarily to another page and return
back to the page. This again starts the applet. Start() method can be called more than one.

Syntax for running state is given below

public void start()


{

33 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

// Body of the start


}

Idle state

An applet becomes idle when it is stopped form running stopping occurs automatically when we
leave the page containing the currently running applet. We can also do so by calling the stop() method.

The syntax for stop method is given below

public void stop()


{
// Body of the stop
}

Dead state

An Applet is said to be dead when it is removed from memory. These occurs automatically by
calling destroy method when we quit the browser like initialization destroying occurs only once in the applet
life cycle. If the applet has created any resources like thread we may override the destroy() method to clean
up this resource.

Syntax for dead state is given below

public void destroy()


{
// Body of the destroy
}

Display state

The Applet moves to the display state whenever it has to perform some output operation. This
happens immediately affect the applet in to the running state. The paint method is called to accomplish to
run.

The syntax to paint is given below

public void paint(Graphics g)


{
// Body of the display
}

What are the steps of creating, developing and testing the java applet?

1) Building an applet code.


2) Creating an executable applet (.class).
3) Designing a web page using HTML tag.
4) Preparing applet tag.
5) Incorporating <APPLET> tag into the web page.

34 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

6) Creating HTML file.


7) Testing the applet code.

import java.awt.*;
import java.applet.*;

public class hellow java extends applet


{
string str;
public void init()
{
str=getParameter("String");
if(str==null)
str="Java";
str="Hello"+str;
}
public void paint(Graphics g)
{
g.drwString(str,10,100);
}

<HTML>
<HEAD><TITLE>WELCOME</TITLE></HEAD>
<BODY>
<APPLET CODE=applethellowjava.class HEIGHT=100 WIDTH=100>
<PARAM NAME="string" VALUE="Applet">
</APPLET>
</BODY>
</HTML>

What is interface?

An interface is basically a kind of class like classes. Interface contains methods and variables but
with a major different. The difference is that interface defines only abstract method and final field. This
mean interfaces do not specify any code to implement this method and the data field contains only constant
therefore it is the responsibility of the class that implement an interface to define the code.

The syntax is given below

Interface Interface_name
{
// Variable declaration
// Method declaration
}

Here interface is the keyword “Interface_name” is any valid name.

interface abc
{
Static final int pi=3.14;
float compute(float, float); // declaration
void show();
35 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER
JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Static string x="Fan"; //Declaration


}

Difference between class and interface

Class Interface
The member of the class can be constant or The member of the interface is always declaring as
variable. constant and there values are final.
The method in an interface is abstract in nature that
The class definition can be contains the code for is there is no code associated with the method it is
each method that is method can be abstract. later defined by the class that implements the
interface.
It cannot be declare objects. It can only be inherited
It can be create use to create objects.
by a class.
Class can use public private and protected. Inheritance only use public

Give an example of interface

WAP to find area of a circle and area of rectangle

import java.io.*;
import java.util.scanner.*;

interface Area
{
Static float final pi=3.14F;
float compute(float, float);
}
class Rectangle implements Area
{
float compute(float x, float y);
{
return(x*y);
}
}
class Circle implements Area
{
float compute(float x, float y);
{
return(pi*x*x);
}
}
class Interfacetest
{
public static void main(String args[])
{
Rectangle rect=new Ractangle();
Circle cir=new Circle();
Area area;
area=rect;
System.out.println("Area of recangle is "+area.compute(5.5,6.5));

36 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

area=cir;
System.out.println("Area of circle is "+area.compute(5.5,0));
}
}

WAP to add and subtract to integer


import java.io.*;
import java.util.scanner.*;

interface Calc
{
int compute(int.int);
}
class add implements Calc
{
int compute(int x.int y)
{
return(x+y);
}
}
class Sub implements Calc
{
int compute(int x.int y)
{
return(x-y);
}
}
class display
{
public static void main(String args[])
{
add a=new add();
sub s=new sub();
Calc calc;
clac=a;
System.out.println("Addition is "+a.compute(6,3));
calc=s;
System.out.println("Subtraction is "+s.compute(6,3));
}
}

There is another process to solve this


import java.io.*;
import java.util.scanner.*;

interface Calc
{
final int a=10,b=20;
void display();
}
class add implements Calc
{
Void display()
{

37 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Int c=a+b;
System.out.println("Addition is "+c);
}
}
class add implements Calc
{
Void display()
{
Int d=a-b;
System.out.println("Subtraction is "+d);
}
}
class Interfacetest
{
public static void main(String args[])
{
add a=new add();
sub s=new sub();
Calc cl;
cl=A;
A.display();
cl=B;
B.display();
}
}

How to implement multiple interfaces in java?

Interfaces can be use to declare a set of constant that can be use in different classes. This is similar
to creating header files in C++ to contain a large number of constant. Since such interfaces do not contain
methods there is no need to worry about implementing any method the constant values will be available to
any class that implement to the interface. The following program shows multiple inheritance can be
implemented using interface.

import java.io.*;
import java.util.scanner.*;

class student
{
int rollno;
void getnumber(int x)
{
rollno=n;
}
void putnumber()
{
System.out.println("Rollno is "+rollno);
}
}
class test extends students
{
float part1,part2;
void getMark(float m1,float m2)
{

38 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

part1=m1;
part2=m2;
}
void putmark()
{
System.out.println("Marks are "+m1,+m2);
}
}
Interface sports
{
float sportwt=60;
void putwt();
}
class Results extends test implements sports
{
public void putwt()
{
System.out.println("Weight is "+sportwt);
}
void display()
{
float total=part1+part2+sportwt;
putnumber();
putmark();
System.out.println("Total marks is "+total);
}
}
class MultipleInheritance
{ Getnumber
public static void main(String args[]) putnumber
{
Results R=new Results();
R.getnumber(22);
R.getmarks(90,92); Extends
R.display(); Interface
}
} Getmarks Sportwt=60
Putmarks Putwt()
Getnumber
putnumber

Extends
Implement

Getmarks
Putmarks
Getnumber
Putnumber
display

39 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Difference between method overloading and method overriding

Method overloading(Compile time polymorphism) Method overriding(Run time polymorphism)


It is use to provide specific implementation of the
It is use to increase the readability of the program.
method that is already provided by super class.
It is perform within class. It is occurs in two classes.
Parameter must be different. Parameter must be same.
It is an example of compile time polymorphism. It is an example of run time polymorphism.

Signature is different. Signature is same.

class ABCD
{
class ABCD
void add()
{
{
int add(int, int)
___
{
___
___
}
___
}
}
class XYZ extends ABCD
int add(float, float)
{
{
void add()
___
{
___
___
}
___
}
}
}

Short note on wrapper class

Wrapper class is some primitive data types. Wrapper class has number of unique method for
handling primitive data type and object. Some of the wrapper classes are

Simple type Wrapper class


boolean Boolean
char Character
int Integer

float Float

long Long
double Double

The following table shows how to convert primitive number to object number using constructor

40 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Constructor Action
Integer Intval=new Integer(i); Convert integer to integer object

Float floatval=new Float(f); Convert float to float object

Class ABCD
{
public void static(string args[])
{
Integer M=new Integer(5);
}
}

The following table shows how to convert object number to primitive number

Method calling Action


int i=M.nextInt(); or
Object to integer conversion
M.intValue();
float f= M.floatValue(); Object to float conversion

double d= M.doubleValue(); Object to double conversion

long f= M.longValue(); Object to long conversion

Display the triangle as follows

2 3

4 5 6

7 8 9 10

import java.io.*;
import java.util.scanner.*;

class triangle
{
public static void main(String args[])
{
System.out.println("Enter a limit");
int n,k=1;
Scanner s=new Scanner(System.in);
n=s.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{

41 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

System.out.print(" "+k);
k++;
}
System.out.println("");
}
}
}

WAP to convert given no of days into months

import java.io.*;
import java.util.scanner.*;

class MonthsDays
{
public static void main(String args[])
{
System.out.println("Enter days");
int n,m,d;
Scanner s=new Scanner(System.in);
n=s.nextInt();
m=n/30;
d=n%30;
System.out.println("There are "+m+" Months");
System.out.println("There are "+d+" Days");
}
}

WAP to find out the result of the series 1+1/2+1/3+1/4………


import java.io.*;
import java.util.scanner.*;

class series
{
public static void main(String args[])
{
System.out.println("Enter the limit: ");
float r=0;
int n;
Scanner s=new Scanner(System.in);
n=s.nextInt();
for(int i=1;i<=n;i++)
{
r=r+1/i;
}
System.out.println("Result of the series is "+r);
}
}

WAP input 3 integers and find the largest number


import java.io.*;
import java.util.scanner.*;

class series

42 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

{
public static void main(String args[])
{
System.out.println("Enter three numbers: ");
int a,b,c;
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
if(a>b)
{
if(a>c)
{
System.out.println("Largest is "+a);
}
else
{
System.out.println("Largest is "+c);
}
}
else
{
if(b>c)
{
System.out.println("Largest is "+b);
}
else
{
System.out.println("Largest is "+c);
}
}
}
}

WAP to reads the radius of circle then compute area


import java.io.*;
import java.util.scanner.*;

class area
{
public static void main(String args[])
{
System.out.println("Enter the radius: ");
float r,a;
Scanner s=new Scanner(System.in);
r=s.nextFloat();
a=r*r*3.14;
System.out.println("Area is "+a);
}
}

What is package?

43 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Packages are java’s way of grouping of grouping a variety of classes and / or interfaces together
packages is a concept similar to class libraries in other languages it is like header file. Packages act as a
container for classes. Packages has the following benefits

1) Classes contained in the packages in other program can be easily use.


2) In packages classes can be unique compared with classes in other packages that is two classes
and two different packages can have the same name.
3) Packages provide a way to hide classes thus preventing other program or packages for accessing
classes that are mean for internal use only.
4) Packages also provide a way of separating design from coding.

Types of packages

There are two types of packages

1) User defined packages


2) System defined packages

Describe different Java API packages provide a number of classes grouped into different packages
according to functionality. Some of the packages are

Java

lang util io awt net applet

Lang (java.lang): language support classes. This class java compiler itself uses and therefore they are
automatically imported. They are mainly use for string, math function, thread and exception.

Util (java.util): Languages supports utility classes for vectors random number # hash labels etc.

Io (java.io): Input output classes. They provided facilities for input output of data.

Awt (java.awt): Set of classes for graphical user interfaces they include window, menu bar, listbox,
command button etc.

Net (java.net): Set of classes for networking they include classes for communicating with local computer as
well as with internet server.

Applet (java.applet): Classes for creating and implementation of applet. The following diagram show how
a package can be represented in hierarchical way.

44 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

Java package
Method of awt
Font classes

Color
Awt classes

img

Java.lang.math.sqrt() Method

class

Sub class

package

How to create a package?

We must declare the name of the package using package keyword followed by package name. For
example package Firstpackage;

public class Firstclass


{
// Body of the class
}

Here, package name is Firstpackage and the class Firstclass is now considered a part of this
package this listing would saved as a file called Firstclass.java and located in as directory named
Firstpackage folder. We can import this package in any java program.

45 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

import Firstpackage.Firstclass

Steps of creating packages are

1) Declare the package at the beginning of the file.


2) Define the class that is to be put in the package and declare it in public.
3) Creating a sub directory under the directory where the main source tile is store.
4) Store the listing as the class_name.java file in the sub directory created.
5) Compile the file and therefore it create .class file.

Consider an example

package package1;
public class classA
{
public void displayA()
{
System.out.println("Class A");
}
}

save it as .class file

The source file name should be classA.java and store inside sub directory package1.
The result of the compilation classA.class file is created. Now we can use the package by another
program.

Import package1.classA Import package1


Class packageTest Public ClassA
{ {
Public static void main(string args[]) Public void displayA()
{ {
classA objA=new classA(); System.out.println(“ClassA”);
objA.displayA(); }
} }
}

Import package1.classA
Class packageTest
{
Public static void main(string args[])
{
classA objB=new classA();
objB.displayA();
}
}

46 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NATH 9038664188

WAP using packages which will store addition subtraction two number using
constructor then call the member function to add or subtract for another program
package package2;

public class classA


{
protected int m=30, n=20;
classA(int a,int b)
{
m=a;
n=b;
}
public int add()
{
return(m+n);
}
public int sub()
{
return(m-n);
}
}
import package2.classA
class package3
{
public static void main(String args[])
{
classA objA=new classA(5,3);
int x=objA.add();
int y=objA.sub();
System.out.println("Addition is "+x);
System.out.println("Subtraction is "+y);
}
}

47 DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Java remaining questions

1.Write a program to create a window and set its title with "IETE" using
AWT.(WBUT 2013)
Sol:

import java.awt.*;
import java.awt.event.*;
class example1 extends Frame
{
public example1(String title)
{
super(title);
MyWindowAdapter adapter=new MyWindowAdapter(this);
addWindowListener(adapter);
}
class MyWindowAdapter extends WindowAdapter
{
example1 e1;
public MyWindowAdapter(example1 e1)
{
this.e1=e1;
}
public void windowClosing(WindowEvent ae)
{
e1.dispose();
}
}
public static void main(String args[])
{
Frame f1=new Frame("IETE" );
f1.setVisible(true);
f1.setSize(200,200);
}
}

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

2. How will you call parameterized constructor and override method from
parent class in sub-class ?
(WBUT 2013)
or

In Java, explain how to call a constructor from another. (WBUT 2013)

Sol:
Definition of Constructor:
A constructor is a special member function whose have the same name as
the class name, but the function (constructor) never returns any value. A
constructor initializes an objects immediately upon creation. Once defined,
the constructor is automatically called immediately after the object is
created.

Parameterized Constructor:
Passing arguments to the function is called parameterized function.
Similarly passing arguments to the constructor is called parameterized
constructor.

Method overriding:
When a method in a subclass has the same name and type signature
as a method in its super class , then the method in the subclass is said to be
override the method in the super class.

Describe all above feature with the following example:

class A
{

int x,y;
A()
{ // zero argument constructor
}
A(int i,int j) // parameterized constructor
{
x=i;y=j;
}
void show() // override methods by subclass version

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

{
System.out.println("x="+x+" y="+y);
}
}
class B extends A
{
int z;
B(int i, int j, int k) // parameterized constructor
{
super(i,j);
z=k;
}
void show()
{
System.out.println("z="+z);
}
}

class override
{
public static void main(String args[])
{
B subob=new B(1,2,3); // call constructor by creating objects
subob.show(); // this calls subclass version
}
}

3. Indicate the difference between PATH and CLASSPATH. (wbut 2013)

1)Main difference between PATH and CLASSPATH is that PATH is an environment variable which
is used to locate JDK binaries like "java" or "javac" command used to run java program and compile
java source file. On the other hand CLASSPATH environment variable is used by System or
Application ClassLoader to locate and load compile Java bytecodes stored in .class file.

2) In order to set PATH in Java you need to include JDK_HOME/bin directory in PATH environment
variable while in order to set CLASSPATH in Java you need to include all those directory where you
have put either your .class file or JAR file which is required by your Java application.

3) Another significant difference between PATH and CLASSPATH is that PATH can not be
overridden by any Java settings but CLASSPATH can be overridden by providing command line

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

option -classpath or -cp to both "java" and "javac" commands or by using Class-Path attribute in
Manifest file inside JAR archive.

4) PATH environment variable is used by operating system to find any binary or command typed in
shell, this is true for both Windows and Linux environment while CLASSPATH is only used by Java
ClassLoaders to load class files.

4.Illustrate the uses of 'this' and 'super' keywords. (WBUT 2013)


“this” Keyword:
Sometimes a method will need to refer to the object that invoked it. To
allow this, Java defines the this keyword. this can be used inside any method
to refer to the current object. That is, this is always a reference to the object
on which the method was invoked. We can use this anywhere a reference to
an object of the current class’s type is permitted.

From above example:


B(int i, int j, int k) // parameterized constructor
{
this.x=i;
this.y=j;
this.z=k;
}

“super” keyword:
super has two general forms: i) The first calls the superclass’s
constructor. ii) super used to access a member of the superclass that has been
hidden by a member of a subclass.
From above example:
B(int i, int j, int k) // parameterized constructor
{
super(i,j);
z=k;
}

Class A{
int i;
}
class B extends A{
int i;

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

B(int i1,int j1)


{
super.i=i1;
i=j1;
}
}

5. What are Adapter classes? (WBUT 2013)


Java provides a special feature, called an adapter class that can simplify
the creation of event handles in certain situations. An adapter class provides
an empty implementation of all methods in an event listener interface.
Adapter classes are useful when we want to receive and process only some
the events that are handled by a particular event listener interface. We can
define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which we are interested.
Ex of adapter class:
i) Component Adapter
ii) Container Adapter
iii) Focus Adapter
iv) Key Adapter
v) Mouse Adapter
vi) Window Adapter

NB: Example is given in first program.

8. What is the package? What is the difference between throw and


throws keywords? (WBUT 2012)
Sol:
1st Part:
Packages are the containers for the classes that are used to keep the class
name space compartmentalized. Packages are stored in a hierarchical
manner and are explicitly imported into new class definitions.
To create the packages use the “package” command as follows:
package p1;
Here p1 is name of the package and we insert the package p1 in the program
with the import statements as follows:
import p1;

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Some packages are


i) import java.awt.*;
ii) import java.awt.event.*;
iii) import java.applet.*;

2nd Part:
throw:

User can catching exceptions that are thrown by the Java run – time
system. However, it is possible for program to throw an exception explicitly,
using the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass
of Throwable. There is two ways obtain a Throwable object: using a
parameter into a catch clause, or creating one with the new operator.
The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.

Class bug extends Exception


{
………//statement
}
……
…….
int i=10;
try
{
if(i<12) throw new OutOfRange();
}catch(OutOfRange e)
{
…….//statement
}

3rd Part:
throws:

If a method is capable of causing an exception that it does not handle, it


must specify this behavior so that callers of the method can guard
themselves against that exception. We do this by including a throws clause
in the method declaration. A throw clause lists the types of exception that a

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

method might throw. This is necessary for all exception, except those of type
Error or RuntimeException or any of their subclasses. All other exceptions
that a method can throw must be declared in the throws clause. If they are
not, a compile – time error will result.
type method – name (parameter list) throws exception list
{
// body of the mewth

Explain the difference between Integer and int in java. Wbut


2013
The following are the differences:

- Integer is a wrapper class, where as int is a primitive data type.

- Integer can be used as an argument to a method which requires an object, where as int can
be used as an argument to a method which requires an integer value, that can be used for
arithmetic expression.

- The variable of int type is mutable, unless it is marked as final. Integer class contains one
int value and are immutable.

public static void main(string args[]) Explanation. wbut 2013

Public : is an Access Modifier, which defines who can access this Method. Public means
that this Method will be accessible by any Class(If other Classes are able to access this
Class.).

Static : is a keyword which identifies the class related thing. This means the given
Method or variable is not instance related but Class related. It can be accessed without
creating the instance of a Class.

Void : is used to define the Return Type of the Method. It defines what the method can
return. Void means the Method will not return any value.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

main: is the name of the Method. This Method name is searched by JVM as a starting
point for an application with a particular signature only.

String args[] : is the parameter to the main Method.

How does java implements platform independence? Wbut 2013

platform independent means, the compiled program can be run on any operating system, JAVA is called so
since it generates the byte code which can be run on any
environment.
JAVA is both platform independent and platform dependent

JAVA
platform dependent means the JVM dependent
JAVA platform independent means the compiled code can be executed any where

But here the context we are discussing is based on the code so


platform independent
means, the compiled program can be run on existing operating system, but not on other operating system
like
C, C++ have the disadvantage that they might got executed in another system.

Instance variables vs class variable wbut 2013

Instance variables are declared in a class, but outside a method, constructor or any block.

When a space is allocated for an object in the heap, a slot for each instance variable value
is created.

Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.

Instance variables can be declared in class level before or after use.

Access modifiers can be given for instance variables.

The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However
visibility for subclasses can be given for these variables with the use of access modifiers.

Instance variables have default values. For numbers the default value is 0, for Booleans it
is false and for object references it is null. Values can be assigned during the declaration
or within the constructor.

Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class ( when instance variables are given
accessibility) should be called using the fully qualified name .
ObjectReference.VariableName.

Example:

import java.io.*;

public class Employee{

// this instance variable is visible for any child class.

public String name;

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

// salary variable is visible in Employee class only.

private double salary;

// The name variable is assigned in the constructor.

public Employee (String empName){

name = empName;

// The salary variable is assigned a value.

public void setSalary(double empSal){

salary = empSal;

// This method prints the employee details.

public void printEmp(){

System.out.println("name : " + name );

System.out.println("salary :" + salary);

public static void main(String args[]){

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Employee empOne = new Employee("amit");

empOne.setSalary(1000);

empOne.printEmp();

This would produce the following result:

name : amit

salary :1000.0

Class/static variables:

Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.

There would only be one copy of each class variable per class, regardless of how many
objects are created from it.

Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never
change from their initial value.

Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.

Static variables are created when the program starts and destroyed when the program
stops.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.

Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally values can be assigned in special
static initializer blocks.

Static variables can be accessed by calling with the class name


ClassName.VariableName.

When declaring class variables as public static final, then variables names (constants) are
all in upper case. If the static variables are not public and final the naming syntax is the
same as instance and local variables.

Example:

import java.io.*;

public class Employee{

// salary variable is a private static variable

private static double salary;

// DEPARTMENT is a constant

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

public static final String DEPARTMENT = "Development ";

public static void main(String args[]){

salary = 1000;

System.out.println(DEPARTMENT + "average salary:" + salary);

This would produce the following result:

Development average salary:1000

What is JAR? OPTIONS IN JAR .WBUT 2013

JAR files are packaged with the ZIP file format, so you can use them for
tasks such as lossless data compression, archiving, decompression, and
archive unpacking. These tasks are among the most common uses of JAR
files, and you can realize many JAR file benefits using only these basic
features.

Even if you want to take advantage of advanced functionality provided by


the JAR file format such as electronic signing, you'll first need to become
familiar with the fundamental operations.

To perform basic tasks with JAR files, you use the Java Archive Tool
provided as part of the Java Development Kit (JDK). Because the Java

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Archive tool is invoked by using the jar command, this tutorial refers to it as
'the Jar tool'.

Options
Use the following options to customize how the JAR file is created, updated,
extracted, or viewed:

e
Sets the class specified by the entrypoint operand to be the entry point
for a standalone Java application bundled into an executable JAR file.
The use of this option creates or overrides the Main-Class attribute
value in the manifest file. The e option can be used when creating (c)
or updating (u) the JAR file.

For example, the following command creates the Main.jar archive


with the Main.class file where the Main-Class attribute value in the
manifest is set to Main:

jar cfe Main.jar Main Main.class


The Java Runtime Environment (JRE) can directly call this
application by running the following command:

java -jar Main.jar


If the entry point class name is in a package, then it could use either
the dot (.) or slash (/) as the delimiter. For example, if Main.class is in
a package called mydir, then the entry point can be specified in one of
the following ways:

jar -cfe Main.jar mydir/Main mydir/Main.class


jar -cfe Main.jar mydir.Main mydir/Main.class

f
Sets the file specified by the jarfile operand to be the name of the JAR
file that is created (c), updated (u), extracted (x) from, or viewed (t).
Omitting the f option and the jarfile operand instructs
the jar command to accept the JAR file name from stdin (for x and t)
or send the JAR file to stdout (for c and u).

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

ROLE OF GARBAGE COLLECTOR IN JAVA WBUT 2013

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically.


In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.

It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.

How can an object be unreferenced?

There are many ways:

By nulling the reference

By assigning a reference to another

By annonymous object etc.

1) By nulling a reference:

Employee e=new Employee();

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

e=null;

2) By assigning a reference to another:

Employee e1=new Employee();

Employee e2=new Employee();

e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:

new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:

protected void finalize(){}

Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.

public static void gc(){}

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Garbage collection is performed by a daemon thread called Garbage Collector(GC). This


thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java

public class TestGarbage1{

public void finalize(){System.out.println("object is garbage collected");}

public static void main(String args[]){

TestGarbage1 s1=new TestGarbage1();

TestGarbage1 s2=new TestGarbage1();

s1=null;

s2=null;

System.gc();

SHORT NOTE ON

APPLET VIEWER ( WBUT 2013)

Applet viewer tool creates a frame and displays the output of applet in the frame.You can
also create your frame and display the applet output.

AppletViewer is a standalone command-line program from Sun to run Java applets. Appletviewer is
generally used by developers for testing their applets before deploying them to a website.

As a Java developer, it is a preferred option for running Java applets that do not involve the use of
a web browser. Even though the applet viewer logically takes the place of a web browser, it functions

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

very differently from a web browser. The applet viewer operates on HTML documents, but all it looks
for is embedded applet tags; any other HTML code in the document is ignored. Each time the applet
viewer encounters an applet tag in an HTML document, it launches a separate applet viewer window
containing the respective applet. The only drawback to using the applet viewer is that it will not show
how an applet will run within the confines of a real web setting. Because the applet viewer ignores all
HTML codes except applet tags, it does not even attempt to display any other information contained in
the HTML document.

Example that works like appletviewer tool

Let's see the simple example that works like appletviewer tool. This example displays
applet on the frame.

import java.applet.Applet;

import java.awt.Frame;

import java.awt.Graphics;

public class MyViewer extends Frame{

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

Class c=Class.forName(args[0]);

MyViewer v=new MyViewer();

v.setSize(400,400);

v.setLayout(null);

v.setVisible(true);

Applet a=(Applet)c.newInstance();

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

a.start();

Graphics g=v.getGraphics();

a.paint(g);

a.stop();

//simple program of applet

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){g.drawString("Welcome",50, 50);}

JVM (WBUT 2013)

JVM (Java Virtual Machine)

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides


runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).

What is JVM?

It is:

A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.

An implementation Its implementation is known as JRE (Java Runtime Environment).

Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.

What it does?

The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Register set

Garbage-collected heap

Fatal error reporting etc.

Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.

Jvm Internal

1) Classloader:

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area:

Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.

3) Heap:

It is the runtime data area in which objects are allocated.

4) Stack:

Java Stack stores frames.It holds local variables and partial results, and plays a part in
method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.

5) Program Counter Register:

PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.

6) Native Method Stack:

It contains all the native methods used in the application.

7) Execution Engine:

It contains:

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

1) A virtual processor

2) Interpreter:Read bytecode stream then execute the instructions.

3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts


of the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation.Here the term ?compiler? refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.

STRING IN JAVA WBUT 2014

Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

String Methods:
Here is the list of methods supported by String class:

SN Methods with Description

1
char charAt(int index)

Returns the character at the specified index.

2
int compareTo(Object o)

Compares this String to another Object.

3
int compareTo(String anotherString)

Compares two strings lexicographically.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

4
int compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences.

5
String concat(String str)

Concatenates the specified string to the end of this string.

6
boolean contentEquals(StringBuffer sb)

Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.

Difference Between Abstract Class and


Interface in Java WBUT
abstract Classes Interfaces

abstract class can extend only one class interface can extend any number
1
or one abstract class at a time of interfaces at a time

abstract class can extend from a class or interface can extend only from an
2
from an abstract class interface

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

abstract class can have both abstract interface can have only abstract
3
and concrete methods methods

A class can extend only one abstract A class can implement any
4
class number of interfaces

In abstract class keyword ‘abstract’ is In an interface keyword ‘abstract’

5 mandatory to declare a method as an is optional to declare a method as

abstract an abstract

abstract class can have protected , Interface can have only public
6
public and public abstract methods abstract methods i.e. by default

abstract class can have static, final or interface can have only static

7 static final variable with any access final (constant) variable i.e. by

specifier default

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Difference between String and StringBuffer


WBUT 2011
There are many differences between String and StringBuffer. A list of differences between String and
StringBuffer are given below:

No. String StringBuffer

1) String class is immutable. StringBuffer class is mutable.

2) String is slow and consumes more memory when you StringBuffer is fast and consumes less
concat too many strings because every time it creates memory when you cancat strings.
new instance.

3) String class overrides the equals() method of Object StringBuffer class doesn't override the
class. So you can compare the contents of two strings by equals() method of Object class.
equals() method.

JAVA PROGRAM TO ADD TWO STRING

Java String Concat Example.

This Java String concat example shows how to concat String in Java.

*/

public class JavaStringConcat {

public static void main(String args[]){

/*

* String concatenation can be done in several ways in Java.

*/

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

String str1 = "Hello";

String str2 = " World";

//1. Using + operator

String str3 = str1 + str2;

System.out.println("String concat using + operator : " + str3);

//2. Using String.concat() method

String str4 = str1.concat(str2);

System.out.println("String concat using String concat method : " + str4);

//3. Using StringBuffer.append method

String str5 = new StringBuffer().append(str1).append(str2).toString();

System.out.println("String concat using StringBuffer append method : " + str5);

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Serialization and Deserialization in Java wbut 2011


Serialization is a process by which we can store the state of an object into any
storage medium. We can store the state of the object into a file, into a database
table etc. Deserialization is the opposite process of serialization where we
retrieve the object back from the storage medium

Java provides a mechanism, called object serialization where an object can be


represented as a sequence of bytes that includes the object's data as well as information
about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its data
can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain


the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data
types, but one method in particular stands out:

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object:

public final Object readObject() throws IOException, ClassNotFoundException

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

This method retrieves the next Object out of the stream and deserializes it. The return
value is Object, so you will need to cast it to its appropriate data type.

To demonstrate how serialization works in Java, I am going to use the Employee class
that we discussed early on in the book. Suppose that we have the following Employee
class, which implements the Serializable interface:

public class Employee implements java.io.Serializable

public String name;

public String address;

public transient int SSN;

public int number;

public void mailCheck()

System.out.println("Mailing a check to " + name + " " + address);

Notice that for a class to be serialized successfully, two conditions must be met:

 The class must implement the java.io.Serializable interface.

 All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.

If you are curious to know if a Java Standard Class is serializable or not, check the
documentation for the class. The test is simple: If the class implements
java.io.Serializable, then it is serializable; otherwise, it's not.

Serializing an Object:
The ObjectOutputStream class is used to serialize an Object. The following
SerializeDemo program instantiates an Employee object and serializes it to a file.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

When the program is done executing, a file named employee.ser is created. The program
does not generate any output, but study the code and try to determine what the program
is doing.

Note: When serializing an object to a file, the standard convention in Java is to give the
file a .ser extension.

import java.io.*;

public class SerializeDemo

public static void main(String [] args)

Employee e = new Employee();

e.name = "Reyan Ali";

e.address = "Phokka Kuan, Ambehta Peer";

e.SSN = 11122333;

e.number = 101;

try

FileOutputStream fileOut =

new FileOutputStream("/tmp/employee.ser");

ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(e);

out.close();

fileOut.close();

System.out.printf("Serialized data is saved in /tmp/employee.ser");

}catch(IOException i)

i.printStackTrace();

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Deserializing an Object:
The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program. Study the program and try to determine its output:

import java.io.*;

public class DeserializeDemo

public static void main(String [] args)

Employee e = null;

try

FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");

ObjectInputStream in = new ObjectInputStream(fileIn);

e = (Employee) in.readObject();

in.close();

fileIn.close();

}catch(IOException i)

i.printStackTrace();

return;

}catch(ClassNotFoundException c)

System.out.println("Employee class not found");

c.printStackTrace();

return;

System.out.println("Deserialized Employee...");

System.out.println("Name: " + e.name);

System.out.println("Address: " + e.address);

System.out.println("SSN: " + e.SSN);

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

System.out.println("Number: " + e.number);

This would produce the following result:

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

Here are following important points to be noted:

 The try/catch block tries to catch a ClassNotFoundException, which is declared by the


readObject() method. For a JVM to be able to deserialize an object, it must be able to find
the bytecode for the class. If the JVM can't find a class during the deserialization of an
object, it throws a ClassNotFoundException.

 Notice that the return value of readObject() is cast to an Employee reference.

 The value of the SSN field was 11122333 when the object was serialized, but
because the field is transient, this value was not sent to the output stream. The
SSN field of the deserialized Employee object is 0.

 (Java Event Handling) wbut 2009


Changing the state of an object is known as an event. For example, click on button, dragging mouse etc.
The java.awt.event package provides many event classes and Listener interfaces for event handling.

Event classes and Listener interfaces:


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Implement the Listener interface and overrides its methods


2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods. For
example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

JRE (Java Runtime Environment) wbut 2011

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Java Runtime Environment contains JVM, class libraries, and other supporting
files. It does not contain any development tools such as compiler, debugger,
etc. Actually JVM runs the program, and it uses the class libraries, and other
supporting files provided in JRE. If you want to run any java program, you
need to have JRE installed in the system

Runtime Polymorphism or Dynamic method dispatch (


wbut 2011)
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at
runtime. This is how java implements runtime polymorphism. When an overridden method is called
by a reference, java determines which version of that method to execute based on the type of object it
refer to. In simple words the type of object which it referred determines which version of overridden
method will be called.

Upcasting

When Parent class reference variable refers to Child class object, it is known as Upcasting

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Example
class Game

public void type()

{ System.out.println("Indoor & outdoor"); }

Class Cricket extends Game

public void type()

{ System.out.println("outdoor game"); }

public static void main(String[] args)

Game gm = new Game();

Cricket ck = new Cricket();

gm.type();

ck.type();

gm=ck; //gm refers to Cricket object

gm.type(); //calls Cricket's version of type

Output:

Indoor & outdoor

Outdoor game

Outdoor game

Notice the last output. This is because of gm = ck; Now gm.type() will call Cricket version of type
method. Because here gm refers to cricket object.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Q. Difference between Static binding and Dynamic binding in java ?

Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
Static binding uses type(Class) information for binding while dynamic binding uses instance of
class(Object) to resolve calling of method at run-time. Overloaded methods are bonded using static
binding while overridden methods are bonded using dynamic binding at runtime.

Difference between POP & OOP ( wbut 2014)


No Procedure oriented Object oriented
programming (POP) programming (OOP)
1 POP emphasis on OOP emphasis on data
algorithms (procedure) rather than procedure.
2 Large programs are Programs are divided into
divided into smaller objects.
programs known as
functions.
3 They have not facility to They have facility to hide
hide data. data from outside world.
4 Function can transfer Objects can
data from one function to communication with each
another and one form to other using functions.
another form.
5 It does not have powerful It contains powerful
features like operator features like operator
overloading, inheritance overloading, inheritance.
etc.
6 For design program it For design program it uses
uses top-down approach. bottom-up approach.
7 Examples: C, COBOL, Examples: C++
FORTRAN etc.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

Operator in java wbut 2010


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:

 Arithmetic Operators

 Relational Operators

 Bitwise Operators

 Logical Operators

 Assignment Operators

 Misc Operators

Unicode System wbut 2010

Unicode is a universal international standard character encoding that is capable of


representing most of the world's written languages.

Why java uses Unicode System?

Before Unicode, there were many language standards:

ASCII (American Standard Code for Information Interchange) for the United States.

ISO 8859-1 for Western European Language.

KOI-8 for Russian.

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER


JAVA NOTE BY ANANTA DEV PAL EDITED BY SUBHAJIT NATH

GB18030 and BIG-5 for chinese, and so on.

This caused two problems:

A particular code value corresponds to different letters in the various language standards.

The encodings for languages with large character sets have variable length.Some
common characters are encoded as single bytes, other require two or more byte.

To solve these problems, a new language standard was developed i.e. Unicode System.

In unicode, character holds 2 byte, so java also uses 2 byte for characters.

lowest value:\u0000

highest value:\uFFFF

DO NOT USE THIS NOTE WITHOUT THE PERMISSION OF THE OWNER

You might also like