core java

95
CORE JAVA SunMicrosystem divided the Java into three groups: 1) J2SE(Java2 Standalone Edition): Deals with developing a standalone application.(Core Java, Adv.Java). 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. Java Program Execution: Features Of Java: 1) Simple: Java is simple programming language. Learning and practicing java is easy because its look like c,c++. Pointers are eliminated in java due to the following reason: i) Pointer creates confusion for a programmer. ii) Pointer may crash a program. If we can’t use pointers properly crash occurs. iii) Using pointers virus and hacking programs are developed. 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. x.java x.clas s Byte code 1 JVM Result

Upload: svsn-sandeep-svsn

Post on 24-Nov-2014

491 views

Category:

Documents


14 download

TRANSCRIPT

Page 1: CORE  JAVA

CORE JAVA

SunMicrosystem divided the Java into three groups:

1) J2SE(Java2 Standalone Edition): Deals with developing a standalone application.(Core Java, Adv.Java).

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.

Java Program Execution:

Features Of Java:

1) Simple: Java is simple programming language. Learning and practicing java is easy because its look like c,c++.

Pointers are eliminated in java due to the following reason: i) Pointer creates confusion for a programmer. ii) Pointer may crash a program. If we can’t use pointers properly crash occurs. iii) Using pointers virus and hacking programs are developed.

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.

Properties: Properties are represented as variables in java.Actions: Actions are represented as methods.An Object contains variables and methods.

ii) Class: A class is a model to create the objects. Class does not exist physically. A class also contains properties and actions.

3) Distributed: Java is distributed programming language.

4) Robust: In Robust we have two features:

i) Exception Handlingii) Memory Management

Memory Mangement: Memory allocation is done by JVM. JVM contains class loader

x.java x.class

Byte code

1

JVM Result javac

Page 2: CORE  JAVA

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.

6) High Performance: JVM contains i) JIT compiler and ii) Interpreter

JIT: Just in Time compiler is useful to increase the speed of the execution.

Interpreter: Interpreter shows the line number.

Demo Program:

Demo.java

import java.lang.*;class Demo {

public static void main(String[] args) {

System.out.println("Hello World!");}

}

import: import is a keyword which is used to import the packages.

java: java is a java library.

lang: lang is the name of the default package.

class: Class is a keyword to define class name.

public: Public data available to all other programmer.

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.

main: Name of the main method.

String[] args: Here args is the name of the array. The type of the array is String.

System: System is a class.

out: Out is a static field. Static field can’t changed.

2

Page 3: CORE  JAVA

println: Name of the method.

JVM Architecture:

JVM is divided into five sections:

1) Method Area: It contains the class code and method code.

2) Heap: Objects are created on Heap memory.

3) Java Stack: Java Stack are the places where java methods are executed.

4) PC Register: These registers store memory address of next instruction to be executed by the microprocessor.

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.

i) Single line comment: This comment starts with //.ii) Multiline comment: This comment starts with /* and ends with */.iii) Documentation comment: This comment starts with /** and ends with */.

Q: What is an API document?A: (Application Programming Interface). It is a document containing description of all the features of software or product or technology. We can create our own API document by using javadoc command.

Q: What is the difference between #include and import?A: #include makes the compiler to copy the entire header file code into a c or c++ program. Thus it increases the size of the program and waste memory and processor time.

Import makes JVM to goto the java library, execute the code there, comes back and substitute the result into a java program.

Q: What is JRE(Java Runtime Environment)?A: JRE=JVM + JavaLibrary

Q: What is command line argument?A: The values pass to main method is called command line argument. The values store in String type array.

3

Page 4: CORE  JAVA

Naming Rule:

1) Package names in java are written in all small letters. Ex: java.lang.*,java.io.* etc2) 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() etc4) 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.

Data Type: A datatype represents the type of data stored in memory.

Primitive Data Type or Fundamental Data Type:

I) Integer Data Type

Data Type Memory Sizei) byte 1byteii) short 2 bytesiii) int 4 bytesiv) long 8 bytes

II) Float Datatype

i) float 4 bytesii) double 8 bytes

III) Character Datatypei) char 2 bytes

IV) Boolean datatypei) boolean 1bit(true or false)

Q: What is the difference between float and double?A: float can represent upto 7 digit after decimal point accurately. Double can represent upto 15 digit accurately after decimal point.

Operator: An operator is a symbol that perform some operations.

Ex: A + B (Here + is an operator and A,B is called operand)

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.

4

Page 5: CORE  JAVA

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.BufferedReaderb) 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

