+ All Categories
Home > Documents > Total Java Notes

Total Java Notes

Date post: 28-Dec-2015
Category:
Upload: karthik-smile
View: 50 times
Download: 9 times
Share this document with a friend
Description:
Total Java Notes, tutorial, work process
Popular Tags:
114
COMPLETE JAVA NOTES KARTHIKEYAN NOTES JAVA SYLLABUS 45 Hours Class: 1 1 Introduction of Java language 2 Data types 3 Access specifies 4 Difference between class and methods 5 Conversion or Wrapper classes 6 Basic Programs Class: 2 7 Operators 8 If Condition 9 For Loop 10While 11Do while 12Switch Class: 3 13Array Methods 14String Methods Class: 4 15Class and Object 16Calling method 17Method overloading THANKING YOU CREATED BY A.KARTHIKEYAN
Transcript
Page 1: Total Java Notes

COMPLETE JAVA NOTES

KARTHIKEYAN NOTES

JAVA SYLLABUS 45 Hours Class: 1

1 Introduction of Java language2 Data types3 Access specifies4 Difference between class and methods5 Conversion or Wrapper classes6 Basic Programs

Class: 27 Operators8 If Condition9 For Loop10While 11Do while12Switch

Class: 313Array Methods14String Methods

Class: 415Class and Object16Calling method17Method overloading18Method overriding19Constructor20Finalize

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 2: Total Java Notes

COMPLETE JAVA NOTES

Class: 521Static method and Static members22This keyword23Final keyword24Super keyword

Class: 625Abstract Class26 Interface27 Inheritance

Class: 728Package Creation29Exception Handling

Class: 830 Introduction to Util package31Date class32Vector class33ArrayList class34LinkList class35HashSet class36TreeSet class

Class: 937 Input and Output Stream classes and methods

Class: 1038 Introduction to Networking package39URL Classes40URLConnection Classes41 INetAddress Classes

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 3: Total Java Notes

COMPLETE JAVA NOTES

Class: 1142Socket Classes43ServerSocket Classes44ClientSocket Classes45DatagramPacket Classes46DatagramSocket Classes

Class: 1247 Introduction of multithreading48Extends Thread49 Implements Thread

Class: 1350 Introduction of JDBC51Connection between Ms Access to java with ODBC

Class: 1452 Introduction to Applet 53Basic Applet programs54Color Class55Font Class

Class: 1556 Introduction to Graphics57Line method58Rectangle method

Class: 1659Polygon method60Oval method61Arc method62 Image classes.

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 4: Total Java Notes

COMPLETE JAVA NOTES

Class: 1763 Introduction to AWT components64Label Class65Text Field Class66Button Class67Panel Class

Class: 1868 Introduction to Events69Mouse Events70Keyboard Events71 Item Events

Class: 1972Text Area Class73Scrollbar Class74Checkbox Class75Checkbox Group Class

Class: 2076Choice Class77List Class78Frame Class79Mouse Cursor Class

Class: 2180Menu bar Class81Popup Menu Class82Canvas Class

Class: 2283 Introduction of Layout84FlowLayout Class85GridLayout Class

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 5: Total Java Notes

COMPLETE JAVA NOTES

86BorderLayout Class87CardLayout Class

Class: 2388 Introduction to swings89Swings Controls or Components90Swings Windows91Swings Programs

Class: 2492Message box93Timer Class94ProgressBar Class95Dialog Class

Class: 2596Swings Menus Class97Swings Container98Swings Programs

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 6: Total Java Notes

COMPLETE JAVA NOTES

To set the java path:

Way to set the java Path:Right click to My computer go to propertiesClick

Go to Environment variables Click

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 7: Total Java Notes

COMPLETE JAVA NOTES

Goto User variable for Administrator Click New Button

Then click Ok Ok Ok

Go to Dos command check the java path:Start Run Cmd Ok

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 8: Total Java Notes

COMPLETE JAVA NOTES

Class: 1

Introduction of Java language: Java developed by sun micro system corporation. Java is plat form software Java is a general purpose Java is a pure oops concept Object oriented language was developed by sun micro system of

USA in 1991 Originally it is called as OAK by James gosling, one of the

inventor of the language Java was designed for the development of software for

consumer electronics devices like microwave ovens and remote controls

In the year 1995 .OAK replaced as java then we used to Internet concept

Java is the platform independent language. (It means write once and run anywhere)

Here program name and class name are same Java is the first programming that is not tied to any particular

operating system Java is an Internet programming language Java is a case sensitive

Using software:1. Java any version2. Net bean 6.03. Eclipse 3.0

Java calling steps:Package ClassesMethods

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 9: Total Java Notes

COMPLETE JAVA NOTES

Java programs divided into 2 types:1. Application programming

That program is based on console-based runner2. Applet programming (used for internet concept)

That program is based on web design and development)

Features of Java1. Platform Independent2. Compiler and interpreter3. OOPs4. Security5. Portability6. Distributed application (RMI, Sockets)7. Multi threading programming

Syntax for compiler:Javac <file name>.java

Syntax for Interpreter:Java <file name>

Way of execution: Compiler Interpreter

Source Code ------------Byte Code------------ Output

Java Program StructureClass <class name>{

[<Access Specifies>]Public static void main (String arg[] ){

<Statements>;}

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 10: Total Java Notes

COMPLETE JAVA NOTES

PROGRAM EXECUTION:Start notepad type your programSave your program <file name>.java

To see output:Then go to DOS command compile the programThen run the java program in consoleStart RunCmd or command (Enter)Go to your Folder AreaCompileRun See output

Constants of System classesout for outputin for inputerr for errorexit for terminate the program execution

Notes:DataInputStream:Class are first sound letter start with capital letter and every sound also start with capital letter

parseInt():Methods are first sound letter start with small letter and other every sound also start with capital letter

readLine( ):Used to get input from user at run time

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 11: Total Java Notes

COMPLETE JAVA NOTES

Difference between C++ and JAVA:

C++ JAVA

Operating overloading NotSupports all kinds of

inheritanceOnly single, multi level others achieved by interface concept

Delete operator to destroy the resource

Not available

Support destructor methods There, finalize () is usedSupport pointers Not use

Friend function specifies Not useCout<< System.out.printlnCin>> d.readLine()

Funcitons Methods#include<iostream.h> import java.io.*;

Java TypesJDK Java Development KitJVM Java Virtual MachineJSL Java Standard Library

Data types:

Data types ByteInt 4 bytesLong int 8 bytesChar 2 bytesFloat 8 bytesDouble 16 bytesString( S should be capital because default data type is string)

No need

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 12: Total Java Notes

COMPLETE JAVA NOTES

Access specifies:Public Call any wherePrivate Access within only the function not for other classesProtected only used for Inheritance ConceptPackage Used for calling package access

Basic Programs:Eg://To display my nameclass p1{

public static void main(String s[]){

System.out.print("karthikeyan");}

}Eg://Eg for Data typesclass p2{

public static void main(String arg[]){

int i=10;char c='z';double d=10.00;float f=10.50f;String s="karthikeyan";System.out.println("int value is:"+i);System.out.println("char value is:"+c);System.out.println("double value is:"+d);System.out.println("float value is:"+f);System.out.println("string value is:"+s);

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 13: Total Java Notes

COMPLETE JAVA NOTES

Conversion or Wrapper classes:Used to convert data type from one data type to another data type

Data type ConversionInt Integer.parsInt(d.readLine());Char Char.parseChar(d.read());

Or(char)d.read();

Float Float .parseFloat(d.readLine( ));Double Double.parseDouble(d.readLine());String No need because default data type is String

Eg://Eg for character conversionimport java.io.*;class p4{

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

char c;DataInputStream d=new DataInputStream(System.in);System.out.print("Enter any character:");c=(char)d.read();System.out.print("characater is:"+c);

}}

