JAVA CMPLT
JAVA CMPLT
2016
JAVA NOTE BY ANANTA DEV PAL 9874040410 EDITED BY SUBHAJIT NAT
NATH 9038664188
JAVA
History of Java
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++ Java
C++ supports operator overloading. Java does not support operator overloading.
overloading
C++
C Java
Features of Java
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.
Java Source Code Java Compiler Byte Code (Machine Independent Code)
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.
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.
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 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.
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 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.
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
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.
(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.
6 Byte code
5 3
Java web browser
Applet tag HTML
document
7
Request
2
Output 1 Web Browser
User
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);
}
}
import java.util.Scanner.*;
import java.io.*;
Class even
{
public static void main(String args[])
{
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);
}
}
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)
{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("Number is not prime.");
}
else
{
System.out.println("Number is prime.");
}
}
}
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;
}
}
}
}
}
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
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
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
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.
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
Multilevel inheritance
In this type of inheritance sub class inherit the properties of another sub class.
A B C
Hierarchical inheritance
In this type of inheritance many sub classes can be created from one single super class.
B C D
Multiple inheritances are not supports in java. However it is implements with the help of interface.
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);
}
}
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");
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();
}
}
---
}
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,
WAP to implement abstract class in abstract method to calculate area of a circle, rectangle and
square
}
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++.
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,
Main() main()
{ {
}
Thread
}
End
Single Thread
Thread A Thread B Thread C
During the life cycle of thread there are many state it can enter the include
start
stop
Queue
Active Runnable
Running Dead
state state stop
state
Suspend()
resume() stop
sleep()
notify()
wait()
Blocked 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
New Born
Start Stop
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 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()
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)
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()
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.
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.
It is less expensive in terms of context switching. It is more expensive in terms of context switching.
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.*;
{
public static void main(string args[])
{
A a=new A();
B b=new B();
C c=new C();
a.start();
b.start();
c.start();
}
}
C c=new C();
a.start();
b.start();
c.start();
}
}
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.*;
{
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
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
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.
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[])
{
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
Try block
Catch the
exception and
Display it
Exception Meaning
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)
{
____
____
____
}
catch(Exceptiontype3 object3)
{
____
____
____
}
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");
}
}
}
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
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”);
}
}
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.
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.
1) Born state
2) Running state
3) Idle state
4) Dead or destroyed state
The life cycle of applet is given below
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.
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.
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.
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.
What are the steps of creating, developing and testing the java applet?
import java.awt.*;
import java.applet.*;
<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.
Interface Interface_name
{
// Variable declaration
// Method declaration
}
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
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
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));
area=cir;
System.out.println("Area of circle is "+area.compute(5.5,0));
}
}
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));
}
}
interface Calc
{
final int a=10,b=20;
void display();
}
class add implements Calc
{
Void display()
{
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();
}
}
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)
{
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
class ABCD
{
class ABCD
void add()
{
{
int add(int, int)
___
{
___
___
}
___
}
}
class XYZ extends ABCD
int add(float, float)
{
{
void add()
___
{
___
___
}
___
}
}
}
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
float Float
long Long
double Double
The following table shows how to convert primitive number to object number using constructor
Constructor Action
Integer Intval=new Integer(i); Convert integer to integer 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
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++)
{
System.out.print(" "+k);
k++;
}
System.out.println("");
}
}
}
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");
}
}
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);
}
}
class series
{
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);
}
}
}
}
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?
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
Types of 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 (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.
Java package
Method of awt
Font classes
Color
Awt classes
img
Java.lang.math.sqrt() Method
class
Sub class
package
We must declare the name of the package using package keyword followed by package name. For
example package Firstpackage;
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.
import Firstpackage.Firstclass
Consider an example
package package1;
public class classA
{
public void displayA()
{
System.out.println("Class A");
}
}
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
Class packageTest
{
Public static void main(string args[])
{
classA objB=new classA();
objB.displayA();
}
}
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;
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);
}
}
2. How will you call parameterized constructor and override method from
parent class in sub-class ?
(WBUT 2013)
or
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.
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
{
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
}
}
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
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.
“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;
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.
3rd Part:
throws:
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
- 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 : 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.
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.
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
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.
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.
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.*;
name = empName;
salary = empSal;
empOne.setSalary(1000);
empOne.printEmp();
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.
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.
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.*;
// DEPARTMENT is a constant
salary = 1000;
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.
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
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.
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).
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.
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.
1) By nulling a reference:
e=null;
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:
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.
s1=null;
s2=null;
System.gc();
SHORT NOTE ON
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
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.
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;
Class c=Class.forName(args[0]);
v.setSize(400,400);
v.setLayout(null);
v.setVisible(true);
Applet a=(Applet)c.newInstance();
a.start();
Graphics g=v.getGraphics();
a.paint(g);
a.stop();
import java.applet.Applet;
import java.awt.Graphics;
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).
What is JVM?
It is:
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?
Loads code
Verifies code
Executes code
Memory area
Register set
Garbage-collected heap
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
Jvm Internal
1) Classloader:
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:
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.
PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.
7) Execution Engine:
It contains:
1) A virtual processor
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:
1
char charAt(int index)
2
int compareTo(Object o)
3
int compareTo(String anotherString)
4
int compareToIgnoreCase(String str)
5
String concat(String str)
6
boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.
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
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
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
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.
This Java String concat example shows how to concat String in Java.
*/
/*
*/
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.
The ObjectOutputStream class contains many write methods for writing various data
types, but one method in particular stands out:
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:
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:
Notice that for a class to be serialized successfully, two conditions must be met:
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.
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.*;
e.SSN = 11122333;
e.number = 101;
try
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
out.writeObject(e);
out.close();
fileOut.close();
}catch(IOException i)
i.printStackTrace();
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.*;
Employee e = null;
try
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
c.printStackTrace();
return;
System.out.println("Deserialized Employee...");
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
For registering the component with the Listener, many classes provide the registration methods. For
example:
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){}
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
Upcasting
When Parent class reference variable refers to Child class object, it is known as Upcasting
Example
class Game
{ System.out.println("outdoor game"); }
gm.type();
ck.type();
Output:
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.
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.
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
ASCII (American Standard Code for Information Interchange) for the United States.
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