1) Preincrementation: In Preincrementation , incrementation has done first and any other operation are performed next.

Example:

//Preincrementation exampleclass 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);

}}

2) Postincrementation: In Postincrementation any other operation is done first, incrementation is performed at the end.Ex: x++

Example:

5

Page 6: CORE  JAVA

//postincrementationclass 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);

}}

The precedence of java operators:--

1) Increment and Decrement Operator2) Arithmetic Operations3) Comparisons4) Logical Operations5) Assignment Operations

Highest() [] .

++ -- ~ !

* / %

+ -

>> >>> <<

6

Page 7: CORE  JAVA

> >= < <=

==

!=

&

^

|

&&

||

?:

= 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;

7

Page 8: CORE  JAVA

int z = 0;//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");

8

Page 9: CORE  JAVA

}else{

System.out.println("It is negative");}

}}

Example 2:

//Nested if-elseclass 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 );

}}

9

Page 10: CORE  JAVA

2) do-while loop: This loop is used to repeat early execute a group of statements as long as 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);

}}

3) while loop: This loop is repeatedly execute a group of statements as long as given condition is true.

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;

10

Page 11: CORE  JAVA

for(;;)//infinite loop//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;

11

Page 12: CORE  JAVA

case '2':System.out.println(a-b);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.

// Using break to exit a loop.class BreakLoop{public static void main(String args[]) {for(int i=0; i<=100; i++){//if(i == 10) break; // terminate loop if i is 10//0 to 9//if(i == 10) continue; //0 to100 except 10 if((i%2 == 0)) continue; System.out.println("i: " + i);}System.out.println("Loop complete.");}}

Break statement 2:

// Using break with nested loops.class BreakLoop2{public static void main(String args[]) {for(int i=0; i<3; i++) {System.out.print("Pass " + i + ": ");for(int j=0; j<100; j++)

12

Page 13: CORE  JAVA

{if(j == 10) break; // terminate loop if j is 10System.out.print(j + " ");}System.out.println();}System.out.println("Loops complete.");}}

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 callerSystem.out.println("This won't execute.");

}

}

13

Page 14: CORE  JAVA

Accept the value from keyboard:

Stream: A stream represents flow of data from one place to another place.

a) InputStream: InputStream read or receive data.b) OutputStream: OutputStream send or write data to some other place.

Note: All stream classes are available in java.io package.

System class:

1) System.in (represent keyboard)2) System.err (represent monitor and display error messages)3) System.ou (represent monitor and display general messages)

Example 1:

//Accepting data from keyboardimport java.io.*;class Input {

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

/*InputStreamReader obj=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(obj);*/

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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:

//Accepting Employee dataimport java.io.*;class Empdata{

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

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

14

Page 15: CORE  JAVA

System.out.println("Enter Id");int id=Integer.parseInt(br.readLine());System.out.println("Enter sex(M/F)");char sex=(char)br.read();br.skip(2);System.out.println("Enter Name");String name=br.readLine();System.out.println("Id-->"+id);System.out.println("Sex-->"+sex);System.out.println("Name-->"+name);

}}

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:

i) One dimensional array 1Dii) Two dimensional array 2Diii) Multi dimensional array 3D

1) One dimensional array 1D: One dimensional array represents a single row of data or a single column of data.

Creating One dimensional array:

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:

//One diamansional array exampleimport java.io.*;class Arr1 {

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

15

Page 16: CORE  JAVA

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("How many subjects");int n=Integer.parseInt(br.readLine());int marks[]=new int[n];for(int i=0;i<n;i++){

System.out.println("Enter Marks");marks[i]=Integer.parseInt(br.readLine());

}int tot=0;System.out.println("The marks are");for(int i=0;i<n;i++){System.out.println(marks[i]);tot=tot+marks[i];}System.out.println("Total Marks="+tot);float percent=(float)tot/n;System.out.println("Percent " +percent);System.out.println("The length of array="+marks.length);

}}

Example 2:

//The values pass into the runtime//import java.lang.*;class Arr2 {

public static void main(String a[]) {

int n=a.length;System.out.println("No.of args="+n);System.out.println("The args are");for(int i=0;i<n;i++)System.out.println(a[i]);

}}

Example 3:

//Character Array(1D)class CharArray{

public static void main(String[] args) {

char ch[]={'A','B','C','D'};System.out.println(ch[3]);

16

Page 17: CORE  JAVA

}}

2) Two dimensional array 1D: Two dimensional array represents several rows columns of elements.

Creating Two dimensional array:

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:

//Two diamensional array exampleclass Arr3 {

