Professional Documents
Culture Documents
CORE JAVA
SunMicrosystem divided the Java into three groups:
2) J2EE(Java2 Enterprise Edition): Deals with developing business application for Internet.
3) J2ME(Java2 Micro Edition): Deals with developing embedded system and wireless
application.
javac
Byte code
Features Of Java:
1) Simple: Java is simple programming language. Learning and practicing java is easy because
its look like c,c++.
2) Object Oriented:
i) Object: An object is anything that exists in the real world. Object will have
properties and it may perform some actions.
ii) Class: A class is a model to create the objects. Class does not exist physically.
A class also contains properties and actions.
i) Exception Handling
ii) Memory Management
Memory Mangement: Memory allocation is done by JVM. JVM contains class loader
2
subsystem to allot memory. Memory Deallocation is done by JVM
Garbage collection. Garbage collection automatically removed unused
objects.
5) Portable: Java is system independent. All java program are portable because it will give same
result anywhere.
JIT: Just in Time compiler is useful to increase the speed of the execution.
Demo Program:
Demo.java
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
static: static keyword is used to call main method without creating object.
void: void is a return type. Main method doesn’t return any value but it will execute all the
Statement.
String[] args: Here args is the name of the array. The type of the array is String.
JVM Architecture:
3) Java Stack: Java Stack are the places where java methods are executed.
5) Native Method Stack: These are the places where native methods are store.
Comments: Comments represents the description of aim and features of a program. The main
advantage of comments are Readability. Readability means understandable by
everyone. There are three types of comments in java.
1) Package names in java are written in all small letters. Ex: java.lang.*,java.io.* etc
2) Each word of class name and interface name start with a capital letter. Ex: Thread, String
3) Method name start with a small letter than each word start with a capital letter. Ex: read(),
readLine() etc
4) Variable names also follow the above method rule. Ex: String empName, int empNum etc.
5) Constant should be written using all capital letters. Ex: int final PI=22/7, MAX=10 etc.
6) All keywords should be written in all small letters. Ex: import, public, static etc.
i) float 4 bytes
ii) double 8 bytes
Operand is a variable in which the operator acts. An operator can act upon single operand than it is
called “unary” operator. An operator can act upon 2 operand than it is called “binary” operator. If
an operator act upon 3 operand than it is called “ternary” operator.
5
Operator in Java:
1) Arithmetic Operator:+,-, %, *, /
2) Unary Operator:++, --
3) Assignment Operator: =, +=, -=, *=, %=
4) Relational Operator: <, <=, >=, >, ==, !=
5) Logical Operator: &&, ||, !
6) Boolean Operator: &, |, !
7) Bitwise Operators:
a) Bitwise complement: ~
b) Bitwise and:&
c) Bitwise or: |(pipe symbol)
d) Bitwise XOR:^(cap symbol)
8) Dot Operator:
a) To refer to a class into package
ex: java.util.Date, java.io.BufferedReader
b) To refer to a method of a class
ex: Math.pow(), Emp.sum()
c) To refer to a variable in a class
ex: Emp.name, Emp.no
Increment Operator: This operator increases the value of a variable by 1. We have 2 types in
increment operator.Ex: ++x
Example:
//Preincrementation example
class Pre
{
public static void main(String[] args)
{
int x=7;
System.out.println(++x);
System.out.println(x);
System.out.println(++x);
System.out.println(x);
}
}
Example:
6
//postincrementation
class Post
{
public static void main(String[] args)
{
int x=18;
System.out.println(x++);
System.out.println(x);
System.out.println(x++);
System.out.println(x);
}
}
PrePost Example
class PrePost
{
public static void main(String[] args)
{
int x=3;
//System.out.println(++x*x++*x++);
System.out.println(++x*x++*++x);
System.out.println(x);
}
}
Highest
() [] .
++ -- ~ !
* / %
+ -
==
!=
&
&&
||
?:
= op=
Lowest
Note: If equal precedence than precedence will count from left to right.
Example:
class OpeTest
{
public static void main(String[] args)
{
int a=10*4+20/2-5;
int b=10*(4+20)/2-5;
int c=(10+20)/5+5;
int d=(10+20)/(5+5);
System.out.println(a+" "+b+" "+c+" "+d);
System.out.println("Value of a is-->"+a);
System.out.println("Value of b is-->"+b);
System.out.println("Value of c is-->"+c);
System.out.println("Value of d is-->"+d);
}
}
Ternary operator:
class Ternary
{
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
8
//z = i < j ? i : j; // ternary operator(output is 20)
z = i > j ? i : j; // ternary operator(output is 55)
System.out.println("The value assigned is " + z);
}
}
Reverse:
class Reverse
{
public static void main(String[] args)
{
int r=0,rev=0;
int n=63674;
while(n>0)
{
r=n%10;
rev=(rev*10)+r;
n=n/10;
}
System.out.println("The Reverse Number is-->"+rev);
}
}
Control Statement: Executing the statement one by one is called Sequential Execution.
Executing the statement randomly is called Random Execution.
Random Execution is useful to write better program. Random Execution is
possible by using control statement. Control statements are the statements
which change the flow of execution of a program.
1) if-else statement: This statement is useful to perform a task depending upon whether a
condition is true or false.
Example 1:
class IfTest
{
public static void main(String[] args)
{
int num=-4;
if(num==0)
{
System.out.println("It is zero");
}
else if(num>0)
{
System.out.println("It is positive");
9
}
else
{
System.out.println("It is negative");
}
}
}
Example 2:
//Nested if-else
class IfElse
{
public static void main(String args[])
{
int month = 4;
String season;
if(month == 12 || month == 1 || month == 2)
{
season = "Winter";
}
else if(month == 3 || month == 4 || month == 5)
{
season = "Spring";
}
else if(month == 6 || month == 7 || month == 8)
{
season = "Summer";
}
else if(month == 9 || month == 10 || month == 11)
{
season = "Autumn";
}
else
{
season = "Bogus Month";
}
System.out.println("April is in the " + season );
}
}
2) do-while loop: This loop is used to repeat early execute a group of statements as long as
10
given condition is true.
Example:
class DoWhileTest
{
public static void main(String[] args)
{
int x=0;
do
{
System.out.println(x);
x++;
}
while(x>=10);
}
}
Example:
class WhileTest
{
public static void main(String[] args)
{
int i=2;
while(true)
//while(i<=10)
{
System.out.println(i);
i+=2; //i=i+2
}
}
}
4) for loop: This loop is repeatedly execute a group of statements as long as given condition
is true. For loop is more suitable for executing the statement a fixed number of
times.
Example:
class ForTest {
public static void main(String[] args)
{
int i=1;
for(;;)//infinite loop
11
//for( i=1;i<=20;i++)
{
System.out.println(i);
}
//System.out.println(i);
}
}
5) switch statement: Switch statement is useful to execute a particular task from among
several task depending upon the value of a variable.
Example 1:
class SwitchTest
{
public static void main(String[] args)
{
char color='g';
switch(color)
{
case 'r':System.out.println("red");
break;
case 'g':System.out.println("green");
break;
case 'b':System.out.println("blue");
break;
case 'w':System.out.println("white");
break;
case 'p':System.out.println("pink");
break;
default:System.out.println("No condition");
}
}
}
Example 2:
class SwitchTest1
{
public static void main(String[] args)
{
char color='2';
int a=10,b=20;
switch(color)
{
case '1':System.out.println(a+b);
break;
case '2':System.out.println(a-b);
12
break;
case '3':System.out.println(a*b);
break;
case '4':System.out.println(a/b);
break;
case '5':System.out.println(a%b);
break;
default:System.out.println("No condition");
}
}
}
Jump Statement:
Break statement 1:
//When a break statement is encountered inside a loop, the loop is terminated and program
control resumes at the next statement following the loop.
Break statement 2:
Continue statement:
// Demonstrate continue.
class Continue
{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
Return Statement:
//The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
// Demonstrate return.
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t) //return; // return to caller
System.out.println("This won't execute.");
Stream: A stream represents flow of data from one place to another place.
System class:
Example 1:
System.out.println("Enter a value");
//char ch=(char)br.read();
String ch=br.readLine();
//int ch1=Integer.parseInt(ch);
float ch1=Float.parseFloat(ch);
double ch1=Double.parseDouble(ch);
System.out.println("You have entered-->"+ch1);
}
}
Example 2:
Array: An array represents a group of elements of same data type. By representing a group of
elements with a single array we can make programming easy.
Types of Array:
1) One dimensional array 1D: One dimensional array represents a single row of data or a
single column of data.
i) We can declare and initialize a one dimensional array using assignment operator.
Ex: int marks[]={10,20,30,40,50};
ii) We can create an empty array using new operator and later on we can store the elements
into the array.
Ex: int marks[]=new int[5];
marks[0]=10;
marks[1]=20;
marks[2]=30;
marks[3]=40;
marks[4]=50;
Example 1:
Example 2:
Example 3:
//Character Array(1D)
class CharArray
{
public static void main(String[] args)
{
char ch[]={'A','B','C','D'};
System.out.println(ch[3]);
}
}
17
2) Two dimensional array 1D: Two dimensional array represents several rows columns of
elements.
i) We can declare and initialize a two dimensional array using assignment operator.
Ex: int marks[][]={{10,20,30},{40,50,60},{70,80,90}};
ii) We can create an empty array using new operator and later on we can store the elements into
the array.
Ex: int marks[][]=new int[5][5];
Example 1:
Example 2:
Example 3:
//In java,a multi-diamensional array is an array whose components are themselves arrays.
class CharMultiArray
{
public static void main(String[] args)
{
char ch[][]={{'A','B','C','D'},{'E','F','G','H'}};
String str[][]={{"John","Andrews","David","Scott"},{"-Manager","-
CEO"}};
System.out.println(ch[1][1]);
System.out.println(ch.length);
System.out.println(str[0][0]+str[1][0]);
System.out.println(str[0][2]+str[1][1]);
//System.out.println(str[0][2]+str[2][1]);//ArrayIndexOutOfBoundsException
System.out.println(str.length);
}
}
String: A String represents a group of character. In java String is a class. Any String is
a object of String class in java.
Creating a String:
ii) Using new operator we can create a String class object and store data into it.
Ex: String st = new String(“Hello”);
hashCode: hashCode is a unique identification number allotted to every object by the JVM.
hashCode number used to refer to object position in memory.
Types of Objects:
i) Mutable Object: Mutable Objects are the Objects whose contents(data) can be
modified.
Ex: StringBuffer
ii) Immutable Object: Immutable Objects are the Objects whose data can not be
19
modified.
Ex: String
Example 1:
class Str1
{
public static void main(String[] args)
{
String s1="This is java";
System.out.println("hashcode for s1=-->"+s1.hashCode());
String s2=new String("I like");
System.out.println("hashcode for s2=-->"+s2.hashCode());
char arr[]={'a','p','t','e','c','h'};
String s3=new String(arr);
System.out.println("s1="+s1);
System.out.println("s2="+s2);
System.out.println("s3="+s3);
System.out.println("The no. of character in s1 including spaces="+s1.length());
System.out.println("s1 join with s2 with s3="+s1.concat(s2)+" "+s2.concat(s3));
// System.out.println(s1+" "+s2+" "+s3);
boolean x=s1.startsWith("This");
if(x)
System.out.println("s1 starts with This");
else
System.out.println("s1 does not starts with This");
String r=s1.toUpperCase();
String s=s2.toUpperCase();
String r1=s1.toLowerCase();
System.out.println("After converting s1="+r);
System.out.println("After converting s2="+s);
System.out.println("After converting s1="+r1);
}
}
Example 2:
class Str2
{
public static void main(String[] args)
{
String s1="Hello";
System.out.println("hashcode for s1=-->"+s1.hashCode());
String s2="Hello1";
System.out.println("hashcode for s2=-->"+s2.hashCode());
//if(s1==s2)
if(s1.equals(s2))
System.out.println("Both are equals");
20
else
System.out.println("Both are not equals");
}
}
Example 3:
class Str3
{
public static void main(String[] args)
{
String s1="Hello";
System.out.println(s1);
String s2="Hai";
s1=s1+s2;
System.out.println(s1);
}
}
/*Garbage Collector remove the previous value and storing the new value*/
Example 4:
String Methods:
//1) codePointAt():-- The codePointAt() method returns the character(Unicode code point) at the
specified index.
//2) codePointBefore():-- The codePointBefore() method returns the character(Unicode code point)
before the specified index.
//3) codePointCount():-- The codePointCount() method returns the number of Unicode code points
between two indices in the String.
//4) startsWith():-- The startsWith() method returns a boolean value to test whether the string starts
with a specified prefix.
//5) endsWith():-- The endsWith() method returns a boolean value to test whether the string ends
with a specified sufix.
//6) toUpperCase():--The toUpperCase() method converts the characters in the string to upper case.
//7) toLowerCase():--The toLowerCase() method converts the characters in the string to lower
case.
//8) valueOf():--The valueOf() method returns the string representation of the specified
argument.The argument can have any one of the values:boolean, char, float, double, int, long etc.
21
//9) toCharArray():-- The toCharArray() method copies the content of the String to a new character
array.
//10) equalsIgnoreCase():-- The equalsIgnoreCase() method compares two strings, ignoring case
and returns a boolean value. If the strings are equal the method returns a true value, otherwise
false.
class StringMethod
{
public static void main(String[] args)
{
String str="Aptech Global Learning Solutions";
String str1="APTECH GLOBAL LEARNING SOLUTIONS";
char[] array={'A','p','t','e','c','h',' ','G','l','o','b','a','l'};
System.out.println(str.codePointAt(0));//65
System.out.println(str.codePointBefore(1));//65
System.out.println(str.codePointCount(0,5));//5
System.out.println(str.startsWith("Apt"));//true
System.out.println(str.endsWith("tions"));//true
System.out.println(str.toUpperCase());
//APTECH GLOBAL LEARNING SOLUTIONS
System.out.println(str.toLowerCase());//aptech global learning solutions
System.out.println(String.valueOf(array));
//Aptech Global
System.out.println(String.valueOf(array,7,6));
// Global
char[] array1;
array1=str.toCharArray();
System.out.println(String.valueOf(array1));
//Aptech Global Learning Solutions
System.out.println(str.equalsIgnoreCase(str1)); //true
}
}
Example 5:
StringBuffer Methods:
//1) charAt():-- The charAt() method returns the character value at the specified index.
//2) deleteCharAt():-- The deleteCharAt() method deletes the character value at the specified
position.
/*3) getChars():-- The getChars() method copies specified number of character into an array.
syntax:
void getChars(int begin,int end, char[] destArray,int destArrayBegin)*/
22
//4) length():-- The length() method returns the total number of characters from the StringBuffer
object.
//5) replace():-- The replace() method replaces characters from the StringBuffer object with new
characters.
//6) setCharAt():-- The setCharAt() method replaces a character from the StringBuffer object with
a new character at the specified index.
//7) setLength():-- The setLength() method sets the length of the StringBuffer to a new value.
//8) capacity():-- The capacity() method returns the current capacity of the StringBuffer object. The
capacity is the amount of storage available for newly inserted characters, beyond which an
allocation will occur.
//9) substring():-- The substring() method creates a new string from the stringBuffer object.
class StringBufferMethod
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("Aptech Global Learning Solutions");
StringBuffer sb1=new StringBuffer("Aptech Global Learning Solutions");
System.out.println(sb.charAt(7));//G
System.out.println(sb.deleteCharAt(5));
//Aptec Global Learning Solutions
char[] array=new char[10];
sb1.getChars(0,6,array,0);
System.out.println(array);//Aptech
System.out.println(sb1.length());//32
System.out.println(sb1.replace(23,32,"Services"));
//Aptech global Learning Services
sb1.setCharAt(7,'g');
System.out.println(sb1);
//Aptech global Learning Services
//sb1.setLength(35);
System.out.println(sb1);
//Aptech global Learning Services
sb1.setLength(13);
System.out.println(sb1);
//Aptech global
StringBuffer sb2=new StringBuffer();
System.out.println(sb2.capacity());//16
System.out.println(sb1.capacity());//48
//capacity=length+16
String str;
str=sb1.substring(7);
System.out.println(str);//global Learning Services
23
str=sb1.substring(7,13);
System.out.println(str);//global
}
}
The languages like c, pascal, fortron these are called procedural languages because they follow an
approach called procedural approach.
The languages like c++ and java called object oriented because they follow an approach called
object oriented programming approach.
Features of OOPS:
Object: An object is anything that exists in the real world. An object contains properties
and Actions. Properties are represented as variables. Actions are represented as
methods. So an object contains variables and methods. Class does not exist
physically but Object does exist physically.
Class: A class is a model or idea to create the objects. From the class we create objects. A
class also contains variables and methods. An object does not exist without a class but a
class exist without any objects.
4) Inheritance: Producing a new class from an existing class is called inheritance. The newly
produced class automatically built inherit all the features of the existing
class. Reusability of code is the main advantage of inheritance
Access Specifier: An access specifier is a keyboard that specifies how to access the members of
class or the class itself. There are four access specifier in java:
1) Private: Private member of a class are not accessible in another class either in the same
package or in another package. The scope of private specifier is class scope.
24
2) Public: Public members of a class are available in another class of same package or of an
another package. The scope of public spcifier is global scope.
3) Protected: Protected members are available in another class in the same package but they
are not available in another package class.
Note: Protected members are always available to subclasses(inheritance) in the
same package or another package.
4) 4) Default: Default members are available in another class in the same package but they
are not available in another package class. The scope of default specifier is
package scope.
Problem 1:
class Person
{
private String name;
private int age;
//String name;
//int age;
void talk()
{
System.out.println("Hello I am -->"+name);
System.out.println("Hello My Age -->"+age);
}
}
class FirstType
{
class Person
{
private String name="san";
private int age=25;
//String name="xyz";
//int age=20;
void talk()
{
System.out.println("Helllo I am -->"+name);
System.out.println("Helllo My Age -->"+age);
}
}
class SecondType
{
public static void main(String[] args)
{
Person p1=new Person();
p1.talk();
Person p2=new Person();
p2.name="abc";
p2.age=29;
p2.talk();
}
}
//Note:defect in this program is private variable can't be initialize second time.
Problem 3:
class Person
{
private String name;
private int age;
//String name;
//int age;
Person()//default constructor
{
name="xyz";
age=20;
System.out.println("default constructor");
}
void talk()
{
System.out.println("Helllo I am -->"+name);
System.out.println("Helllo My Age -->"+age);
}
26
}
class ThirdType
{
public static void main(String[] args)
{
Person p1=new Person();
Person p2=new Person();
p1.talk();
p2.talk();
}
}
//Note: defect in this program is default constructor can initialize only one set of value.
Constructor Overloading: Writing two or more constructor with the same name but with a
difference in the parameter is called constructor overloading.
Example:
//Parameterized Constructor
class Constru
{
private String a;
private int b;
private int c;
Constru()//default constructor
{
a="xyz";
b=30;
//c=45;
}
Constru(String a,int b)
{
this.a=a;
this.b=b;
}
Constru(String a,int b,int c)
27
{
this.a=a;
this.b=b;
this.c=c;
}
void display()
{
Method: A method is a group of sttements similar to class. (or) A method represents a group
of statements to execute a task. A method will have two parts:
i) Method Header or Method Prototype: This part contains method name, method
parameters and method return type.
ii) Method Body: A method body represents a group of statements containing logic
written inside { }
If a method returns some values we should use return statements inside to the method
body. We can return only one entity.
28
Method Without Return Type Example:
Types of Methods:
1) Static Method: Static methods are the methods which does not act upon the instance
variables of a class. Static methods are declared as static by using a static
keyword. Static methods are called using classname.methodname. Here no
need to create an object. Static methods can act upon static variable. Static
variable should be declared as static.
Ex: static double d1,d2,d3;
Example:
2) Instance Method: These are the methods which act upon instance variables of a class.
Instance methods are called using objectname.methodname.
a) Accessor Method: These methods access or read the instance
variables.
b) Mutator Method: These methods not only read the instance variable but also
modifies the contents of the object.
30
Example:
3) Factory Method: A Factory method is a method that returns an object of the class to
which it belongs. All the Factory methods are static method. When we
use Factory Method we can not use new operator.
31
Example:
Inner Class: A class within another class is called inner class. We can not write private before
main class. Private can be used only before inner class. Inner class not available to
the other programmer. We can create an object to inner class only in its outer class.
Example:
Inheritance: Producing a new class from an existing class is called inheritance. The existing
class is called super class and the newly produced class is called sub class.
Subclass object contains copy of the super class. The main advantage of
inheritance is the reusability of the code. We can create an object to the subclass
only in inheritance.
Types of Inheritance:
1) Single Inheritance
2) Multilevel Inheritance
3) Multiple Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance
Example 1:
class Inherit
{
public static void main(String[] args)
{
Student st=new Student();
st.setId(1);
st.setName("xxx");
st.setAddr("131-22,P&T colony,DSNR");
st.setMarks(598);
System.out.println("ID="+st.getId());
System.out.println("NAME="+st.getName());
System.out.println("ADDRESS="+st.getAddr());
System.out.println("MARKS="+st.getMarks());
}
}
34
Note: a) From above program all the Teacher class members are available to student class.
b) To access or read all the members of Teacher class(Super class) to Student class(Sub
class) we use extends keyword.
Example 2:
class OneDemo
{
OneDemo()
{
System.out.println("OneDemo in super class!");
}
}
class TwoDemo extends OneDemo
{
TwoDemo()
{
System.out.println("TwoDemo in sub class");
}
}
class TDemo extends TwoDemo
{
TDemo()
{
System.out.println("TDemo in sub class");
}
}
class InheritDemo
{
public static void main(String[] args)
{
TDemo t=new TDemo();
}
}
Note: a) From above program first super class constructor is executed and than the sub class
constructor is executed.
b) Super class parameterized constructor is not available to sub class.
c) Super is a keyword that refers to super class from a sub class. It means super can refer
super class instance variable, super class constructor and also super class methods.
35
Example 3:
class One
{
int x;
One(int x)
{
this.x=x;
}
void show()
{
System.out.println("super class method");
}
}
class Two extends One
{
int x;
Two(int a,int b)
{
super(a);
x=b;
}
void show()
{
super.show();
System.out.println(super.x);
System.out.println("Sub class method="+x);
}
}
class SuperDemo
{
public static void main(String[] args)
{
Two t=new Two(100,299);
t.show();
}
}
Polymorphism: The word came from two Greek word. i) Poly—Poly means many and ii)
Morph—morph means forms. If something exist in several form it is called
polymorphism. If the same method performs various task is called
polymorphism. Different method bodies are required to perform various task.
In polymorphism there are two types:
36
a) Static polymorphism
b) Dynamic polymorphism
Example:
Method Overloading: Writing two or more methods with the same name but with different
method Signature.
//Method Overloading
class Sample
{
void add(int a,int b)
{
System.out.println("sum of two="+(a+b));
}
void add(int a,int b,int c)
{
System.out.println("sum of three="+(a+b+c));
}
}
class Poly
{
public static void main(String[] args)
{
Sample s=new Sample();
s.add(10,20);
s.add(10,20,30);
}
}
Method Signature: Method Signature represents method name and method parameters. When two
or more methods are written with the same method name and there is a
difference in the method signature from can identify those method s different
method.
The difference in the method signature may be due to the following factor:
Method Overriding: Writing two or more methods in super and sub classes with the same name
and same signature is called method overriding. In method overriding JVM
execute a method depending on the data type of reference variable used to
call a method.
Example:
//Method Overriding
class One
{
void calculate(double x)
{
System.out.println("Square="+(x*x));
}
}
class Two extends One
{
void calculate(double x)
{
super.calculate(2);
System.out.println("Square root value"+
Math.sqrt(x));
}
}
class Poly1
{
public static void main(String[] args)
{
Static Polymorphism: The Polymorphism executed at compile time is called static polymorphism
or static binding.
38
Use of Final keyword:
Type Casting or Casting: Converting one data type into another type is called type casting or
casting.
1) Widening: Casting a lower data type into a higher data type is called widening.
Ex: char ch = ‘A’
int i = (int) ch;//65
2) Narrowing: Converting a higher data type into lower type is called Narrowing.
Ex: int n = 65;
Char ch = (char) n;
Abstract class: A method consists of two parts: method header and method body. Method
header represents the future the programmer wants in a class. Method body
represents how to implements this future. Implementing means writing body
for method. When a method has got different implementation in different
objects than the programmer cannot write method body in the super class.
Points:
Maruti(int regno)
{
super(regno);
}
void steering(int direction)
{
System.out.println("Regno of Maruti="+regno);
System.out.println("Maruti uses manual steering="+direction);
System.out.println("please drive the maruti car");
}
void breaking(int force)
{
System.out.println("Breaking of Maruti="+force);
System.out.println("Maruti uses hydralic breaks");
System.out.println("Apply breaks stop the car");
}
}
class Santro extends Car
{
Santro(int regno)
{
super(regno);
}
void steering(int direction)
{
System.out.println("Regno of Santro="+regno);
System.out.println("Santro uses manual steering="+direction);
System.out.println("please drive the Santro car");
}
40
void breaking(int force)
{
System.out.println("Breaking of Santro="+force);
System.out.println("Santro uses hydralic breaks");
System.out.println("Apply breaks stop the car");
}
}
class AbstractDemo
{
public static void main(String[] args)
{
Maruti m=new Maruti(6666);
Santro s=new Santro(9999);
Car c,c1;
c=m;
c1=s;
c.fillTank();
c.steering(2);
c.breaking(200);
c1.fillTank();
c1.steering(2);
c1.breaking(200);
}
}
Interface: An interface is a specification of method prototype. All the methods of interface are
by default abstract only. We cannot create an object to interface.
Points:
Example1:
import java.io.*;
interface MyInter
{
void connect();
}
Example 2:
//An Interface can extends more than one interface,but one interface can't implements another
interface
42
interface First
{
void disp1();
}
interface Second
{
void disp2();
}
interface Third extends First,Second
{
void disp3();
}
class Test implements Third
{
public void disp3()
{
System.out.println("disp3()");
}
public void disp1()
{
System.out.println("disp1()");
}
public void disp2()
{
System.out.println("disp2()");
}
}
class Inter1
{
public static void main(String[] args)
{
Test t=new Test();
t.disp1();
t.disp2();
t.disp3();
//System.out.println("Hello World!");
}
}
Example 3:
Multiple Inheritance: Java doesn’t support multiple inheritance. We can achieve multiple
inheritance by using multiple interfaces.
Example:
Packages: A packages represents a sub directory that contains a group of related classes and
interfaces. Packages hide classes and interfaces in separate subdirectories. Accidental
deletion is not possible. The classes of one package are different from the classes of
another package. Packages provide the reusability of code. We can create our own
package as well as extend already available packages.
Example 1
Addition.java
package ddd;
public class Addition
{
double d1,d2;
public Addition(double d1,double d2)
{
this.d1=d1;
this.d2=d2;
}
public void sum()
{
System.out.println("sum="+(d1+d2));
}
}
Note: > javac –d . Addition.java
UseAdd.java
import ddd.Addition;
class UseAdd
{
public static void main(String[] args)
{
Addition a=new Addition(24,534);
45
Addition a1=new Addition(25,53);
//ddd.Addition a=new ddd.Addition(25,55);
a.sum();
a1.sum();
}
}
Example 2:
MyDate.java
package cdf;
public interface MyDate
{
void showDate();
}
MyDateImpl.java
package cdf;
import java.util.Date;
public class MyDateImpl implements MyDate
{
public void showDate()
{
Date d=new Date();
System.out.println(d);
}
}
Useinterface.java
import cdf.MyDateImpl;
class Useinterface
{
public static void main(String[] args)
{
MyDateImpl m=new MyDateImpl();
m.showDate();
}
}
SubPackage Example
Sample.java
package demo.aptech;
public class Sample
46
{
public void show()
{
System.out.println("sub packages");
}
}
UseSample.java
import demo.aptech.Sample;
class UseSample
{
public static void main(String[] args)
{
Sample s=new Sample();
s.show();
}
}
Exception Handling:
Types of Error:
1) Compile time error: These are the errors in the syntax or grammar of the language. These
errors are detected by the compiler at the time of compilation. Desk
checking(line by line) is the solution for compile time errors.
2) Runtime error: These errors will arise due to inefficiency (enough memory not available)
or unable to execute the statement by processor. Ex: something divides by
zero. Runtime errors are detected by JVM.
3) Logical error: These are the errors in the logic of the program. These errors are not
detected by the compiler or JVM. The programmer is completely
responsible for logical errors.
Checked Exception: The Exception which are detected by java compiler at the time of
compilation are called Checked Exception.
Unchecked Exception: The exception which are not detected by java compiler and they are
detected by JVM at runtime are called Unchecked Exception:
Note: An Exception is an error that can be handled but an error cannot be handled.
47
Example:
//without handling
class Exce11
{
public static void main(String[] args)
{
System.out.println("open the files");
int n=args.length;
System.out.println("Number of args are-->"+n);
int a=45/n;
System.out.println(a);
int a1[]={10,20};
a1[3]=40;
System.out.println("The value of a is"+a1);
System.out.println("close the file");
}
}
When there is an exception JVM come out of the program and we loss the remaining statement
also. When there is an exception the programmer should do the following task:
1) We should write all the statements where there may be an exception inside try block. When
there is an exception inside try block JVM doesn’t abnormally terminate the program. It
will jump into catch block.
2) When there is an exception JVM stores exception details in the Exception Stack. In catch
block the programmer should display exception details and also any messages to the user.
3) The programmer should close all the files and databases and perform cleanup operation by
writing them in finally block. The statements inside finally blocks are always executed
wether there is an exception or not.
Example:
Throws clause: Throws clause is useful to throughout an exception from a method without
handling it.
Throw clause: Throw clause is useful to create an exception class object and throws it out of a try
block.
Example:
class NestedTry
{
public static void main(String[] args)
{
int a=args.length;
int c[]={1};
try
{
int b=90/a;
System.out.println("b is : "+b);
try
{
if (a==1)
a=a/(a-a);
System.out.println("a is : "+a);
if (a==2)
c[3]=9;
}
catch(ArrayIndexOutOfBoundsException e)
49
{
System.out.println("array is out of bounds : "+e);
}
}
catch(ArithmeticException e)
{
System.out.println("division by zero : "+e);
}
}
}
Example:
class NestedTryMethods
{
static void nestedTry(int no)//Method
{
try
{
System.out.println("\n INSIDE STATIC METHOD");
if(no==1)
no=no/(no-no);
if(no == 2)
{
int a[] = {55};
a[42] = 77;
}
}
catch(Exception e)
{
System.out.println("from method : : "+e);
}
}
public static void main(String ar[])
{
try
{
int n,res;
n = ar.length;
System.out.println(" No of Command Line Arguments = "+n);
res = 55/n;
System.out.println(" Result = "+res);
System.out.println("Before Invloking nestedTry(n) Value of N = "+n);
nestedTry(n);
}
catch(Exception e)
{
50
System.out.println("From Main Divide By ZERO "+e);
}
NestedTryMethods.nestedTry(1);
}
}
Example:
//throw example
class Exce2
{
static void demo()
{
try
{
throw new NullPointerException("Mydata");
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
public static void main(String[] args)
{
Exce2.demo();
//demo();
}
}
Example:
//Multiple catch
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 10/a;
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Violation "+e);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero"+e);
}
catch(Exception e)
{
System.out.println(" from Super class Exception "+e);
}
finally
{
System.out.println("after Catch");
}
}
}
Example:
Example:
class UserDefinedExce
{
static void check(int no) throws MyException
{
System.out.println("In Check("+no+")");
if(no<500)
throw new MyException(no);
System.out.println("Normal Exit");
}
public static void main(String ar[])
{
try
{
check(1000);
53
check(350);
}
catch(MyException me)
{
System.out.println(me);
}
}
}
Exception List:
Exception Meaning:
Wrapper Class: A wrapper class is a class whose object contains a primitive data type.
Character class: A Character class contains a value of primitive type char in an object. An object
of type Character contains a single field whose type is char.
Example:
//Character Test
import java.io.*;
class CharTest
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter a character");
char ch=(char)br.read();
if(Character.isDigit(ch))
System.out.println("It is a Digit");
else if(Character.isUpperCase(ch))
System.out.println("It is capital");
else if(Character.isLowerCase(ch))
System.out.println("It is small");
else if(Character.isSpaceChar(ch))
System.out.println("It is coming from spacebar");
else if(Character.isWhitespace(ch))
System.out.println("It is coming from enter,tab");
else
System.out.println("Sorry I donot know that character");
}
}
55
Byte class: A Byte class contains a value of primitive type byte in an object. An object
of type Byte contains a single field whose type is byte.
Example:
import java.io.*;
class ByteTest
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter first byte no.");
String s1=br.readLine();
Byte b1=new Byte(s1);
System.out.println("Enter second byte no.");
String s2=br.readLine();
Byte b2=new Byte(s2);
int n=b1.compareTo(b2);
System.out.println("CompareTo() methods return the difference between two
no="+n);
if(n==0)
System.out.println("Both are equal");
else if(n>0)
System.out.println("b1 is bigger="+b1);
else
System.out.println("b1 is smaller="+b1);
}
}
Integer class: A Integer class contains a value of primitive type int in an object. An object
of type Integer contains a single field whose type is int.
Example:
import java.io.*;
class IntTest
{
public static void main(String[] args) throws IOException
{
IOStream:
Stream: A stream represents flow of data from one place to another place. There are two types of
stream:
1) InputStream: InputStream read or accept data that is coming from some other place.
Byte Stream: Byte Stream handles the data in the form of bits and bytes. To handle the data in the
form of bytes the abstract class InputStream or OutputStream are used.
InputStream Division:
1) FileInputStream
2) FilterInputStream
a) BufferedInputStream
b) DataInputStream
3) Object InputStream
OutputStream Division:
1) FileOutputStream
2) FilterOutputStream
a) BufferedOutputStream
b) DataOutputStream
3) Object OutputStream
CharacterStream or TextStream: They will handle the data in the form of chracters
Reader Division:
1) BufferedReader
2) CharArrayReader
3) InputStreamReader
a) FileReader
4) PrintReader
57
Writer Division:
1) BufferedWriter
2) CharArrayWriter
3) OutputWriterr
a) FileWriter
4) PrintWriter
Example 1:
//Creating a text file and enter the data into the file
import java.io.*;
class Create
{
public static void main(String[] args) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
FileOutputStream fout=new FileOutputStream("MyFile.txt");
//FileOutputStream fout=new FileOutputStream("MyFile.txt",true);
BufferedOutputStream bout=new BufferedOutputStream(fout);
char ch;
System.out.println("Enter data('@'at end):");
while((ch=(char)dis.read())!='@')
fout.write(ch);
fout.close();
}
}
Example 2:
//Using Writer create and pass the data into the file
import java.io.*;
class Create2
{
public static void main(String[] args) throws IOException
{
String str="This is an Institute I am a student";
FileWriter fw=new FileWriter("textfile.txt",true);
BufferedWriter bw=new BufferedWriter(fw);
for(int i=0;i<str.length();i++)
bw.write(str.charAt(i));
bw.close();
}
}
Example 4:
Example 5:
Example 6:
Example 7:
Serialization:
Example 1:
import java.io.Serializable;
public class Ctwo1 implements Serializable
{
public int varone;
public float vartwo;
public String varthr;
public transient Cone varfr;
}
import java.io.Serializable;
public class Ctwo2 implements Serializable
{
public static int a;
public float b;
public String c;
public Ctwo2(int a1,float b1,String c1)
{
a=a1;
b=b1;
c=c1;
}
public void print()
{
System.out.println("value of a="+a);
System.out.println("value of b="+b);
System.out.println("value of c="+c);
}
61
}
//Serialization Demo
import java.io.*;
public class Ser1
{
public static void main(String[] args) throws Exception
{
//Cone o=new Cone();
Ctwo o=new Ctwo();
o.varone=10;
o.vartwo=22.5f;
o.varthr=new String("Hello");
FileOutputStream fos=new FileOutputStream("TestSer1");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(o);
}
}
//DeSerialization Demo
import java.io.*;
public class DeSer1
{
public static void main(String[] args) throws Exception
{
Ctwo o=null;
FileInputStream fis=new FileInputStream("TestSer1");
ObjectInputStream ois=new ObjectInputStream(fis);
o=(Ctwo)ois.readObject();
System.out.println(o.varone);
System.out.println(o.vartwo);
System.out.println(o.varthr);
}
}
import java.io.*;
public class Ser3
{
public static void main(String[] args) throws Exception
{
Ctwo2 o=new Ctwo2(10,20.22f,"xxx");
o.print();
FileOutputStream fos=new FileOutputStream("TestSer2");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(o);
FileInputStream fis=new FileInputStream("TestSer2");
ObjectInputStream ois=new ObjectInputStream(fis);
o=(Ctwo2)ois.readObject();
System.out.println(o.a);
System.out.println(o.b);
System.out.println(o.c);
}
}
Example:
class Thr1
{
public static void main(String[] args)
{
System.out.println("This is first statement");
Thread t=Thread.currentThread();
63
t.setName("Mythread");
System.out.println(t.isAlive());
System.out.println("Thread name is");
System.out.println("current thread="+t);
}
}
1) Single Tasking: Executing only one task at a time is called single tasking
b) Thread based multitasking: Executing different parts of the same program with the
help of threads is called Thread based multitasking.
Example 1:
}
}
}
64
class Thr2
{
public static void main(String args[])throws IOException
{
Tdemo obj=new Tdemo();
Thread t=new Thread(obj);
t.start();
}
}
Example 2:
Thread Synchronization or Thread safe: when a thread is acting on an object, preventing other
threads from acting on the same objects is called
thread Synchronization or Thread safe.
Example:
Example:
t1.start();
t2.start();
}
}
Thread Priority:
Max Priority- 10
Min Priority 5
Norm Priority 1
Example:
//Priority Demo
public class PriorityDemo extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
String str=Thread.currentThread().getName();
System.out.println(str+":"+i);
}
}
public static void main(String args[])
{
PriorityDemo pd1=new PriorityDemo();
PriorityDemo pd2=new PriorityDemo();
pd1.setName("First");
pd2.setName("Second");
pd2.setPriority(MAX_PRIORITY);
//pd2.setPriority(8);
pd1.setPriority(MIN_PRIORITY);
68
pd1.start();
pd2.start();
Applet: An Applet is a program that comes from internet server into a client and gets executed at
client side and displays the result. An applet represents byte code embedded in a HTML
page.
1) public void init(): This method is used for initializing the variables, parameters and to create
Components (button,images). This method is executed only once at the time
of applet loaded into memory.
2) public void start(): This method will execute when applet gains the focus.
3) public void stop():This method will execute when applet loss the focus.
4) public void destroy(): This method is executed only once when the applet is terminated from
Memory.
Example 1:
import java.awt.*;
import java.applet.*;
/*<applet code="MyApplet1" width=600 height=400>
</applet>*/
public class MyApplet1 extends Applet
{
String msg=" ";
public void init()
{
setBackground(Color.pink);
setForeground(Color.yellow);
Font f=new Font("Dialog",Font.BOLD,30);
setFont(f);
msg+="Init";
}
public void start()
{
69
msg+="start";
}
public void paint(Graphics g)
{
msg+="paint";
g.drawString(msg,100,100);
}
public void stop()
{
msg+="stop";
}
public void destroy()
{}
}
<html>
<h1>My First Applet</h1>
<body bgcolor="red">
<applet code="MyApplet1.class" width=400 height=300>
</applet>
</body>
</html>
Example 2:
Image i=getImage(getDocumentBase(),"OBJECT.gif");
//move image from left to right
for(int x=0;x<100;x++)
{
g.drawImage(i,x,50,this);
}
//make time delay
try
{
Thread.sleep(1000);
}
70
catch(InterruptedException IE)
{}
}
}
<html>
<h1>My Image</h1>
<body bgcolor="red">
<applet code="MyApplet2.class" width=400 height=300>
</applet>
</body>
</html>
Example 3:
<html>
<head>
<title>My page</title>
</head>
<body bgcolor=blue>
<h2>This page shows use of Applet</h2>
<p>
<applet code="MyApplet3.class" width=400 height=100>
<param name=para value="Passing value from HTML">
</applet>
</body>
</html>
71
Example 4:
//Draw graphics
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import java.applet.Applet;
public class MyApplet4 extends Applet
{
public void paint(Graphics g)
{
Font f=new Font("Courier",Font.BOLD,16);
Color c=new Color(200,235,255);
g.drawLine(10,1,10,60);
g.drawLine(10,1,60,10);
g.drawRect(10,10,50,50);
g.setFont(f);
g.setColor(c);
g.drawString("Have a nice Day!",110,50);
}
}
<html>
<head>
<title>My page</title>
</head>
<body bgcolor=red>
<h2>This page shows use of Graphics</h2>
<p><applet code="MyApplet4.class" width=400 height=100>
</applet>
</body>
</html>
72
73