Exception:Some abnormal condition an error can be occurring to avoid this error we can use exception conceptEnd the main function use throws ExceptionUsing package import java.io.*;

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 14: Total Java Notes

COMPLETE JAVA NOTES

Class: 2

Operators:Operator is a Symbol, Which is used to do some arithmetic Operations

Arithmetic Operator:

Operator Meaning+ Addition- Subtraction* Multiplication/ Division% Modulus (After division

Remainder)

Relational Operator:

Operator Meaning> Greater Than< Lesser than>= Greater than or equal to<= Less than or equal to= = Equal to< > ,! = Not Equal t

Logical Operator:

Operator Meaning&& AND (Both condition True)|| OR (Any one condition True)! NOT

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 15: Total Java Notes

COMPLETE JAVA NOTES

Assignment Operator:

Operator Meaning+=-=*=/=

Unary Operator:

Operator Meaninga++ Post increment++a Pre Incrementa-- Post Decrement--a Pre Decrement

Conditional Operator:Conditional operator is used to check conditionSyntax:(<Condition>)? <True statement> : <false statement>;

Special Operator:

Operator Meaning{ Left Brace}

Right Brace

( Left Parenthesis) Right Parenthesis[ Left Square Bracket] Right Square Bracket

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 16: Total Java Notes

COMPLETE JAVA NOTES

Eg://Eg for Arithmetic operatorimport java.io.*;class p3{

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

DataInputStream d= new DataInputStream(System.in);int a,b;System.out.print("Enter the a value:");a=Integer.parseInt(d.readLine());System.out.print("Enter the b value:");b=Integer.parseInt(d.readLine());System.out.println("Addition is:"+(a+b));System.out.println("Subtraction is:"+(a-b));System.out.println("Multiplication is:"+(a*b));System.out.println("Division is:"+(a/b));System.out.println("Modulus is:"+(a%b));

}}

If ConditionIf condition, Else if condition, Ladder If condition, Nested If condition

Syntax for if condition:If (<condition>){

< True statements>;}else{

< False statements>;}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 17: Total Java Notes

COMPLETE JAVA NOTES

Eg://Eg for if conditionimport java.io.*;class p5{

public static String u,p;public static void main(String arg[])throws Exception{

DataInputStream d=new DataInputStream(System.in);System.out.print("Enter the user name:");u=d.readLine();System.out.print("Enter the password:");p=d.readLine(); if(u.equals("karthi")&&(p.equals("bss"))){

System.out.print("Login : SUCCESS");}else{

System.out.print("Login : FAILED");}

}}

For Loop:They have 3 function 1) starting value 2) condition 3) inc or Dec

Syntax for normal for loop:for (<variable name> = <starting >; <condition>; <Inc / Dec>){

<Statements>;.

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 18: Total Java Notes

COMPLETE JAVA NOTES

Eg://To display table format by using for loopimport java.io.*;class p6{

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

int n,c,i;DataInputStream d=new DataInputStream(System.in);System.out.print("Enter which table u want::");n=Integer.parseInt(d.readLine());System.out.print("Enter how many number u want:");c=Integer.parseInt(d.readLine());for(i=1;i<=c;i++){

System.out.println(i+"*"+n+"="+(i*n));}

}}

While:

In while first they check condition after given true statements are executed

Syntax for while condition:While (<condition>){

< True statements>;...

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 19: Total Java Notes

COMPLETE JAVA NOTES

Eg://Eg for whileclass p7{

public static void main(String arg[]){

int i=1;System.out.println("Display odd number 1 to 10");do{

System.out.println(i);i=i+2;

}while(i<10);

}}

Do while:Do While first given statements are executed after they check conditionDo while statements end with semicolon

Syntax for do while condition:

do{

< True statements>;...

}While (<condition>);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 20: Total Java Notes

COMPLETE JAVA NOTES

Eg://Eg for do whileclass p8{

public static void main(String args[]){

int i=1;do{

int j=i*5;System.out.println(i+"*5="+j);i++;

}while(i<=10);

}}

Switch:They check a condition by case formatCase should be end with colon not for semicolon

Syntax for switch:switch(<Exp>){

case <Exp1>:<Statements>;break;case <Exp2>:<Statements>;break;

.default:< default statements>;

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 21: Total Java Notes

COMPLETE JAVA NOTES

}

Eg://Eg for switchclass p9{

public static void main(String args[]){

int i=1;switch(i){

case 0:System.out.println("The case Zero");break;case 1:System.out.println("The case One");break;default:System.out.println("Default");break;

}}

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 22: Total Java Notes

COMPLETE JAVA NOTES

Class: 3Array Methods:Array means declare one variable store more than one value in same data type as in same variable name is called arrayThey are two types in Array:1) Single Dimensional Array2) Multi Dimensional Array

Syntax for single dimensional array:<Data type> <var1>[ ] = new <data type> [ <size> ];Syntax for Array initialization:<Data type> <var1> [ ] = {<values>};(Or)<Data type> [ ] <var1> = {<values>};Length:Used to find the Total size of arraySyntax for length:<Variable name>.length

Multi dimensional array:Multi dimensional array is mostly used for matrix addition or matrix Subtraction or matrix multiplication Syntax for Multi dimensional array:<Data type> <var1> [ ] [ ] = new <data type> [<size>] [<size>];

Syntax for Array initialization:<Data type> <var1> [ ] [ ] = {<values>} {<values>};(Or)<Data type> [ ] [ ] <var1> = {<values>} {<values>};

Eg:int a [ ] [ ] = { 34,23,67,74} {34,12,56,23 };(Or)

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 23: Total Java Notes

COMPLETE JAVA NOTES

int [ ] [ ]a = { 34,23,67,74} {34,12,56,23 };Eg://Eg for Array intializationclass p11{

public static int a[]={1,5,4,12,18};public static int i;public static void main(String arg[]){

System.out.println("Array value are:");for(i=0;i<a.length;i++){

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

}}

Eg://Eg for Array run time valueimport java.io.*;class p12{

public static int a[]=new int[5];public static int i;public static void main(String arg[])throws Exception{

DataInputStream d=new DataInputStream(System.in);System.out.println("Enter the five values:");for(i=0;i<a.length;i++){

a[i]=Integer.parseInt(d.readLine());}System.out.println("Given Array value are:");for(i=0;i<a.length;i++)

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 24: Total Java Notes

COMPLETE JAVA NOTES

{System.out.println(a[i]);

}}

}

Eg://Eg for double dimensional Array intializationclass p13{

public static int a[][]={1,5} {12,18};public static int i,j;public static void main(String arg[]){

System.out.println("Array values are:");for(i=0;i<a.lenght;i++){

System.out.print("\n\n");for(j=0;j<a.length;j++){

System.out.print(a[i][j]);System.out.print("\t\t");

}}

}}

Eg://Eg for character arrayclass p14{ public static void main(String ar[]) {

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 25: Total Java Notes

COMPLETE JAVA NOTES

String s=new String("This is my String"); System.out.println(s.length()); char c[]=new char[s.length()];

c=s.toCharArray();System.out.println(c);for(int i=0;i<c.length;i++)

{ System.out.println(i+" :"+c[i]);

} }

}

Eg://Eg for multidimensional arrayclass p15{

public static void main(String arg[]){

int r=10;int c=10;int p[][]=new int[r][c];System.out.println("Multiliplication Table");System.out.println(" ");for(int i=1;i<r;i++){

for(int j=1;j<c;j++){

p[i][j]=i*j;System.out.println(i+" * "+ j + ":= "+p[i][j]);

}System.out.println(" ");

}}

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 26: Total Java Notes