public static void main(String[] args) {

int x[][]={{23,56,47},{26,24,86},{12,56,64}};System.out.println("In Matrix Form:");for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

System.out.print(x[i][j]+"\t");}

System.out.println();}

}}

Example 2:

//Two diamensional character array exampleclass Arr4{

public static void main(String[] args) {

char x[][]={{'a','b','c'},{'d','e','f'},{'g','h','i'}};System.out.println("In Matrix Form:");for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

17

Page 18: CORE  JAVA

System.out.print(x[i][j]+"\t");}

System.out.println();}

}}

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]);//ArrayIndexOutOfBoundsExceptionSystem.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:

i) We can create a String by declaring and initializing a String class object.Ex: String st = “Hello”;

ii) Using new operator we can create a String class object and store data into it.

Ex: String st = new String(“Hello”);

iii) We can create a String class object from a character array.Ex: char a[]={‘h’,’e’,’l’,’l’,’o’}; String st = new String(a);

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

18

Page 19: CORE  JAVA

ii) Immutable Object: Immutable Objects are the Objects whose data can not be 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");elseSystem.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)

19

Page 20: CORE  JAVA

if(s1.equals(s2))System.out.println("Both are equals");elseSystem.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.

20

Page 21: CORE  JAVA

//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));//65System.out.println(str.codePointBefore(1));//65System.out.println(str.codePointCount(0,5));//5System.out.println(str.startsWith("Apt"));//trueSystem.out.println(str.endsWith("tions"));//trueSystem.out.println(str.toUpperCase());//APTECH GLOBAL LEARNING SOLUTIONSSystem.out.println(str.toLowerCase());//aptech global learning solutionsSystem.out.println(String.valueOf(array));//Aptech GlobalSystem.out.println(String.valueOf(array,7,6));// Globalchar[] array1;array1=str.toCharArray();System.out.println(String.valueOf(array1));//Aptech Global Learning SolutionsSystem.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)*/

21

Page 22: CORE  JAVA

//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));//GSystem.out.println(sb.deleteCharAt(5));//Aptec Global Learning Solutionschar[] array=new char[10];sb1.getChars(0,6,array,0);System.out.println(array);//AptechSystem.out.println(sb1.length());//32System.out.println(sb1.replace(23,32,"Services"));//Aptech global Learning Servicessb1.setCharAt(7,'g');System.out.println(sb1);//Aptech global Learning Services//sb1.setLength(35);System.out.println(sb1);//Aptech global Learning Servicessb1.setLength(13);System.out.println(sb1);//Aptech global StringBuffer sb2=new StringBuffer();System.out.println(sb2.capacity());//16System.out.println(sb1.capacity());//48

//capacity=length+16 String str;

str=sb1.substring(7);System.out.println(str);//global Learning Services

22

Page 23: CORE  JAVA

str=sb1.substring(7,13);System.out.println(str);//global

}}

OOPS(Object Oriented Programming System)

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:

1) Object and class

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.

2) Encapsulation: Writing variables and methods as a single unit is called encapsulation. Class is an example of encapsulation. The advantage of encapsulation is the programmer can use same name for the member of two different classes.

3) Abstraction: Hiding unnecessary data from the user is called abstraction.

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

5) Polymorphism: If something exist in various forms it is called polymorphism. If a single method perform various task it is called polymorphism.

6) Message passing: Calling a method is called message passing.

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.

23

Page 24: CORE  JAVA

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 with Private specifier:

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{

public static void main(String[] args) {

Person p1=new Person();p1.talk();

Person p2=new Person();p2.name="san";p2.age=25;p2.talk();}

}/*note: Defect in this program is if we declare the variables as private we can't use that variable in other class*/

24

Page 25: CORE  JAVA

Problem 2:

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);

25

Page 26: CORE  JAVA

}}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: A constructor is similar to a method which initializes the instance variables of a class. A constructor name and class name should be same. A constructor may have parameters and may not have parameters. A constructor without any parameter is called default constructor. A constructor with one or more parameters is called parameterized constructor. A constructor does not return any value not even void. A constructor is called only once at the time of creating an object.

Q: What is the difference between default constructor and parameterized constructor?A: default constructor is used to initialize every object with same data. Parameterized constructor is used to initialize every object with different data.

Constructor Overloading: Writing two or more constructor with the same name but with a difference in the parameter is called constructor overloading.

Example:

//Parameterized Constructorclass 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;

}

26

Page 27: CORE  JAVA

