Java Program2 PDF
Java Program2 PDF
Java Program2 PDF
Features of Java:
1. Simple : Java is easy to learn and use. There is no surprising feature in Java.
2. Object Oriented: In Java everything depends upon object.
3. Distributed: Java is designed to support various levels of network connectivity, it
supports TCP/IT protocol. They can open and access remote objects on the
internet.
4. Interpreted : Java is compiled to bytecode which are interpreted by Java run time
environment.
5. Robust: Java is strictly typed language. It not only performs code check at compile
time but also at run time.
6. Secure
7. Architecture Neutral: Java bytecode can be interpreted by any system that
implements JVM. So Java applications are able to run on most platforms.
8. Dynamic:Java supports dynamic loading of classes(Load on demand), automatic
memory management(garbage collection)
9. Multithreaded
Array in Java:
type name[]=new type[size];
int a[]=new int[10];
int a[]={2,4,6,7,};
Arrays are dynamically allocated in Java, so we cannot use any element outside the
range of array.
Defining a class:
class class-name
{
Member-1;
Member-2;
-
-
}
e.g. //Test.java
class Test
{
public static void main(String r[])
{
int a,b;
a=10;
b=12;
System.out.println(“a=”+a+”\nb=”+b);
}
}
*compile the source file javac Test.java
javac it is jdk tool that generates bytecode (Test.class)
*execute the bytecode java Test
*specify path
c:\documents and settings\students>path c:\program files\java\jdk1.6.0_21\bin
Constructor: It is a member function of a class that has the same as the class
name. It doesn’t have any return type not even main. It is used to initialize an
object upon its creation.
class Student
{
int roll;
String sname;
Student() //constructor
{
roll=90;
sname=”Amit”;
}
void display() //display function
{
System.out.println(“Rollno:”+roll+”\n Name:”+sname);
}
}
class Smain
{
public static void main(String s[])
{
Student s1=new Student(); //creating object
s1.display();
}
}
class Smain
{
public static void main(String s[])
{
Student s1=new Student(); //creating object
Student s2=new Student(1012,”Anil”);
s1.display();
s2.display();
}
}
Inheritance in Java
1. Super class (Base class)
2. Sub Class (Derived class)
Class Abc
{
}
Class Abc1 extends Abc
{
}
e.g.
class Calc
{
int r;
void add(int a,int b)
{
r=a+b;
System.out.println(“Sum=”+r);
}
int sub(int a,int b)
{
r=a-b;
return r;
}
}
class Smain
{
public static void main(String s[])
{
int z;
Calc1 s =new Calc1(); //creating object
s.add(20,30);
z=s.sub(78,21);
System.out.println(“Difference=”+z);
s.multiplication(9,15);
}
}
void sum()
{
int s;
s=a+b+c;
System.out.println(“Sum=”+s);
}
void display()
{
System.out.println(“\na=”+a+”\nb=”+b+”\nc=”+c);
}
}
class Smain
{
public static void main(String s[])
{
Abc1 ob1 =new Abc1(); //creating object
Abc1 ob2 =new Abc1(10,20,30);
ob1.sum();
ob2.sum();
ob1.display();
ob2.display();
}
}
void display()
{
super.display();
System.out.println(“\nc=”+c);
}
}
class Smain
{
public static void main(String s[])
{
Abc1 ob1 =new Abc1(); //creating object
Abc1 ob2 =new Abc1(10,20,30);
ob1.sum();
ob2.sum();
ob1.display();
ob2.display();
}
}
Method Overloading:
Method Overloading is a feature that allows a class to have more than one method having the
same name, but they must differ in number and type of arguments.
Method overloading is not possible by changing the return type of the method only.
e.g.
class Methodoverload
{
int sum(int a,int b)
{
return a+b;
}
float sum(float a,float b)
{
return a+b;
}
}
Class Smain
{
public static void main(String s[])
{
int r1;
float r2;
Methodoverload ob1 =new Methodoverload (); //creating object
r1=ob1.sum(20,600);
r2=(float)ob1.sum((float)20.6,(float)30.56);
System.out.println(“\ninteger Sum=”+r1);
System.out.println(“\nFloating Sum=”+r2);
}
}
The final Keyword : It is non-access modifier in Java. Final is used for finalizing the
implementation of variable, method or class.
-To prevent variable from its content being modified
-To prevent method overriding
-To prevent inheritance
e.g. class Test
{
final int a=90;//final variable initialize only once
void run()
{
a=400;
}
public static void main(String args[])
{
Test ob=new Test();
ob.run();
}
}
//compile time error
}
class Test1 extends Test
{
void run()
{
System.out.println("running safely ");
}
Syntax:
abstract class Exam
{
------
}
An abstract class must have at least one abstract method.
abstract void sum();
e.g.
abstract class Shape
{
abstract void area();
}
//Another example
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor.
abstract class Person
{
String name,gender;
Person(String n,String g) //constructor
{
name=n; gender=g;
}
abstract void work(); //abstract method
{
return “Name-“+name+” Gender-“+gender”;
}
void changeName(String newname)
{
name=newname;
}
}
class Emp extends Person
{
int empid;
Emp(String n,String g,int id)
{
Super(n,g);
Empid=id;
}
public void work()
{
if(empid==0)
System.out.println("\Not Working ");
else
System.out.println("\nworking as employee ");
}
}
class Test
{
public static void main(String args[])
{
Emp ob1=new Emp(“Amit”,”m”,201);
Person ob2=new Emp(“Anil”,”m”,205); //in terms of abstract class
ob1.work();
ob2,work();
ob1.changeName(“Kumar”);
System.out.println(ob1.toString());
}
}
Java Input:
There are several ways to get input from the user in Java.
For that import Scanner class
import java.util.Scanner
create an object of Scanner class which will be used to get input from the user.
Scanner ip=new Scanner(System.in);
int a=ip.nextInt(); //method of Scanner class to get integer data
float b=ip.nextFloat(); //to get float data
String s=ip.next(); //to get string
String s=ip.nextLine();
Double d=ip.nextDouble();
Java Packages:
Java packages are group of similar type of classes, interfaces and sub-packages.
Packages in java categorized in two forms:
-built-in packages (java, lang, io, util)
-user defined packages
Defining a package:
Syntax: package pkgname; //it is the first statement in any java source file
Importing packages: import keyword is used to import built-in and user defined packages
in Java source file.
Syntax : import pkg.*|classname;
e.g. import cs.*;
import cs.Test;
Access Modifiers: In java there are four categories of visibility for class memebers
a). subclasses in same package
b). Non-sub classes in same package
c). subclasses in different package
d). Non-sub classes in different package
*A class can have only two access: default and public (if a class have default access then it
is not accessible outside the package and public class can be accessed by any code).
// importing packages
import cs.*;
import cs1.*
class Test
{
public static void main(String args[])
{
Exam ob1=new Exam();
Exam1 ob2=new Exam1();
Exam2 ob3=new Exam2();
Exam3 ob4=new Exam3();
Exam4 ob5=new Exam4();
}
}
Interfaces:
Interfaces are similar to classes, but they lack instance variables and their methods are
declared without any body. Using an interface we specify what a class must do but not how
it does it.
Once an interface is defined, any number of classes can implement an interface. One class
can implement any number of interfaces.
An interface is blue print of class. It is a mechanism to achieve abstraction and multiple
inheritance in Java.
Java Exceptions: An exception is an object that describes an exceptional condition, during the
execution of program. When an exceptional condition arises the normal flow of program
disrupted and program terminates abnormally.
An exception can occur for many different reasons:
- A user has entered an invalid data
- A network connection in the middle
- A file that needs to be opened cannot be found
Java exception handling is managed via five keywords- try, catch, throw, throws and finally
Program statements that we want to monitor for exceptions are contained within a try block.
If an exceptions occurs within try block it is thrown. We can catch the exception using catch
block.
System generated exceptions are automatically thrown by Java run time system.
To manually thrown an exception use throw clause.
Any code that must be absolutely executed it is put in finally block.
Syntax: try
{
---------
}
catch(Exceptiontype obj)
{
--------
}
finally
{
--------
}
//uncaught exception
class Test
{
public static void main(String args[])
{
int a,b=0;
a=100/b;
System.out.println(“\na=”+a);
}
}
catch(ArithmeticException e)
{
System.out.println(“\nDivide by zero”);
}
System.out.println(“\After try catch”);
}
}
finally
{
System.out.println(“\nFinally block”);
}
}
}
throw clause: it is used to manually throw an exception.
Syntax: throw throwableinstance;
import java.util.*;
class Test
{
public static void main(String args[])
{
int a,b;
Scanner ob=new Scanner(System.in);
System.out.println(“\nEnter values for b”);
b=ob.nextInt();
try
{
if(b==0)
throw new ArithmeticException(“Divide by zero”);
else
{
a=50/b;
System.out.println(“\na=”+a);
}
}
catch(ArithmeticException e)
{
System.out.println(“\nDivide by zero”);
}
}
}
throws clause: a throws clause lists the types of exceptions that a method might throw
Syntax:
return-type method-name() throws exception-list
{
-----------
}
e.g.
class Test
{
public static void main(String args[])
{
try
{
calc();
}
catch(ArithmeticException e)
{
System.out.println(“\nDivide by zero”);
}
}
void calc() throws ArithemeticException
{
int a=0,b;
b=200/a;
System.out.println(“\nb=”+a);
}
}
String Handling: A string is a sequence of characters. Java implements string as object of type
String. (String is an in-built class of java.lang package)
When we create a string object, we are creating a string that cannot be changed.
The String constructor:
String can support several constructors.
String s=new String();
To create string initialized by an of characters:
Char a[]={‘B’,’i’,’r’,’l’,’a’};
String s=new String(a); // is initialize with “Birla”
String s1=new String(s); //create string object that contain same character sequence as
another string object
System.out.println(s);
System.out.println(s1); //output of both statements are “Birla”
//program
public class Sexample
{
public static void main(String args[])
{
int start=9,end=10;
String s1="This is my Java Program"; //creating string by java string literal
char s2[]={'P','r','o','g','r','a','m'};
String s3=new String(s2); //converting char array to string
String s4=new String("JAVA"); //creating java string by new keyword
char ch;
char st[]=new char[15];
ch=s1.charAt(4);
s1.getChars(start,end,st,0);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(ch);
System.out.println(st);
}
}
*when we creating String object, we are creating a string that cannot be changed.
For modification of string there is companion class of String called StringBuffer, whose
object contain strings that can be modified after they are created.
Java StringBuffer class is used to create modifiable string.
Constructor of StringBuffer class:
StringBuffer() //creates an empty string buffer with initial capacity of 16
StringBuffer(String s) //creates a string buffer with the specified string
StringBuffer(int capacity); // creates an empty string buffer with specified capacity
//methods of StringBuffer class
append()- it is used to append the specified string with this string.
e.g. StringBuffer sb=new StringBuffer(“Java”);
sb.append(“Program”);
insert(int offset,String s)- it is used to insert the specified string with this string at specified
position.
e.g. StringBuffer sb=new StringBuffer(“Java program”);
sb.insert(5 ,“ First”);
A thread can be running, It can be ready to run as soon as it gets CPU time.
A running thread can be suspended, which temporarily suspends its activity. A suspended
thread can be resumed, allowing it to pick up where it left off.
A thread can be blocked while waiting fir a resource.
At any time a thread can be terminated, once terminated, it cannot be resumed.
Thread Priorities: Java assigns to each thread a priority that determines how one thread treated
with respect to the others i.e. when one to switch from one running thread to the next.
A thread can be pre-empted by a higher priority thread.
Thread class and Runnable interface: Java Multithreading is built upon Thread class and its
companion Runnable interface. To create a new thread, program either extends Thread class or
implements the Runnable interface.
The Main thread- when a Java program starts up one thread is automatically created i.e. the
main thread.
It is important for two reasons :
- It is the thread from which other “child” will be spawned
- It must be the last thread to finish execution because it perform various shutdown
activities
Creating a Thread: There are two ways for creating a thread in Java:
- extends the Thread class
- implements Runnable interface
Output:
New Thread:Thread[New Thread,5,main]
Main Thread:1
New Thread:1
Main Thread:2
New Thread:2
--
--
class TDemo
{
public static void main(String args[])
{
new NThread(“one”);
new NThread(“two”);
new NThread(“three”);
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println(“Main Interrupted”);
}
System.out.println(“Exiting Main thread”);
}
}
Applets: Applets are small Java programs transmitted over the internet and can be
automatically installed and run as a part of web document.
An applet does not have any main method. Applets are designed to be embedded within an
HTML page.
Advantages:
1). It works on client side so it has less response time.
2). Secured
3). It can be executed by Java compatible web browser
start() : it is automatically called after init. It is called each time an applet is displayed on
screen. If a user leaves a page and comes back, the applet resumes execution at start()
paint(): it is invoked automatically after the start() method and also any time the applet needs
to repaint itself in the browser.
stop(): it is called automatically when user leaves web page containing an applet (goes to
another page)
destroy(): it is called when an applet needs to be removed completely from memory. To free
resources the applet may be using. The stop() is always called before destroy.
e.g
import java.awt.*;
import java.applet.*;
public class Myapplet extends Applet
{
public void init()
{
//initialization
}
public void start()
{
//start or resume execution
}
public void paint(Graphics g)
{
//display contents of window
}
public void stop()
{
//suspends execution
}
public void destroy()
{
//perform shutdown activities
}
e.g.
import java.awt.*;
import java.applet.*;
public class Myapplet extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“BKBIET”,20,30);
}
}