COMPLETE JAVA NOTES

String Methods:String means more than one character Here we don’t use any package

S.NO Syntax for methods Meaning

1<s1>. toUpperCase( ) Convert lower case to upper

case

2<s1>. toLowerCase( ) Convert upper case to lower

case

3<s1>.length( )

Find the length of string

4<s1>.charAt(<nth> ) Display given nth position of

character

5<s1>.subString(<start

pos>,< up to no of character> )

Extract given character from the string

6<s1>.indexOf(<char>); Display first occurrence of the

character position

7<s1>.lastIndexOf(<char>); Display last occurrence of the

character position

8<s1>.reverse();

Reverse the given string

9concat(<s1>,<s2>);

Attach two strings

10<s1>.startsWith(<char>) String starts from the given

character

11<s1>.endsWith(<char>) String ends from the given

character

12<s1>trim(); Remove white spaces front and

back

13 <s1>.equals(<s2>)Check two string are equal or not if return =0 equal else not

equal

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 27: Total Java Notes

COMPLETE JAVA NOTES

14<s1>.equalsIgnoreCase(<s

2>

Check two string are equal or not but it ignore the case

sensitiveEg://Eg for stringmethodclass p12{

public static void main(String arg[]){

String s1="karthik";String s2="KEYAN";String s3=" java

";String s4="KARTHIK";System.out.println("Upper case

is:"+s1.toUpperCase());System.out.println("Upper case

is:"+s2.toLowerCase());System.out.println("Length of s1 is:"+s1.length());System.out.println("s1 3 rd position char

is:"+s1.charAt(3));System.out.println("Substring of s1

is:"+s2.substring(2,4));System.out.println("s1 r position is:"+s1.indexOf('k'));System.out.println("s1 r position

is:"+s1.lastIndexOf('k'));//System.out.println("s1+s2 :"+concat(s1,s2));//System.out.println("starts with t

is:"+s1.startsWith('t'));//System.out.println("End with t is:"+s2.endsWith('Y'));System.out.println("Without removing space:"+s3);System.out.println("Removing space:"+s3.trim());if(s1.equalsIgnoreCase(s4)){

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 28: Total Java Notes

COMPLETE JAVA NOTES

System.out.println("s1 and s4 string are Equal");}else{

System.out.println("s1 and s4 string are Not Equal");

}}

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 29: Total Java Notes

COMPLETE JAVA NOTES

Class: 4Class and Object:Class means collections of methods & members or variablesAn object is an instance of a class which is used to access members of class

Class Declaration syntax:class <class name>{

< Declaration parts>;...

}class <class name or program name>{

<main function>( ){

<class name> <object name> = new <class name>( );<Object name>.<members>;<Object name>.<methods>(args[ ]);

.}

}

Eg://Eg for class and objectclass demo1{

public static void disp(){

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 30: Total Java Notes

COMPLETE JAVA NOTES

System.out.println("Hai this is first class method");}

}class demo2{

public static void disp(){

System.out.println("Hai this is second class method");}

}class demo3{

public static void disp(int x,String n){

System.out.println("Class3 int x value is:"+x);System.out.println("Class3 String n value is:"+n);

}}class p14 extends demo1{

public static void main(String arg[]){

disp();demo2 s1=new demo2();s1.disp();demo3 s2=new demo3();s2.disp(10,"karthi");

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 31: Total Java Notes

COMPLETE JAVA NOTES

Calling Methods:Calling Methods are function that operate on instant of classes are which they are defined object can communicate with each other. Using methods & can call methods in other classes

Syntax for Function or methods Declaration:< Return type> <method name> ( ){

< Statements >;.

}

Argument methods:Functions have any argument that methods have argument methods

Syntax for Arguments:

< Object name>. < method name>(<type1>,<type2>);

Eg://Eg for Calling members and Argument methodsimport java.io.*;class demo{

public static String n,d;public static int s;public static void show(String a,String b,int c){

System.out.println("Name is:"+a);System.out.println("Designation is:"+b);System.out.println("Salary is:"+c);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 32: Total Java Notes

COMPLETE JAVA NOTES

}}class p30 extends demo{

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

p30 ss = new p30( );ss.n="kumar";ss.d="software Engineer";ss.s=10000;ss.show(ss.n,ss.d,ss.s);

}}

Method overloading:Same function name or methods name but different types of arguments is called method overloading

Syntax for method overloading:< Return type> <same method name> (<different Arg>){

< Statements >;}< Return type> <same method name> (<different Arg>){

< Statements >;}

Eg://Eg for Method overloadingimport java.io.*;class demo{

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 33: Total Java Notes

COMPLETE JAVA NOTES

public static void show(int x,int y){

System.out.println("x value is:"+x);System.out.println("y value is:"+y);

}public static void show(String j,String k){

System.out.println("j name is:"+j);System.out.println("k name is:"+k);

}}class p31 extends demo{

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

p31 s=new p31( );s.show(10,5);s.show("karthi","senthil");

}}

Method Overriding:Same method name and same types of arguments are called method overriding

Constructor:Constructor when and object is created for class it call automaticallyHere you don’t use return type in front of methods name

Rules of making constructor:Constructor method name must name must be same as class nameConstructor does not return any values. So we don’t use return typeConstructors have argumentsTypes of constructor:

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 34: Total Java Notes

COMPLETE JAVA NOTES

Default constructor or Empty constructorParameter constructor or Argument constructorHere we don’t use Copy constructor Default constructor or empty constructor:Constructor methods have without any argument is called default constructor or empty constructor

Argument constructor or parameter constructor: Constructor methods have any argument is called argument constructor or parameter constructor

Eg://Eg for Constructorclass demo{

public demo(){

System.out.println("This is empty constructor");}public demo(int x,float f,String s){

System.out.println("X value is:"+x);System.out.println("Float value is:"+f);System.out.println("String s value:"+s);

}}class p17{

public static void main(String arg[]){

demo d=new demo();demo d1=new demo(10,18.24f,"java");

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 35: Total Java Notes

COMPLETE JAVA NOTES

}

Finalize:Finalize method or function is contradiction (opposition) to the constructor methodThe finalize method is represented by the keyword “ finalize ”Syntax for finalize:Protected void finalize ( ){

<Statements>;}We use only Boolean data type to check either true or falseEg://Eg for finalize conceptclass demo{

public demo(){

System.out.println("Memory is allocated");}protected void finalize(){

System.out.println("Memory is deallocated");}

}class p18{

public static void main(String arg[]){

while(true){

demo s= new demo();}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 36: Total Java Notes

COMPLETE JAVA NOTES

}}

Class: 5Static method and Static members:Static variable can be initializing only onceAll objects that are initialized zero automatically share static membersStatic method only allows a static member or static variablesStatic methods are called without making objectWithout using object we can call function by using static keyword