Constru(String a,int b,int c){

this.a=a;this.b=b;this.c=c;

}void display(){

System.out.println("Hello name is-->"+a);System.out.println("Hello age is-->"+b);System.out.println("Hello age is-->"+c);

}}class Paramcon{

public static void main(String[] args) {Constru c1=new Constru();c1.display();Constru c2=new Constru();c2.display();Constru c3=new Constru("san",25);c3.display();Constru c4=new Constru("Ram",55);c4.display();Constru c5=new Constru("xxx",58,54);c5.display();Constru c6=new Constru("ddd",53,44);c6.display();}

}//Note: In this program we are able to get different set of values by using parameterized constructor, even the variable are declared as private.

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.

27

Page 28: CORE  JAVA

Method Without Return Type Example:

//Method without return typeclass Wrt {

double d1,d2;Wrt(double x,double y)//Parameterized constructor{

d1=x;d2=y;

}void sum(){

double d3=d1+d2;System.out.println("sum="+d3);

}}class DemoWrt{

public static void main(String[] args) {

Wrt s=new Wrt(10.3,20.5);s.sum();Wrt s1=new Wrt(10.4566,20.55556);s1.sum();

}}

Method WithReturn Type Example:

//Method with return typeclass Withrt {

double d1,d2;Withrt(double x,double y){

d1=x;d2=y;

}double sum(){

//double d3=d1+d2;//return d3;return d1+d2;

}}class DemoWithrt

28

Page 29: CORE  JAVA

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

Withrt s=new Withrt(10.3,20.5);System.out.println("sum="+s.sum());Withrt s1=new Withrt(23.5,12.6);System.out.println("sum="+s1.sum());}

}

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:

//Static method exampleclass Sta{

//static int a=10;static int a1=10;

static void display(){

System.out.println(a1);}

}class Static

{public static void main(String[] args)

{Sta.display();

}}

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.

29

Page 30: CORE  JAVA

Example:

//Accesor and Mutator methodclass Person{

String name;int age;char sex;Person(String name,int age,char sex){

this.name=name;this.age=age;this.sex=sex;

}//Accesor Methodvoid display(){

System.out.println("Name-->"+name);System.out.println("Age-->"+age);System.out.println("Sex-->"+sex);

}//Mutator MethodPerson modify(Person obj){

obj.name="yyy";--obj.age;obj.sex='F';return obj;

}}class MutaAcc{

public static void main(String[] args) {

Person p=new Person("xxx",36,'M');p.display();Person p1=p.modify(p);//Here we are not creating an object to p1. Here p1 is a reference variable.p1.display();p.display();Person p2=new Person("sai",22,'M');p2.display();}

}

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

30

Page 31: CORE  JAVA

use Factory Method we can not use new operator.

Example:

//Example for Factory Methodimport java.text.*;class FactMe {

public static void main(String[] args) {

final double PI=(double)22/7;double r=54.87;double area=PI*r*r;System.out.println("Area="+area);NumberFormat obj=NumberFormat.getNumberInstance();obj.setMaximumFractionDigits(2);String str=obj.format(area);System.out.println("Formatted Area="+str);obj.setMinimumFractionDigits(6);String str1=obj.format(area);System.out.println("Formatted Area="+str1);

}}

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:

//Inner class exampleclass BankAcct//Outer class {

private double bal;BankAcct(double b){

bal=b;}void start(double r){

Interest in=new Interest(r);in.calculateInterest();

}private class Interest//Inner class{

private double rate;

31

Page 32: CORE  JAVA

Interest(double r){

rate=r;}void calculateInterest(){

double interest=bal*rate/100;System.out.println("Interest="+interest);bal+=interest;System.out.println("Balance="+bal);

}}

}class InnerDemo{

public static void main(String[] args) {

BankAcct acct=new BankAcct(100000);acct.start(3);

}}

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 Inheritance2) Multilevel Inheritance3) Multiple Inheritance4) Hierarchical Inheritance5) Hybrid Inheritance

Example 1:

//Example of Inheritance(using setters and getters methods)class Teacher {

int id;String name,addr;void setId(int id){

this.id=id;}int getId()

32

Page 33: CORE  JAVA

{return id;

}void setName(String name){

this.name=name;}String getName(){

return name;}void setAddr(String addr){

this.addr=addr;}String getAddr(){

return addr;}

}

class Student extends Teacher{

int marks;void setMarks(int marks){

this.marks=marks;}int getMarks(){

return marks;}

}

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());

}

33

Page 34: CORE  JAVA

}

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.

34

Page 35: CORE  JAVA

Example 3:

//Example for super

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:

35

Page 36: CORE  JAVA

a) Static polymorphismb) Dynamic polymorphism

Dynamic polymorphism: Dynamic means at runtime. The polymorphism executed at runtime is called dynamic polymorphism or runtime polymorphism or dynamic binding or dynamic linking. Here java compiler does not know which method is called by the user at the time of compilation. JVM can bind the method, call with the method body at the time of running the program.

Example:Method Overloading: Writing two or more methods with the same name but with different method Signature.

//Method Overloadingclass 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:

a) There may be a difference in the number of parameter.Ex: void add(int a, int b) void add(int a, int b, int c)

36

Page 37: CORE  JAVA

b) There is a difference in the data type of parametersEx: void add(int a, int b) void add(float a, float b)

c) There is a difference in the sequence of parameters.Ex: int swap(int a, char b) Int swap(char a, int b)

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 Overridingclass 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) {

Two t=new Two();t.calculate(25);t.calculate(9);t.calculate(36);

}}

Static Polymorphism: The Polymorphism executed at compile time is called static polymorphism

37

Page 38: CORE  JAVA

or static binding.Use of Final keyword:

1) Final keyword is writing before constants.2) Final keyword is used before the class name to prevent inheritance.3) Final methods can not be overridden.

Type Casting or Casting: Converting one data type into another type is called type casting or casting.

Casting primitive data type:

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.

A method without method body is called a abstract method. A class that contains abstract method is called abstract class. To declare abstract method class should be declare using keyword abstract. Concrete methods mean complete methods. We cannot create object to abstract class.

Points:

1) An abstract class is a class with zero or more abstract methods.2) An abstract class can have abstract method, concrete method and instance

variables. 3) Both the abstract class and abstract methods should be declared as abstract.4) We cannot create an object to abstract class.5) We can create reference variables of abstract class type.6) All the abstract methods of abstract class should be implemented in its

subclasses.7) If any method is not implemented that subclass should also be declare as

abstract.8) Abstract class reference variable can be used to refer to the objects.9) Abstract class reference cannot refer to individual method of a class.10) A class cannot have both abstract and final.

38

Page 39: CORE  JAVA

Example:

abstract class Car {

int regno;Car(int regno){

this.regno=regno;}void fillTank()//concrete method{

System.out.println("Fill Tank");}abstract void steering(int direction);abstract void breaking(int force);

}class Maruti extends Car{

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");

39

Page 40: CORE  JAVA

}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:

1) Interface is a specification of method prototype or method header.2) An interface contains zero or more abstract methods.3) All the methods of the interface are public and abstract by default.4) An interface can also contain variables which are public, static and final by

default.5) When an interface is written any third party vendor can implement it.6) All the abstract method of the interface should be implemented in a class called

implementation class.7) If any method is not implemented than that class should be declare as abstract.8) We cannot create an object to an interface.9) We can create a reference of an interface.10) Interface reference can be used to refer to the objects of its implementation

classes.11) We can write a class within an interface.12) An interface cannot implement another interface.

40

Page 41: CORE  JAVA

13) An interface can extends another interface. 14) A single class can implement multiple interfaces.

Example1:

import java.io.*;interface MyInter{

void connect();}

class OracleDb implements MyInter{

public void connect(){

System.out.println("Connecting to oracle");}

}class SybaseDb implements MyInter{

public void connect(){

System.out.println("Connecting to sybase");}

}class Inter {

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

/*Class c=Class.forName(args[0]);MyInter mi=(MyInter)c.newInstance();mi.connect();*/

OracleDb ob=new OracleDb();SybaseDb sb=new SybaseDb();MyInter m1,m2;m1=ob;m1.connect();m2=sb;m2.connect();

}}

Example 2:

//An Interface can extends more than one interface,but one interface can't implements another interface

41

Page 42: CORE  JAVA

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:

//class inside interfaceinterface Outer{

void disp();class Inner{

42

Page 43: CORE  JAVA

void test(){

System.out.println("Inner");}

}}class Main implements Outer{

public void disp(){

System.out.println("disp");}

}class Inter2{

public static void main(String[] args) {

Main m=new Main();m.disp();Outer.Inner i=new Outer.Inner();i.test();System.out.println("Hello World!");

}}

Multiple Inheritance: Java doesn’t support multiple inheritance. We can achieve multiple inheritance by using multiple interfaces.

Example:

//Multiple inheritance by using multiple interfaceinterface Father{