Eg:class statictest{

static int count=0;public statictest(){

count++;}public void display(){

System.out.println(count);}public static void main(String a[]){

statictest s=new statictest();s.display();statictest s1=new statictest();s1.display();

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 37: Total Java Notes

COMPLETE JAVA NOTES

This keyword:

Final keyword:

Super keyword:

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 38: Total Java Notes

COMPLETE JAVA NOTES

Class: 6Abstract Class:Abstract class is an incomplete class.It is an collection of abstract behaviors of its sub classesInstance cannot be created using abstract class.Sub classes can in heritance variables & methods from them.Classes that cannot be instantiated directly Abstract classes exist.

Syntax for Abstract Class:abstract class < class name 1>{

abstract <return type > <method name 1>( );//Concrete methods are still allocated in abstract classes

}

Eg:abstract class bank{

abstract void balance();}

Eg:class icicibank extends bank{

void balance(){

System.out.println("Icicibank balance:"+5,00,000");}

}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 39: Total Java Notes

COMPLETE JAVA NOTES

Eg:class indianbank extends bank{

void balance(){

System.out.println("Indian Bank:"+8,00,000");}

}

Eg:class sbibank extends bank{

void balance(){

System.out.println("SBI Balance"+1,00,000");}

}

Eg:class p22 {

public static void main(String arg[]){

sbibank s1=new sbibank();s1.balance();icicibank s2=new icicibank();s2.balance();indianbank s3=new indianbank();s3.balance();

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 40: Total Java Notes

COMPLETE JAVA NOTES

Interface:Interface is a collection of abstract behaviors that individual classes can implementsInterface designed to support dynamic method (random methods) or to access same name methods

Notes:Implements are a keyword that used for implementing an interface a class

Syntax for interface:[<Access specifies>] interface <interface name>{

<Return type> <Methods name1>( );}class <base class name> implements <interface name>{

<Return type> <Methods name1>( ){

<Statements>;}

}class <derived class name> implements <interface name>{

<Return type> <Methods name1>( ){

<Statements>;}<Main method statements>( ){

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 41: Total Java Notes

COMPLETE JAVA NOTES

<Statements>;}

}

Eg://Eg for interface conceptinterface interface1{

public void disp();}class base1 implements interface1{

public void disp(){

System.out.println("This is Base class Interface ");}

}class p23 implements interface1{

public void disp(){

System.out.println("This is Derived class Interface ");}public static void main(String arg[]){

p23 s1=new p23();base1 s2=new base1();s1.disp();s2.disp();

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 42: Total Java Notes

COMPLETE JAVA NOTES

Inheritance:Creating a new class from an existing classNew class is called as derived or inherited class and the existing class is called as base or super classNotes:Here extends keyword is used to call base class to another derived class

Types of inheritance:1. Single Inheritance2. Multilevel Inheritance 3. Multiple Inheritance (not supported here)4. Hierarchal Inheritance 5. Hybrid Inheritance (Not supported here)

Java doesn’t supported Multiple inheritance and Hybrid InheritanceIt can be achieved by interface concept

Single inheritance: Single Inheritance as one base class and one derived class

Multilevel Inheritance: Multilevel has one pure base class and one as act as a base and also derived and another one as pure derived class

Multiple inheritance: Multiple inheritances as many base classes and one derived class(It can be achieved by Interface concept and implements keyword)

Hierarchal inheritance:Hierarchal has one base class and two or more than two derived classes

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 43: Total Java Notes

COMPLETE JAVA NOTES

(It can be achieved by Interface concept and implements keyword)

Hybrid inheritance:The combination of multiple Inheritance and multilevel InheritanceEg://Eg for single inheritanceclass Single{

int a;publicvoid Get(){

a=10;}

}class Make extends Single{

void Display(){

System.out.println("A:="+a);}

}class Single_inh{

public static void main(String arg[]){

Make s=new Make();s.Get_Data();s.Display();

}}

Eg://Eg for multiple inheritance

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 44: Total Java Notes

COMPLETE JAVA NOTES

class data1 { int d1; public void get_d1()

{ d1=67; } } interface data2 { int d2=56; void mul(); } class multiple extends data1 implements data2 {

int tot;public void mul()

{ tot=d1*d2;

} public void display()

{ System.out.println("total="+tot);

} } class multi { public static void main(String arg[]) { multiple s=new multiple(); s.get_d1(); s.mul(); s.display();}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 45: Total Java Notes

COMPLETE JAVA NOTES

}

Eg:/*Multilevel Inheritance*/class Student{

int rno;void Get1(int x){

rno=x;}void Put1(){

System.out.println("Roll_Number:="+ roll_no);}

}class Test extends Student{

int sub1,sub2;void Get2(int m1,int m2){

sub1=m1;sub2=m2;

}void Put2(){

System.out.println("Mark1:="+sub1);System.out.println("Mark2:="+sub2);

}}class Result extends Test{

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 46: Total Java Notes

COMPLETE JAVA NOTES

float total;void Disp(){

total=sub1+sub2;Put1();Put2();System.out.println("Total:="+total);

}}class Multi_level{

public static void main(String arg[]){

Result s=new Result(); //Object creations. Get1(111);s.Get2(100,100);s.Disp();

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 47: Total Java Notes

COMPLETE JAVA NOTES

Class: 7Package Creation:Packages are nothing but it is a “class – libraries”Packages are nothing but it is collection of methods and various classes.

Java Package Is 2 Types:1) Java Application Programming Interface Package (API Package)(Or) System Defined package2) User Defined Package

System Defined Packages:import java.lang.* Language Support classes automatically importedimport java.util.* date and time, Vector etcimport java.io.* Input/output Operationsimport java.applet.*Classes for creating and implementing appletsimport java.awt.* Set of classes implementing GUIimport java.net.* Classes for networking

Steps to create package:1) Create a new folder when it has same name of package name2) Here package name and folder name are same3) Include the package command, along with the package name as the first statements in the program name4) Write class declaration5) Save the file in package folder as “Name of class java”6) Set the class path = % class path% ; d:\<package name >7) Compile this file using javacSyntax for package creation:package <package name or folder name> .[<sub package name>];public class <class name >

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 48: Total Java Notes

COMPLETE JAVA NOTES

{public static String <method name>(String arg[ ])orpublic static <method name>( ){

<statements>;}

}

Eg://Eg for package creationpackage device;public class input{

public static show( ){

System.out.println(“\nInput device are:”);System.out.println(“\n\tKeyboard”);System.out.println(“\n\tMouse”);System.out.println(“\n\tScanner”);System.out.println(“\n\tLight Pen”);System.out.println(“\n\tBarcode reader”);

}}1) Save the file to your package folder input. Java2) Set the D:\karthi\device>set path = D:\jdk1.6\bin3) Compile this file using javac.

Eg://Eg for package creationpackage device public class output{

public static show( )

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 49: Total Java Notes

COMPLETE JAVA NOTES

{System.out.println(“\nOutput device are:”);System.out.println(“\n\tMonitor”);System.out.println(“\n\tPrinter”);System.out.println(“\n\tScanner”);

}}1) Save the file to your package folder output. Java2) Set the class path = % class path% ; d:\<package name >3) Compile this file using javac.

Syntax for using package classes:import <package name>.*;<access specifier > class <class name>{

<main method>(String arg[ ]){

<class name> <obj name> = new <class name>( );<obj name>. <method name>( );<statements>;

}}

Eg://To display package methodsimport device.*;public class p49{

public static void main(String arg[ ]){

input s = new input( );output d= new output( );s.show( );d.show( );

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 50: Total Java Notes

COMPLETE JAVA NOTES

}}

Exception Handling:Some abnormal conditions an error can be occur to avoid this error we can use Exception conceptThey are 5 types:

1) Try2) Catch3) Throw4) Throws 5) Finally

Here all are keywordsTWO BENEFITS:To allow you to fix the errorIt prevents the program from automatically terminatingSOME EXCEPTIONS ARE:

Exception Classes NamesMeaning

ArithmeticException Arithmetic error, such as divide by zero

IOException General problems during input and output operators

ArrayIndexOutOfBoundsException

When array index is out the given range

ArrayStoreExceptionAssignment to the array element

of an incompatible by array index

NullPointerExceptionInvalid use of null reference

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 51: Total Java Notes

COMPLETE JAVA NOTES

InterruptedIOExceptionOne thread has been interrupted

by another thread

FileNotFoundExceptionWhen a requested file is not

foundEOFException End of file reached exception

error

SQLExceptionWhen error occurs during a

database access

UnknownLostExceptionWhen the host cannot be located

NumberFormatExceptionWhen the string passes is not a

number

General syntax for try catch method:

try{

<Try block statements>;.

}catch( Exception <type1>){

<Exception handlers>;.

}catch( Exception <type2>){

<Exception handlers>;.

}finally{

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 52: Total Java Notes

COMPLETE JAVA NOTES

<Final statements>;}

Try & Catch modelWhenever there is a possibility of an exception being generated in a program. It is a better to handler it explicitlyImmediately the following try block include a catch clause that specifies the exception type that you using the catch

Syntax:try{

<Try block statements>;..

}catch( Exception <type1>){

<Exception handlers>;..

}

Multi catchMore than one catch could be single piece of code. To handle this type of situation you can specify are more than two catchesEach catching different types of Exception

Syntax:try{

<Try block statements>;

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 53: Total Java Notes

COMPLETE JAVA NOTES

.

.}catch( Exception <type1>){

<Exception handlers>;..

}catch( Exception <type2>){

<Exception handlers>;..

}

ThrowThrow is possible to throw an Exception explicitlyThey are two ways you can obtain a throwable object using a parameter into a catch clause, or creating one with the new operator

Syntax for throw:throw <throwable instance>;

Throws:Throws does not to handle exception using try-catch block. It can use the main( ) method is the program excepts the generation of arithmetic exception but does not want to handle try catch block.

Syntax:throws <Exception name>

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 54: Total Java Notes

COMPLETE JAVA NOTES

Eg://Eg for try catch methodimport java.io.*;public class p34{

public static int a,b,c;public static void main(String arg[ ]){try

{DataInputStream d= new DataInputStream(System.in);

System.out.println("Enter the a value:");a=Integer.parseInt(d.readLine());System.out.println("Enter the b value:");b=Integer.parseInt(d.readLine());c=a/b;System.out.println("Division of two number is:"+c);}catch(Exception e){System.out.println("You divided zero");}}

}

Eg://Eg for multicatch import java.io.*;class p36{

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 55: Total Java Notes

COMPLETE JAVA NOTES

public static int i,j=2,c,a[ ]=new int[5];public static void main(String arg[ ]){

try{DataInputStream d=new DataInputStream(System.in);for(i=1;i<=7;i++){

System.out.println("Enter the "+i+" values:");a[i]= Integer.parseInt(d.readLine( ));c=a[i]/j;System.out.println("Given divide value is:"+c);j=j--;

}}catch(ArithmeticException e1){

System.out.println(e1);}catch(ArrayIndexOutOfBoundsException e2){

System.out.println(e2);}

}}

Eg://Eg for throw Exceptionimport java.io.*;class p37{

public static void disp( ){

try

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 56: Total Java Notes

COMPLETE JAVA NOTES

{throw new NullPointerException("disp");}catch(NullPointerException e1){System.out.println(e1);throw( ); //Recall the methods.}

}public static void main(String arg[ ]){

try{

disp( );}catch(NullPointerException e2){

System.out.println(e2);}

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 57: Total Java Notes

COMPLETE JAVA NOTES

Class: 8Date class:It contains a collection util Framework, collection classes Syntax for Date Class Declaration:GregorianCalendar <obj name>=new GregorianCalendar ();

Method Declaration Meaning<obj name>.get(Calendar.DATE) Display Date <obj name>.get(Calendar.YEAR) Display Year <obj name>.get(Calendar.MONTH) Display Month<obj name>.get(Calendar.DAY) Display Day<obj name>.get(Calendar.HOUR) Display Hour<obj name>.get(Calendar.MINUTE) Display Minute<obj name>.get(Calendar.SECOND) Display Second<obj name>.get(Calendar.WEEK_OF_YEAR) Display week of year<obj name>.get(Calendar.WEEK_OF_MONTH)

Display week of Month

<obj name>.get(Calendar.DAY_OF_MONTH) Display day of month<obj name>.get(Calendar.DAY_OF_YEAR) Display day of year<obj name>.get(Calendar.DAY_OF_WEEK) Display day of week<obj name>.get(Calendar.AM_PM) Display AM or PM<obj name>.get(Calendar.HOUR_OF_DAY) Display Hour of day

Eg:import java.util.*;public class d1{ public static void main(String s[]) { GregorianCalendar c=new GregorianCalendar();

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 58: Total Java Notes

COMPLETE JAVA NOTES

System.out.println("YEAR: " + c.get(Calendar.YEAR)); System.out.println("MONTH: " + c.get(Calendar.MONTH)); System.out.println("WEEK_OF_YEAR: " + c.get(Calendar.WEEK_OF_YEAR)); System.out.println("WEEK_OF_MONTH: " + c.get(Calendar.WEEK_OF_MONTH)); System.out.println("DATE: " + c.get(Calendar.DATE)); System.out.println("DAY_OF_MONTH: " + c.get(Calendar.DAY_OF_MONTH)); System.out.println("DAY_OF_YEAR: " + c.get(Calendar.DAY_OF_YEAR)); System.out.println("DAY_OF_WEEK: " + c.get(Calendar.DAY_OF_WEEK)); System.out.println("AM_PM: " + c.get(Calendar.AM_PM)); System.out.println("HOUR: " + c.get(Calendar.HOUR)); System.out.println("HOUR_OF_DAY: " + c.get(Calendar.HOUR_OF_DAY)); System.out.println("MINUTE: " + c.get(Calendar.MINUTE)); System.out.println("SECOND: " + c.get(Calendar.SECOND)); }}

Vector class:Vector is a dynamic arrayThat can be holding an object as any data type and any number

Syntax for vector class declaration:Vector <obj name> = new Vector(<size>);

SYNTAX METHODS NAME MEANING<obj name>.removeElementAt (<nth>); Remove the item stored

in the nth position<obj name>.addElementAt (<item>); Add the item specified to

the list at the end<obj name>.elementAt(<nth>); Used to find out the nth

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 59: Total Java Notes

COMPLETE JAVA NOTES

Element or object<obj name>.size( ); Find out the size of

vector<obj name>.removeElement(<item> ); Remove the item stored

in nth position in the list<obj name>.removeAllElements( ); Remove all Elements in

the list<obj name>.insertElementAt(<string>,<pos>);

Insert the string as given position

<obj name>.capacity(); Find out the capacity of vector

<obj name>.add(<string>) Add item to vector

Eg://Eg for vectorimport java.util.*;class v1{ public static void main(String ss[]) {

Vector v=new Vector(3); System.out.println("Capacity Of Vector:"+v.capacity()); System.out.println("size of Vector:"+v.size()); v.addElement("Apollo"); v.addElement("Rosi"); v.addElement("supria"); System.out.println("Capacity Of Vector:"+v.capacity()); System.out.println("size of Vector:"+v.size()); v.add("Saranya"); System.out.println("fourth element:"+v.elementAt(3)); System.out.println("Capacity Of Vector:"+v.capacity());

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 60: Total Java Notes

COMPLETE JAVA NOTES

System.out.println("size of Vector:"+v.size()); v.add(new Integer(10)); v.add(new Float(10.9f)); System.out.println("Capacity Of Vector:"+v.capacity()); System.out.println("size of Vector:"+v.size()); System.out.println(v); v.removeElementAt(3); System.out.println("After Removing One Element Capacity Of Vector:"+v.capacity()); System.out.println("size of Vector:"+v.size()); System.out.println(v); Enumeration e=v.elements(); while(e.hasMoreElements()) { System.out.println(e.nextElement()); } }}ArrayList class:Eg:import java.util.*;class al{ public static void main(String args[]) { Integer i1=new Integer(10); Integer i2=new Integer(20); Integer i3=new Integer(30); Integer i4=new Integer(40); String s1=new String("Hai"); ArrayList a=new ArrayList(); a.add(i1); a.add(i2); a.add(i3);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 61: Total Java Notes

COMPLETE JAVA NOTES

a.add(i4); a.add(s1); System.out.println("Array list is:"+a); }}