int PROP1=50000;float HT1=6.2F;

}interface Mother{

int PROP2=20000;float HT2=5.4F;

}class Child implements Father,Mother{

void property(){

System.out.println("Child property="+(PROP1+PROP2));}

43

Page 44: CORE  JAVA

void height(){

System.out.println("Child height="+(HT1+HT2)/2);}

}class Multi {

public static void main(String[] args) {

Child c=new Child();c.property();c.height();

}}

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) {

44

Page 45: CORE  JAVA

Addition a=new Addition(24,534);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;

45

Page 46: CORE  JAVA

public class Sample{

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:

Bug: A bug is an error in software. Debugging means removing the errors

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.

Exception: An Exception represents runtime 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.

46

Page 47: CORE  JAVA

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:

//handling the exceptionclass Exce1 {

public static void main(String[] args) {

System.out.println("open the files");try{

int n=args.length;System.out.println("Number of args are"+n);

47

Page 48: CORE  JAVA

int a=45/n;}catch(Exception ae){

System.out.println(ae);}finally{

System.out.println("close the file");}

}}

1) Exception Handling means there will not be a damage or no loss of data. 2) By using multiple catch blocks we can handle multiple exceptions.3) A try block can be followed by several catch blocks.4) A catch block does not exist without a try block.5) A try block exists without catch block.6) One exception we can handle at a time even though there is multiple exceptions.

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;

}

48

Page 49: CORE  JAVA

catch(ArrayIndexOutOfBoundsException e){

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)

49

Page 50: CORE  JAVA

{System.out.println("From Main Divide By ZERO "+e);

} NestedTryMethods.nestedTry(1);}

}

Example:

//throw exampleclass 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;

System.out.println("No of Command Line Arguments = "+a);

int b = 10/a;

System.out.println("After Div value ="+b);

int c[] = {10,20,30,40,50,60};

50

Page 51: CORE  JAVA

c[31] = 789;for(int i=0;i<c.length;i++)

System.out.println(c[i]);}

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 for userdefined exceptionclass MyExce extends Exception {

private static int accno[]={1001,1002,1003,1004};private static String name[]={"san","man","van","ran"};private static double bal[]={12000,500,75,1999};MyExce(){}MyExce(String str){

super(str);}public static void main(String[] args) {

try{System.out.println("Accno"+"\t"+"name"+"\t"+"balance");for(int i=0;i<4;i++)

51

Page 52: CORE  JAVA

{System.out.println(accno[i]+"\t"+name[i]+"\t"+bal[i]);if(bal[i]<2000)

{/*MyExce me=new MyExce("Balance amount is less");throw(me);*/throw new MyExce("Balance amount is less");}

}}catch(MyExce me){

//System.out.println(me);me.printStackTrace();

}}

}

Example:

class MyException extends Exception{ private int data; MyException(int n) { data = n;

System.out.println("In MyException "); } public String toString() { return " Exception raised... due to low bal ["+data+"]"; } }

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

{

52

Page 53: CORE  JAVA

check(1000);check(350);

} catch(MyException me) {

System.out.println(me); }

}}

Exception List:

Exception Meaning:

1) ArithmeticException Arithmetic error, such as divide-by-zero.

2) ArrayIndexOutOfBoundsException Array index is out-of-bounds.

3) ArrayStoreException Assignment to an array element of an incompatible type.

4) ClassCastException invalid cast.

5) IllegalArgumentException Illegal argument used to invoke a method.

6) IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.

7) IllegalStateException environment or application is in incorrect state.

8) IllegalThreadStateException Requested operation not compatible with current thread state.

9) IndexOutOfBoundsException Some type of index is out-of-bounds.

10) NegativeArraySizeException array created with a negative size.

11) ClassNotFoundException class not found.

12) CloneNotSupportedException Attempt to clone an object that does notimplement the Cloneable interface.

13) IllegalAccessException Access to a class is denied.

14) InstantiationException Attempt to create an object of an abstract class or interface.

15) InterruptedException One thread has been interrupted by another thread.

53

Page 54: CORE  JAVA

16) NoSuchFieldException A requested field does not exist.

17) NoSuchMethodException A requested method does not exist.

18) NullPointerException invalid use of a null reference.

19) NumberFormatException invalid conversion of a string to a numeric format.

20) SecurityException Attempt to violate security.

21) StringIndexOutOfBoundsException Attempt to index outside the bounds of a string.

22) UnsupportedOperationException An unsupported operation was encountered.

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 Testimport 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");elseSystem.out.println("Sorry I donot know that character");

}}

54

Page 55: CORE  JAVA

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);elseSystem.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{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter a number");String str=br.readLine();int n=Integer.parseInt(str);System.out.println("In decimal-->"+n);

55

Page 56: CORE  JAVA

str=Integer.toBinaryString(n);System.out.println("In binary-->"+str);str=Integer.toHexString(n);System.out.println("In hexadecimal-->"+str);str=Integer.toOctalString(n);System.out.println("In octal-->"+str);

}}

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.

2) OutputStream: OutputStream send or write data to 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) FileInputStream2) FilterInputStream

a) BufferedInputStreamb) DataInputStream

3) Object InputStream

OutputStream Division:

1) FileOutputStream2) FilterOutputStream

a) BufferedOutputStreamb) DataOutputStream

3) Object OutputStream

CharacterStream or TextStream: They will handle the data in the form of chracters

Reader Division:

1) BufferedReader2) CharArrayReader3) InputStreamReader

a) FileReader4) PrintReader

56

Page 57: CORE  JAVA

Writer Division:

1) BufferedWriter2) CharArrayWriter3) OutputWriterr

a) FileWriter4) PrintWriter

Example 1:

//Creating a text file and enter the data into the fileimport 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:

//Without using type command Reading data from fileimport java.io.*;class Read{

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

FileInputStream fis=new FileInputStream("MyFile.txt");BufferedInputStream bin=new BufferedInputStream(fis);int ch;while((ch=bin.read())!=-1)System.out.print((char)ch);bin.close();

}}

57

Page 58: CORE  JAVA

Example 3:

//Using Writer create and pass the data into the fileimport 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:

//Reading file using FileReaderimport java.io.*;class Read2{

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

FileReader fr=new FileReader("textfile.txt");int ch;while((ch=fr.read())!=-1)System.out.print((char)ch);fr.close();

}}

Example 5:

//Accept file name from keyboard and display the contentimport java.io.*;class FileName{

public static void main(String[] args) {

try{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter file name");String fname=br.readLine();

58

Page 59: CORE  JAVA

FileInputStream ss=new FileInputStream(fname);BufferedInputStream bin=new BufferedInputStream(ss);int ch;while((ch=bin.read())!=-1)System.out.print((char)ch);bin.close();

}catch(Exception fe){

System.out.println("File not found"+fe);}

}}

Example 6:

//Zipping a file contentsimport java.io.*;import java.util.zip.*;class Zip {

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

FileInputStream fis=new FileInputStream("MyFile.txt");FileOutputStream fos=new FileOutputStream("File1.zip");DeflaterOutputStream dos=new DeflaterOutputStream(fos);int data;while((data=fis.read())!=-1)dos.write(data);fis.close();dos.close();fos.close();

}}

Example 7:

//Unzip the file contentsimport java.io.*;import java.util.zip.*;class Unzip{

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

FileInputStream fis=new FileInputStream("File1.zip");FileOutputStream fos=new FileOutputStream("File2.doc");InflaterInputStream iis=new InflaterInputStream(fis);int data;

59

Page 60: CORE  JAVA

while((data=iis.read())!=-1)//System.out.println(data);fos.write(data);//iis.close();fos.close();

}}

Serialization:

Example 1:

//Not implements Serializable interfacepublic class Cone{

public int varone;public float vartwo;public String varthr;

}

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);

60

Page 61: CORE  JAVA

}}

//implements Serializable interfaceimport java.io.Serializable;public class Ctwo implements Serializable{

public int varone;public float vartwo;public String varthr;

}

//Serialization Demoimport 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 Demoimport 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);

}}

//Using transient keyword varfr variable is not serializableimport java.io.*;

61

Page 62: CORE  JAVA

public class Ser2{

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

Ctwo1 o=new Ctwo1();o.varone=20;o.vartwo=32.3f;o.varthr=new String("hai");o.varfr=new Cone();FileOutputStream fos=new FileOutputStream("TestSer2");ObjectOutputStream oos=new ObjectOutputStream(fos);oos.writeObject(o);

}}

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);

}}

Threads: A thread represents a process or execution of statements.

Microprocessor uses internally a thread to execute the program.

Execution process or worked is called thread.

Example:

class Thr1 {

public static void main(String[] args) {

System.out.println("This is first statement");

62

Page 63: CORE  JAVA

Thread t=Thread.currentThread();t.setName("Mythread");System.out.println(t.isAlive());System.out.println("Thread name is");System.out.println("current thread="+t);}

}

Note: Every java program contains internally a thread called main. Default priority of main thread is 5 Thread group name is main

Executing statements is of 2 types:

1) Single Tasking: Executing only one task at a time is called single tasking

2) Multitasking: In multitasking several program executing at a time. We have two types in Multitasking

a) Process based multitasking: Executing several programs simultaneously is called process based multitasking.

b) Thread based multitasking: Executing different parts of the same program with the help of threads is called Thread based multitasking.