LinkList class:

syntax for LinkList class:

LinkedList <obj name>=new LinkedList();

Methods:

<obj name>.add(<value>);<obj name>.addFirst(<value>);<obj name>.addList(<value>);<obj name>.remove(<value>);

Eg:import java.util.*;class ll{public static void main(String args[]){

LinkedList l=new LinkedList();l.add(i1);l.add(i2);l.add(i3);l.add(i4);l.add(s1);l.addFirst("XXXXX"); l.addLast("YYYYY");System.out.println(" "+l);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 62: Total Java Notes

COMPLETE JAVA NOTES

}}

HashSet class:Eg:import java.util.*;class hs{ public static void main(String args[]) { HashSet h=new HashSet(); h.add("E"); h.add("D"); h.add("C"); h.add("B"); h.add("A"); System.out.println(" "+h); }}

TreeSet class:Eg:import java.util.*;class ts{ public static void main(String args[]) { TreeSet t=new TreeSet();

t.add("H"); t.add("G"); t.add("F");

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 63: Total Java Notes

COMPLETE JAVA NOTES

t.add("E"); t.add("D"); t.add("C"); t.add("B"); t.add("A"); System.out.println(" "+t); System.out.println(" "); System.out.println(" "+t.headSet("D")); System.out.println(" "); System.out.println(" "+t.tailSet("D")); System.out.println(" "); System.out.println(" "+t.subSet("D","G")); }}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 64: Total Java Notes

COMPLETE JAVA NOTES

Class: 9Input and Output Stream classes and methods:Syntax for File Class declaration:File <obj name>= new File(<path with file name>)

Using Methods Meaning<file obj>.isFile() Check file or not display only true

or false<file obj>.isAbsolute() Return true if the file has an

absolute path else not absolute<file obj>.renameTo(<newfname>)

If true file name changed

<file obj>.delete() If true delete the file <file obj>.getName() Return name of the file without

path<file obj>.getPath() Returns the path given while

creating file object<file obj>.getAbsolutePath() Return absolute path<file obj>.getParent() Return full path of parent directory<file obj>.exists() Check file is present or not<file obj>.canWrite() Check writeable or not<file obj>.canRead() Check readable or not<file obj>.isDirectory() Check directory or not<file obj>.length() Display file size in byte<file obj>.isHidden() Check hidden or not<file obj>.mkdir() Create directory<file obj>.mkdirs() Create any intervening parent

directory<file obj>.createNewFile() Create files

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 65: Total Java Notes

COMPLETE JAVA NOTES

Void deleteOnExit() Delete the file<file obj>.setReadOnly() Set file as read only mode<file obj>.setLastModified(<long sec>)

Sets the time stamp of invoking object to that specified by sec

Eg:class file{

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

File ("H:\Java Notes\Java Program Class\IOStreams Notes\file.java");

getName( )getParent( )exists( )ifFile( )isAbsolute( )canReadcanWriteDelete( )IsHidden( )LastModified( )

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 66: Total Java Notes

COMPLETE JAVA NOTES

Class: 10

Introduction to Networking package:

TCP/IP:

Application(HTTP,FTP,TELNET)

Transports(TCP, UDP)

Network(IP,…)

Link(Device driver,..)

TCP:TCP (Transmission Control Protocol) is a connection based protocol that provides a reliable flow of data between two computers.

UDP:UDP is not connection – based like TCP.

Protocol:A protocol is a rule or a complete set of rules defining how computers communicate.

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 67: Total Java Notes

COMPLETE JAVA NOTES

Types of Protocols: 1.Application Protocol 2.Transport Protocol 3.Network ProtocolURL Classes:URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the internetEg:http: //www.yahoo.comhttp:Protocol Identifier.//www.yahoo.com Resource nameUsing package import java.net.*;Using Classes URL <obj name > = new URL(<Web site name>);URLConnection <obj name>= <Url obj name>.openConnection();

Using Methods Meanings<obj name>.getProtocol(); Display the protocol name<obj name>.getHost(); Display the Resource name<obj name>.getFile(); Display the File name<obj name>.getPort(); Display the Port number<obj name>.getRef(); Display the Reference nameEg://Eg for URL Class and methodsimport java.net.*;import java.io.*;class url{

public static void main(String arg[])throws Exception{URL u=new

URL("http://java.sun.com;80/d0cs/books/tutorialinto.html#DOWNLOADING");

System.out.println("Protocol is:"+u.getProtocol());System.out.println("Host is:"+u.getHost());

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 68: Total Java Notes

COMPLETE JAVA NOTES

System.out.println("File name is:"+u.getFile());System.out.println("Port is:"+u.getPort());System.out.println("Reference is:"+u.getRef());}

}URLConnection Classes:Eg://Eg for URLConnection Class and methodsimport java.net.*;import java.io.*;class urlconnection{

public static void main(String arg[])throws Exception{URL u=new URL("http://www.yahoo.com");URLConnection uc= u.openConnection();BufferedReader b=new BufferedReader(uc.getInputStream());String s;while((s=b.readLine())!=null){

System.out.println(s);}}

}

INetAddress Classes:IPADDRESS:

Ipaddress means Net Address

Syntax for find the ipaddress:

Using Classes:

InetAddress.getLocalHost();

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 69: Total Java Notes

COMPLETE JAVA NOTES

Using Methods:<obj name>.getHostName()// find computer name<obj name>.getHostAddress();//find computer ipaddress

Eg:import java.net.*;import java.io.*;class ipaddress{public static void main(String arg[])throws Exception

{InetAddress addr=InetAddress.getByName("Localhost");System.out.println("Address:"+addr);

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 70: Total Java Notes

COMPLETE JAVA NOTES

Class: 11Socket Classes:A socket is one end point of a two-way communication link between two programs running on the networkA socket is bound to port number so that the TCP Layer can identify the application that data is destined to be sentNormally a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request

Syntax for Socket Class declaration:Socket <obj name> = new Socket();

Syntax for Socket Methods declaration:<obj name>.accept(); // Accept the Socket values

ServerSocket Classes:Syntax for ServerSocket Class declaration:ServerSocket <Obj name>=new ServerSocket(<port number>);

Syntax for ServerSocket Methods declaration:<obj name>.accept(); // Accept the Socket values

Eg:Eg for Server Socket//Eg for Socketimport java.net.*;import java.io.*;class serversocket

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 71: Total Java Notes

COMPLETE JAVA NOTES

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

Socket s;ServerSocket ss=new ServerSocket(4000);System.out.println("Server is waiting");for(;;){

s=ss.accept();System.out.println("port number is:"+s);System.out.println("server is Connected");OutputStream os=s.getOutputStream();PrintStream ps=new PrintStream(os);ps.println("Message from Server BSS\n");

}}

}

Eg:Eg for Client Socket://Eg for client socketimport java.net.*;import java.io.*;class clientsocket{

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

InetAddress addr=InetAddress.getByName("localhost");Socket s=new Socket(addr,4000); System.out.println("Server found");System.out.println(s);InputStream is=s.getInputStream();DataInputStream d= new DataInputStream(is);String str=d.readLine();

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 72: Total Java Notes

COMPLETE JAVA NOTES

System.out.println(str); }}

DatagramSocket Classes:Syntax for DatagramSocket Class declaration:DatagramSocket <obj name>=new DatagramSocket(<port number>);

Syntax for DatagramSocket Methods declaration:<obj name>.receive(<obj name>);

DatagramPacket Classes:Syntax for DatagramPacket Class declaration:DatagramPacket <obj name>=new DatagramPacket(b,b.length);

Syntax for DatagramPacket Methods declaration:<obj name>.receive(<obj name>);

Eg:Eg for DatagramPacket for Server://Eg for DatagramPacket for server.import java.io.*;import java.net.*;class dps{

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

byte b[]=new byte[100];DatagramSocket ds=new DatagramSocket(4000);DatagramPacket dp=new DatagramPacket(b,b.length);System.out.println("Server is waiting");ds.receive(dp);b=dp.getData();

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 73: Total Java Notes

COMPLETE JAVA NOTES

String str=new String(b);System.out.println(str);

}}

Eg:Eg for DatagramPacket for Client://Eg for Datagrampacket for clientimport java.net.*;import java.io.*;class dpc {

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

String str="Hello form Bss";byte b[]=new byte[str.length()];b=str.getBytes();InetAddress addr=InetAddress.getByName("localhost");DatagramSocket ds=new DatagramSocket();DatagramPacket dp=new

DatagramPacket(b,b.length,addr,4000);ds.send(dp);System.out.println("SystemName:"+addr);System.out.println("Data send");

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 74: Total Java Notes

COMPLETE JAVA NOTES

Class: 12Introduction of multithreading:

Extends Thread:

Implements Thread:

Class: 13JDBC - Java Database Connectivity

Introduction of JDBC:

Java Database Connectivity (JDBC) is a programming framework for Java developers writing programs that access information stored in databases

What is ODBC?

Database that another program links to called a data source. Many data sources, including products produced by Microsoft and Oracle, already use a standard called Open Database Connectivity (ODBC)

Connection between Ms Access to java with ODBC:

Step: 1

Create the database table to MSACCESS for connecting the table

MS ACCESS:

Start run Msaccess (type) ok

Select blank access database (Select your directory) (db1) database THANKING YOU

CREATED BY A.KARTHIKEYAN

Page 75: Total Java Notes

COMPLETE JAVA NOTES

name createclose the windows

Step: 2

Start Run control panel (type)ok Administrator tools Data Source (ODBC) user DSNAdd Microsoft access driver [*.mdb] finish

Data source name karthi

Click select optionselect the database name (db1.mdb)okokok

EG:

karthi

Step: 3

Using package import java.sql.*;

Syntax for connection class declaration:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection <con name>=DriverManager.getConnection("jdbc:odbc:<ODBCname>");

Syntax for statements class declaration

Statement <statement name>=<con name>.createStatement();

ResultSet <result set name>;

Syntax for Statements Methods:

<statement name>.execute (<SQL statements>); used for create or delete

<statement name>.executeQuery (<SQL statements >); used for select

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 76: Total Java Notes

COMPLETE JAVA NOTES

<statement name>.executeUpdate(<SQL statements >); used insert or update

<statement name>.commit(); permanently store data

<statement name>.rollBack(); Undone the last data

<statement name>.close(); close statements

Syntax for ResultSet Methods:

<resultset name>.getString(<index>); display string values

<resultset name>.getInt( <index>); display integer values

<resultset name>.getFloat( <index>); display float values

<resultset name>.setString(<index>,<value>); set string values

<resultset name>.setInt(<index>,<value>); set integer values

<resultset name>.setFloat(<index>,<value>);set float values.

<resultset name>.next( ) check the next row

Step: 4

Save your java file

Step: 5

Compile the Java program.

Run the java program

See the Output

Eg:

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 77: Total Java Notes

COMPLETE JAVA NOTES

//Database between Java to msaccess by using odbc controlimport java.sql.*;class create{

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

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection

cn=DriverManager.getConnection("jdbc:odbc:karthi");System.out.println("Connection is created");Statement st=cn.createStatement();System.out.println("Statement is created");String s1="create table report(name text,designation

text,salary number)";st.execute(s1);System.out.println("Table Created ");cn.commit();

st.close();cn.close();

}}

Eg://To insert into report databaseimport java.sql.*;class insert{

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

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection cn =

DriverManager.getConnection("jdbc:odbc:karthi"); Statement st = cn.createStatement(); st.executeUpdate("insert into report

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 78: Total Java Notes

COMPLETE JAVA NOTES

values('karthi','Admin',25000)");System.out.println("1 row created");st.close();cn.close();

}}

Eg://To view all data from reportimport java.sql.*;class select{

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

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection cn =

DriverManager.getConnection("jdbc:odbc:karthi");Statement st = cn.createStatement();ResultSet rs;rs = st.executeQuery("select * from report");System.out.println("Name\tDesignation\tSalary");while(rs.next()){

System.out.print(rs.getString(1)+"\t");System.out.print(rs.getString(2)+"\t");System.out.println(rs.getInt(3)+"\t");

} System.out.println("End of record");st.close();cn.close();

}}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 79: Total Java Notes

COMPLETE JAVA NOTES

Eg://Eg for delete all values from tableimport java.sql.*;class delete{

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

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection cn =

DriverManager.getConnection("jdbc:odbc:karthi");Statement st = cn.createStatement();st.executeUpdate("delete * from report");System.out.println("All Record deleted");cn.commit();st.close();cn.close();

}}

Eg://To drop table from report data baseimport java.sql.*;class drop{

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

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection

cn=DriverManager.getConnection("jdbc:odbc:karthi");System.out.println("Connection is created");Statement st=cn.createStatement();System.out.println("Statement is created");st.execute("drop table report");cn.commit();

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 80: Total Java Notes

COMPLETE JAVA NOTES

System.out.println("Table dropped"); st.close();

cn.close();}

}

Class: 14Introduction to Applet:Applet is mainly used for create web pagesAn applet is a dynamic interactive program that can run inside a web page.Displayed by a java capable such as hot java, Netscape, Opera, Mozilla Fire fox, I.E (Internet Explorer)

Advantage of applet:

Run inside a java browserJava applet has restricted to ensure security & prevent them from being affected by the virus.

Applet package:import java. applet.*;import java.awt.*; (Abstract windowing Toolkit )import java.awt.event.*;

Life cycle of applet programming:

Init( ) start( ) stop( )

Compiler:

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 81: Total Java Notes

COMPLETE JAVA NOTES

javac <file name>.javaRun:

appletviewer <file name>. JavaApplet html tag:<applet code = <file name>.class width=<size> height =<size> </applet>

Difference between Console Application and Applet Application:

Console Application Applet ApplicationConsole based Execution Browser based ExecutionExecution begins from main function

Execution begins from init function

Using background and process such as file handling data base management system, etc

Used for designing web pages

There is no life cycle There is life cycleInit( ) start( ) stop( ) destroy( )This type of method is called on call back method

Structure of Applet program:// <Comment line><package>public class <class name> extends Applet{

<variable declaration>;public void init( ){

<initialization statements>;}

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 82: Total Java Notes

COMPLETE JAVA NOTES

public void start( ){

<starting statements>;}public void paint( ){

< statements>;}public void stop( ){

<stop statements>;}

}

Basic Applet programs://To display my nameimport java.applet.*;import java.awt.*;public class p1 extends Applet{

String s;public void init(){

s="karthikeyan";}public void paint(Graphics g){

g.drawString(s,250,100);}

}//<applet code="p1.class" width=500 height=500> </applet>

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 83: Total Java Notes