Example 1:

//creating and running a thread using extends Threadimport java.io.*;class Tdemo extends Thread {

public void run(){

for(int i=0;i<10;i++){System.out.println(i);try

{Thread.sleep(1000);//1000ms=1s}catch(Exception e){

System.out.println(e);}

}}

63

Page 64: CORE  JAVA

}class Thr2{

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

Tdemo obj=new Tdemo();Thread t=new Thread(obj);t.start();

}}

Example 2:

//creating and running a thread using implements Runnableclass Theatre implements Runnable {

String str;Theatre(String str){

this.str=str;}public void run(){

for(int i=1;i<=5;i++){

System.out.println(str+" "+i);try{

Thread.sleep(1000);}catch(InterruptedException ie){

//System.out.println(ie);ie.printStackTrace();

}}

}}class Thr3{

public static void main(String args[]){

Theatre obj=new Theatre("cut ticket");Theatre obj1=new Theatre("see movie");Thread t1=new Thread(obj);Thread t2=new Thread(obj1);t1.start();

64

Page 65: CORE  JAVA

t2.start();}

}

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:

//Synchonization(two threads acting on single object)class Reserve implements Runnable{

int available=3;int wanted;Reserve(int i){

wanted=i;}public void run(){

synchronized(this){

System.out.println("The number of berths available="+available);if(available>=wanted){

String name=Thread.currentThread().getName();System.out.println(wanted+" "+"berths alloted for"+" "+name);try{

Thread.sleep(1000);available=available-wanted;

}catch(Exception e){}

}else

{System.out.println("sorry no berth to allot for next thread");

}}

}}

class Thr4{

public static void main(String args[]){

65

Page 66: CORE  JAVA

Reserve obj=new Reserve(1);Thread t1=new Thread(obj);Thread t2=new Thread(obj);Thread t3=new Thread(obj);Thread t4=new Thread(obj);t1.setName("First Thread");t2.setName("Second Thread");t3.setName("Third Thread");t4.setName("Fourth Thread");t1.start();t2.start();t3.start();t4.start();

}}

Example:

//Multiple Threads Democlass Thread1 extends Thread{

public void run(){

try{

for(int i=1;i<=10;i++){

System.out.println("Thread1:"+i);Thread.sleep(1000);

}}catch(InterruptedException e)

{System.out.println(e);}

}}class Thread2 extends Thread{

public void run(){

try{

for(int i=1;i<=10;i++){

System.out.println("Thread2:"+i);Thread.sleep(1000);

}

66

Page 67: CORE  JAVA

}catch(InterruptedException ie)

{System.out.println(ie);}

}}public class MultiThreadDemo{

public static void main(String args[]){

Thread1 t1=new Thread1();Thread2 t2=new Thread2();

t1.start();t2.start();

}}

Thread Priority:

Max Priority- 10Min Priority 5Norm Priority 1

Example:

//Priority Demopublic 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);

67

Page 68: CORE  JAVA

pd1.setPriority(MIN_PRIORITY);

pd1.start();pd2.start();

System.out.println("Priority of pd1 is "+pd1.getPriority());System.out.println("Priority of pd2 is "+pd2.getPriority());

}}

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.

Applet = byte code + HTML

Applet Life cycle methods:

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()

68

Page 69: CORE  JAVA

{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:

//Insert image into Appletimport java.applet.*;import java.awt.*;/*<applet code="MyApplet2.class" width=400 height=300></applet>*/public class MyApplet2 extends Applet {

public void init(){}public void paint(Graphics g){

Image i=getImage(getDocumentBase(),"OBJECT.gif");//move image from left to rightfor(int x=0;x<100;x++){

g.drawImage(i,x,50,this);}//make time delaytry{

Thread.sleep(1000);

69

Page 70: CORE  JAVA

}catch(InterruptedException IE){}}

}

<html><h1>My Image</h1><body bgcolor="red"><applet code="MyApplet2.class" width=400 height=300></applet></body></html>

Example 3:

//passing value from HTML to appletimport java.awt.*;import java.applet.Applet;public class MyApplet3 extends Applet{

Font f=new Font("Ariel",Font.BOLD,24);String msg;public void paint(Graphics g){g.setFont(f);g.setColor(Color.blue);g.drawString(msg,10,50);}public void init(){

msg=getParameter("para");if(msg==null)msg="Null value returned";

}}

<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>

70

Page 71: CORE  JAVA

</html>

Example 4:

//Draw graphicsimport 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>

71

Page 72: CORE  JAVA

72

Page 73: CORE  JAVA

73