COMPLETE JAVA NOTES

Color Class:

Syntax for color class:Color <obj name> = new Color ( );OrColor <obj name> = new Color (<color name>);OrColor <obj name> = new Color (<red int >, <green int >, <blue int>);

Method for color classes:setForeground (Color <obj name>);setBackground (Color <obj name>);setColor(Color <obj name>);

Notes: Here set color is a graphics class method so we call the graphics object

Standard colors:

Color name Rgb values

Color. White 255,255,255

Color. Black 0,0,0

Color. Lightgray 192,192,192

Color. Gray 128,128,128

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 84: Total Java Notes

COMPLETE JAVA NOTES

Color. Darkgray 64,64,64

Color. Red 255,0,0

Color. Green 0,255,0

Color. Blue 0,0,255

Color. Yellow 255,255,0

Color. Cyan 0,255,255Color. Magenta 255,0,255

Color. Pink 255,175,175Color. Orange 255,200,0

Eg://Eg for Color classimport java.applet.*;import java.awt.*;public class p2 extends Applet{

public Color b=new Color(255,255,0);public Color f=new Color(0,0,255);public void init(){

setForeground(f);setBackground(b);

}public void paint(Graphics g){

g.drawString("karthikeyan",250,100);g.setColor(Color.orange);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 85: Total Java Notes

COMPLETE JAVA NOTES

g.drawString("===========",250,120);}

}//<applet code="p2.class" width=500 height=500> </applet>

Font Class:Syntax for font class:Font <obj name> = new Font (<name>, <style>, <size>);Methods for font classes:setFont <obj name>; //To apply fontHere:setFont also one of the graphics method.

Some font name:EG:Times New RomanMonotype Corsiva

Style:Font. BOLDFont. ITALICFont. PLAIN

Eg://Eg for Font classimport java.applet.*;import java.awt.*;public class p3 extends Applet{

public Color b=new Color(255,255,0);public Color f=new Color(0,0,255);public Font ff=new Font("Monotype Corsiva",Font.BOLD,26);public void init(){

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 86: Total Java Notes

COMPLETE JAVA NOTES

setForeground(f);setBackground(b);

}public void paint(Graphics g){

g.setFont(ff);g.drawString("karthikeyan",250,100);g.setColor(Color.orange);g.drawString("========",250,120);

}}//<applet code="p3.class" width=500 height=500> </applet>

Class: 15Introduction to Graphics:

Line method:To draw a straight lines

Syntax for drawline method:<graphics obj name>.drawline( <int x1>,<int y1>,<int x2>,<int y2>);

Eg://Eg for drawLine methodimport java.applet.*;import java.awt.*;public class p4 extends Applet{

public Color f= new Color(255,0,0);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 87: Total Java Notes

COMPLETE JAVA NOTES

public Color b= new Color(0,255,0);public void init(){

setForeground(f);setBackground(b);

}public void paint(Graphics g){

g.drawString("my home",750,300);g.drawString("=======",750,320);g.drawLine(300,200,800,200);int i=0;while(i<=460){

g.drawLine(300+i,200,100+i,400);i=i+40;

}g.drawLine(800,200,600,400);g.drawLine(100,400,900,400);g.drawLine(800,200,900,400);g.drawLine(110,400,110,600);g.drawLine(610,400,610,600);g.drawLine(890,400,890,600);g.drawLine(110,600,890,600);

}}//<applet code="p4.class" height=800 width=1000> </applet>

Rectangle method:Rectangle:They are 3 kinds of rectangles.

1) Plain Rectangle2) Round Rectangle

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 88: Total Java Notes

COMPLETE JAVA NOTES

3) 3-Dimensional Rectangle

Each of these Rectangles has 2 methods:Draw the Rectangle in outline colorDraw the Rectangle in Filled with color

1) Plain Rectangle:Used to draw a Normal Rectangle

Syntax for drawrect method:<grap obj name>. drawRect (<int left>, <int top>,<int width>, <int height>);

Syntax for fillrect method:<grap obj name>. fillRect (<int left>, <int top>,<int width>, <int height>);

Eg://Eg for drawRect methodimport java.applet.*;import java.awt.*;public class p5 extends Applet{

public Color f= new Color(0,0,255);public Color b= new Color(0,255,0);public void init(){

setForeground(f);setBackground(b);

}public void paint(Graphics g){

g.setColor(Color.red);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 89: Total Java Notes

COMPLETE JAVA NOTES

g.fillRect(200,200,500,400);g.setColor(Color.black);g.fillRect(220,220,460,360);g.setColor(Color.red);g.drawRect(400,600,100,100);g.fillRect(300,700,300,50);g.setColor(Color.white);g.drawString("BLACK BOARD",400,400);

}}//<applet code="p5.class" height=800 width=1000> </applet>

2) Round Rectangle:Used to draw a Round rectangle

Syntax for draw round rect method:<grap obj name>. drawRoundRect (<int left>, <int top>,<int width>, <int height>,<left bend>, <right bend>);Syntax for fill round rect method:<grap obj name>. fillRoundRect (<int left>, <int top>,<int width>, <int height>>,<left bend>, <right bend>);

Eg://Eg for drawRoundRectangle methodimport java.applet.*;import java.awt.*;public class p6 extends Applet{

public Color f= new Color(0,0,255);public Color b= new Color(0,255,0);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 90: Total Java Notes

COMPLETE JAVA NOTES

public void init(){

setForeground(f);setBackground(b);

}public void paint(Graphics g){

int j=5;g.setColor(Color.red);while(j<=300){

g.drawRoundRect(500-j,395-j,10+j+j,10+j+j,10+j+j,10+j+j);j=j+5;

}}

}//<applet code="p6.class" height=800 width=1000> </applet>

3) 3d Rectangle:Used to draw a 3DrectangleSyntax for draw 3d rectangle method:<grap obj name>. draw3DRect (<int left>, <int top>, <int width>, <int height>, <true / false>);Syntax for fill 3-drectangle method:<grap obj name>. fill3DRect (<int left>, <int top>, <int width>, <int height>, <true / false>);Eg://Eg for 3DRect methodimport java.applet.*;import java.awt.*;public class p7 extends Applet{

public Color f= new Color(0,0,255);public Color b= new Color(0,255,0);

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 91: Total Java Notes

COMPLETE JAVA NOTES

public void init(){

setForeground(f);setBackground(b);

}public void paint(Graphics g){

g.fill3DRect(100,100,400,200,true);g.draw3DRect(400,400,400,200,false);

}}//<applet code="p7.class" height=800 width=1000> </applet>

Class: 16Polygon methodOval methodArc methodImage classes

Class: 17Introduction to AWT componentsLabel ClassText Field ClassButton ClassPanel Class

Class: 18Introduction to EventsMouse Events

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 92: Total Java Notes

COMPLETE JAVA NOTES

Keyboard EventsItem Events

Class: 19Text Area ClassScrollbar ClassCheckbox ClassCheckbox Group Class

Class: 20Choice ClassList ClassFrame ClassMouse Cursor Class

Class: 21Menu bar ClassPopup Menu ClassCanvas Class

Class: 22Introduction of LayoutFlowLayout ClassGridLayout ClassBorderLayout ClassCardLayout Class

Class: 23Introduction to swingsSwings Controls or ComponentsSwings WindowsSwings Programs

Class: 24

THANKING YOUCREATED BY A.KARTHIKEYAN

Page 93: Total Java Notes

COMPLETE JAVA NOTES

Message boxTimer ClassProgressBar ClassDialog Class

Class: 25Swings Menus ClassSwings ContainerSwings Programs

THANKING YOUCREATED BY A.KARTHIKEYAN


Recommended