By Balaji.VP 9791118054 [email protected] Simple Program Import java.lang.math; Class squareroot...

115
By Balaji.VP 9791118054 [email protected]

Transcript of By Balaji.VP 9791118054 [email protected] Simple Program Import java.lang.math; Class squareroot...

Page 1: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

By Balaji.VP

[email protected]

Page 2: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Simple ProgramImport java.lang.math; Class squareroot { public static void main (String args[]) { double x = 5; double y; y = Math.sqrt (x); System.out.println (“The Value of Y =“ +y); } }

Page 3: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Explanation of the ProgramThe first lie is “class squareroot”It is Object –Oriented Construct. Nothing but

everything must be placed inside the class.The word class is a keyword. It is used for

create a new class.Here “squareroot” is identifier. Next is braces ( This is similar to C++)The third line is public static void main

(String args [])

Page 4: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Explanation of the ProgramPublic:

The keyword public is an access specifiers that declares the main method as unprotected and therefore making it accessible to all other classes.

Static:Which declares this method as one that

belongs to the entire class and not a part of the class any objects of the class.

The main must always declare as static since the interpreter uses this method before any objects are created.

Void:The type modifier void states that the main

method does not return any value.

Page 5: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Second Program

Import java.lang.*;Class hall{ float len; float bre; void getdata (float a, float b) { len = a; bre = b; }}

Page 6: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Second ProgramClass area{ public static void main (string args []) { float area; hall hall1 = new hall (); hall1.getdata (5,10); area = hall1.len * hall1.bre; System.out.println (“Area =“ + area) }}

Page 7: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

JAVA TokensMost statements contain expressions, which

describe the actions carried out the data. Smallest individual units in a program are known as Tokens.

Reserved Keywords. (60 Keywords, false, null, true, package etc.,)

Identifiers (alphabets, digits and underscore and dollar sign characters.)

Literals. (Integer, Floating Point. Character, String, Boolean)

Operators.Separators.

Page 8: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

JAVA Tokens (Separators)Parentheses () Method definition and invocation,

defining precedence in expressions.Braces {} Define a block of code for classes,

methods and local scopes.Brackets [] Declare array types and for

dereferencing array values.Semicolon ; Separate the statements.Comma , Consecutive identifiers in a variable

declaration and chain statements (For loop and int a,b)

Period . Separate package names from the sub-packages and class, separate a variable or method from a reference variable.

Page 9: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

ConstantsJAVA Constants

Numeric Constants Character Constants

Integer Cons Real Cons Char Cons String Cons

123, 0.0085, -0.75,‘X’, ‘5’“Hello”

Page 10: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Escapes Sequences ‘\b’ --- > Back Space.‘\f’ --- > Form Feed.‘\n’ --- > New line.‘\t’ --- > Horizontal Tab.

Page 11: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Data TypesData types are two types Primitive and Non-

Primitive.Primitive Non- PrimitiveNumeric Non-Numeric Class, Arrays,

Interface.Integer, Float Char, Boolean

Page 12: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

SizeInteger Type SizeByte 1 (Byte)Short 2Int 4Long 8

Floating Point:Float 4Double 8

Page 13: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Declaration and Giving ValuesInt a;Float a,b;Double s;Byte b;Char c1,c2,c3;Int a = 10;Float x = 20.36;Char c1 = ‘a’

Page 14: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Reading data from KeyboardImport java.lang.*;Import java.io.DataInputStream;Class read{ public static void main (String args []) { DataInputStream in = new DataInputStream

(System. in) int num = 0; float num1 = 0.0f;

Page 15: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Try

{

System.out.println (“Enter a number :”);

num = Integer.parseInt (in.readLine () );

System.out.println (“Enter a Next Number:”);

num1 = Float.valueOf(in.readLine() ).floatValue ();

}

Catch (Exception e)

{

}

Page 16: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (“Num = “ +num); System.out.println (“Num1 = “ +num 1); }}Output:Enter a Number:123Enter the Next Number:123.45Num = 123, Num1 = 1234.45

Page 17: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Scope of the VariablesJava variables are classified in three types,

1. Instance Variables.2. Class Variables.3. Local Variables.

The instance and class variable are declared inside a class. Instance variable are created when the objects are instantiated and therefore they are associated with the objects. They take different value for each object.

Variables declared and used inside the methods are called local variables.

Page 18: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Symbolic ConstantsSymbolic names take the same form as variable

names. But they are written in CAPITALS to visually distinguish them from normal variable names.

After declaration of symbolic constants, they should not be assigned any other value within the program by using an assignment statement.

Like final int PEOPLE = 100; we can not change the value.

This is not done in C and C++ where it is defined using the #define statement. They can NOT be declared inside a method. They should be used only as class data members in the beginning of the class.

Page 19: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Arithmetic and Relational Operators1. a – b 10. == is equal to2. a + b 11. != is not equal

to3. a * b4. a / b5. a % b6. < is less than7. <= is less than or equal to8. > is greater than9. >= is greater than or equal to

Page 20: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Logical Operators&& logical AND|| logical OR! logical NOTEx: if (age > 55 && salary < 1000)

if (number <0 || number >1000)

Page 21: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Assignment Operatorsa = a+1a = a -1a = a* (n +1)a = a / (n+1)a = a % b y = ++m s not equal to y = m++Ex:m = 5; but y = m++ means, y = 5 but m = 6 y = ++my = 6

Page 22: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Conditional OperatorExp1 ? Exp2 : Exp3Ex: a =10; b = 15; x = (a>b) ? a : bIn terms of if statementif (a>b) x = a;elsex = b;

Page 23: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Bitwise OperatorThese operators are used for testing the bits,

or shifting them to right to left.It is may not ne applies to float and double.& bitwise AND! Bitwise OR^ Bitwise exclusive OR~ One’s Complement<< shift left>> shift right

Page 24: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Special OperatorThere are two special operator is there,1. instanceof 2. selection operator (.)Instanceof: person instanceof studentIf it is true the object person belongs to the class

student; otherwise it is false.Dot Operator:Person1.age // Reference to the variable age.Person 1.salary () // Reference to the method

salary()

Page 25: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

If statementimport java.lang.*;class if{ public static void main (String args[]) { int I, count, count1, count2; float [] weight = { 45.10, 55.23, 47.25, 51.23,

54.23} float [] height = { 176.23, 174.56, 168.23,

170.89, 168. 52}

Page 26: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

count = 0;count 1 = 0;count2 = 0;For (i =0; i <=4; i++) { if (weight[i] < 50.0 && height [i] > 170.0) { count1 = count1 + 1; }

Page 27: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

count = count + 1; //Total Persons } count2 = count – count1; System.out.println (“Number of persons

with..”); System.out.println (“Weight <50 and height >

170 =“ +count1); System.out.println (“Others =“ +count2); }}

Page 28: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Else If Ladderclass ladder{ public static void main (String args[]) { int rollNumber [] = {111, 222, 333, 444}; int marks [] = {81, 75, 43, 58} for (int i =0; i <rollNumber. length; i++) { if (marks [i] >79)

Page 29: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (rollNumber [i] + “Honors”);

else if (marks [i] > 59)

System.out.println (rollNumber [i] + “I Division”);

else if (marks [i] > 49

System.out.println (rollNumber [i] + “II Division”);

else

System.out.println (rollNumber [i] + “Fail ”);

}

}

}

Page 30: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Switch caseclass guide { public static void main (String args []) { char ch; System.out.println (“Select your Choice”); System.out.println (“ M Madras”); System.out.println (“ B Bombay”); System.out.println (“ C Calcutta”);

Page 31: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (“ Please select any one”);try { switch (ch = (char)System.in.read() ) { case ‘M’: case ‘m’: System.out.println (“ Madras Booklet 5”); break;

Page 32: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

case ‘b’:case ‘B’: System.out.println (“ Bombay Booklet7”); break;case ‘C’case ‘c’ System.out.println (“ Calcutta Booklet 10”); break;default: System.out.println (“ Invalid Choice”);

Page 33: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

} }catch (Exception e ) { System.out.println (“I/O Error”); }}}

Page 34: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

While Loopclass while{ public static void main (String args []) { StringBuffer string = new StringBuffer (); char c; System.out.println (“Enter a string”); try {

Page 35: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

while ( ( c = (char)System.in.read() ) != ‘\n’) { string.append (c); }}Catch (Exception e) { System.out.println (“Error in input”); }

Page 36: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (“You have entered”); System.out.println (string); }}

Output:Enter a stringI am a good boyYou have enteredI am a good boy

Page 37: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Do-whileclass do { public static void main (String args []) { int row, column, y; System.out.println (“Multiplication Table \

n”); row = 1; do { column = 1;

Page 38: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

do { y = row * column; System.out.println (“ “ +y); column = column + 1; } while (column <=3) { System.out.println (“\n”); row = row + 1;}

Page 39: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

} while (row <=3) }}

Output:1 2 32 4 63 6 9

Page 40: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

class for { public static void main (String args []) { long p; int n; double q; System.out.println (“ 2 to power –n n 2

to power n’); p = 1;

Page 41: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

for (n =0; n<10; ++n) { if (n == 0) p = 1; else p = p * 2; q = 1.0/ (double) p; System.out.println (“ “ + q + “ “ +n “ “ +p); }}}

Page 42: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Output:2 to power –n n 2to power n

1 0 1o.5 1 20.25 3 40.00195313 9 512

Page 43: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Class, Objects and MethodsJava Program must be encapsulated in a class

that defines the state and behavior of the basic program components knows as “Objects”

In JAVA Program the data items are called fields and the functions are called methods.

“ class is a user defined data type with a template that serves to define its properties. Once the class type has been defined, we can create “variables” of that type using declarations that are similar to the basic type declarations.

Page 44: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Define Classclass classname [extends supercalssname]

{ [ variable declarations]

[ method declarations]}

Adding Variables: Data is encapsulated in a class by placing

data field inside the body of the class definition. These variables are called ‘instance variable’. They are created whenever an object of the class is instantiated.

Page 45: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Adding MethodsType method name ( parameter – list) { method- body; }Basic idea of method declaration:

The name of the method. The type of the value the method return.

A list of parameters.The body of the method.

Page 46: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Exampleclass rectangle { int length, width; void getdata (int x, int y) {

length = x;width = y;

}

Page 47: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

int rectArea () {

int area = length * width;return (area);

}

Page 48: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Creating ObjectsObjects in Java are created using the new

operator. The new operator created an object of the specified class and returns a reference to that object.

Ex:rectangle rect;rect = new rectangle ();

orrectangle rect = new rectangle ();

Page 49: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Accessing Class MembersObjectname.varibale name;Objectname.methodname (parameter – list)

Ex:rect.length = 15;rect.width = 10;

Calling Methods:rect. getdata (10,15);

Page 50: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

The first one is, to access the instance variable using the dot operator and compute the area.

int area = rect.length * rect.width;The second one is, to call the method area

declared inside the class, That is

int area = rect1.area();

Page 51: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

ConstructorConstructor have the same name as the class

name itself. They do not specify a return type, not even void. This is because they return the instance of the class itself.

Exrectangle (int x, int y){

length = x;width = y;

}

Page 52: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Method OverloadingIn Java, it is possible to create methods that

have the same name, but different parameter lists and different definitions. This is called method overloading. It is used when objects are required to perform similar task but using different input parameters.

Page 53: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Exampleclass room{

float length;float breath;

room (float x, float y) {

length = x;breath = y;

}

Page 54: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

room (float x) {

length = breath = x; }int area () {

return (length * breath); }

Page 55: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Static MembersLt us assume that we want to define a member that

is common to all the objects and accessed without using a particular object. That is, the member belongs to the class as a whole rather than the object created from the class, Such members can be defined as follows:

static int count;static int max (int x, int y);

The members that are declared static as shown above are called static members. The static variables and static methods are often refer to class variable, methods.

Page 56: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

The static variables, static methods can be called without using the objects. They are also available for use by other classes.

Java class libraries contain a large number of class methods. For example, the Math class of Java library defines many static methods to perform math operations that can be using in any program.

float x = Math.sqrt (25.0);The method sqrt is a class method (or static

method) defined by Math class.

Page 57: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

RestrictionsThe static methods are called using class

names. In fat, no objects have been created for use. They can only call other static methods.They can only access static data.They can not refer to this or super in any way.

Page 58: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

InheritanceThe mechanism of deriving a new class from an

old one is called inheritance. The old class is known as the base class and super class or parent class and the new one is called the subclass or derived class or child class.

1.Single inheritance (Only one Super class)2. Multiple inheritance ( Several super

class) here knows as interface.3. Hierarchical inheritance (One super

class, many subclass)4. Multilevel inheritance (derived from a

derived class)

Page 59: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Define Sub-Classclass subclass name extends super class

{variables declaration ;methods declaration ;

}

Page 60: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Exampleclass Room{

int length;int breadth;Room ( int x, int y){

length = x;breadth = y;

}

Page 61: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

int area () {

return (length * breadth) }}class BedRoom extends Room{

int height;BedRoom (int x, int y, int z){

Page 62: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

super (x,y);height = z;

}int volume () {

return (length * breadth * height) }}

Page 63: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

class Test

{ public static void main (String args [])

{ BedRoom room = new BedRoom (14,12,10);

int area1 = room1.area ();

int volume1 = room1.volume ();

System.out.println (“Area1=“ +area1);

System.out.println (“Volume1=“+volume1);

}

}

Page 64: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Subclass ConstructorSubclass constructor is used to construct the

instance variable of both the subclass and the super class.

The subclass constructor used the keyword super to invoke the constructor method of the super class. Super may only be used within a subclass constructor

method.The call to super class constructor must appear as the

first statement within the subclass constructor.The parameters in the super call must match the

order and type of the instance variable declared in the super class.

Page 65: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Overriding Methods.There may be occasions when we want an object

to respond to the same method but different behavior when that method is called. That means, we should override the method defined in the super class.

This is possible by defining a method in the subclass that has the same name. same argument, and same return type as a method in the super class.

Then. When that method is called, the method defined in the subclass is invoked and executed instead of the one in the super class. This is known as overriding.

Page 66: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Exampleclass super{ int x; super (int x)

{this.x = x;

}Void display ()

{

Page 67: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (“Super X” +x); }}class sub extends super{

int y;sub (int x, int y){

super (x);

Page 68: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

this.y = y;}void display () { System.out.println (“Super x =“ +x);

System.out.println (“Sub y = ” +y); }}class override

Page 69: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

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

sub s1 = new sub (100, 200(;s1.dispaly ();

}}

Page 70: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Final ClassA class that can not be sub classed is called a

final class. This is achieved in Java using the keyword final.ex:

final class AclassFinalizer Methods:

we have seen that a constructor method is used to initialize an object when it is declared. This process is known as initialization. Similarly, Java supports a concept called finalization.

Page 71: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Java run time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold the other non-objects resources such as file descriptors or windows systems fonts.

The garbage collector can not free these resources. In order to free these we must use the Finalizer method. This is similar to destructor in C++.

The finalizer method is simply finalize() and can be added to any class. Java calls that method whenever it is about to reclaim the space for that object.

Page 72: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Abstract Methods and ClassWe have seen that by making a method final

we ensure that the method is not redefined in a subclass. That is, the method can never be sub classed. Java allows us to do something that is exactly opposite to this.

That is, we can indicate that a method must always be redefined in a subclass, thus making overriding compulsory. This is done using the modifier keyword abstract in the method definition.

Ex:

Page 73: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

abstract class shape{

variables ; abstract void draw ()

{}

}

Page 74: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Access Modifiers (Visibility Modifiers)Public:

Use public if the field is to be visible everywhere.

Protected:use protected if the field is to visible

everywhere in the current package and also subclass in other package.

Default:Use default if the field is to be visible everywhere in the current package only.

Page 75: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

private protected:Use private protected if the field is to visible only in subclass, regardless of packages.

private:Use private if the field is not to be visible anywhere except in its own class.

Page 76: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

InterfaceJava provides an alternate approach known

as interfaces to support the concept of multiple inheritance. Java class can not be a sub class of more than one super class, it can implement more than one interface, there by enabling us to create classes that build upon other classes without the problems created by multiple inheritance.

An interface is basically a kind of class. Like classes, interface contain methods and variables but with a major difference.

Page 77: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

The difference is that interface define only abstract methods and final fields. This means that interface do not specify any code to implement these methods and data fields contain only constants.

interface interface name{

variables declaration;methods declaration;

}

Page 78: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Variables and Method declaration static final type variable name = value;Method:return – type method name (parameter - list)

Interface item{

static final int code = 1001;static final String name = “Fan”void display(); }

Page 79: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Extending InterfaceInterface can also be extended, that is an

interface can be sub interfaced from other interface. The new sub interface will inherit all the members of the super interface in the manner similar to sub classes.

This is achieved using the keyword extends.Exinterface (name2) extends (name 1)

{Body of name2;

}

Page 80: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

interface ItemConstants{

int code = 1001;String name = “Fan”;

}Interface Item extends ItemConstants{ void display ();}

Page 81: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Implementing Interfaceinterface area{

final static float pi = 3.14F;float compute (float x, float y)

}Class rectangle implements area{

public float compute (float x, float y){

Page 82: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

return (x * y);}

}class circle implements area{ public float compute (float x, float y)

{ return (pi * x * x);} }

Page 83: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

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

{rectangle rect = new rectangle ();circle cir = new circle ();area area;System.out.println (“Area of Rectangle

=“ +area.compute (10,20));

Page 84: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (“Area of the Circle =“ +area.compute (10,0));

}}

Page 85: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Exceptions HandlingAn exceptions is a condition that is caused by a

run-time error in the program. If we want a program to continue with the

execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as Exception handling.

The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstance”

Page 86: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Find the problem (Hit the exception).Inform that an error has occurred (Throw

the exception).Receive the error information (Catch the

exception).Take corrective actions (Handle the

exception).

Page 87: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Common Java ExceptionsArithmeticException

Caused by math errors such as division by zero.ArrayIndexOutOfBoundException

Caused by bad array indexes.ArrayStoreException

Caused when a program tries to store the wrong type of data in an array.

FileNotFoundExceptionCaused by an attempt to access a nonexistent file.

Page 88: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

IOExceptionCaused by general I/O failures, such as inability to read from

the file.NullPointerException

Caused by referencing a null object.NumberFormatException

Caused when a conversion between strings and number fails.OutOfMemoryException

Caused when there’s not enough memory to allocate a new object.

Page 89: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Syntaxtry { Statement that causes an exception

( Exception object creator)}catch{ Statement that handles the exception

(Exception handler)}

Page 90: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Programclass error{ public static void main (String args []) { int a [] = {5,10}; int b = 5; try { int x = a[2] / b – a[1]; }

Page 91: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

catch (ArithmeticException e){ System.out.println (“Division by zero”) ;}catch (ArrayIndexOutofBoundException e){ System.out.println (“Array index error”);}

Page 92: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

catch{ System.out.println (“Wrong data type”);}int y = a[1] / a[0];System.out.println (“Y = “ +y);}}

Page 93: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Using finally statementJava supports another statement known as

finally statement that can be used to handle an exception that is not caught by any of the pervious catch statements. finally block can be used to handle any exception generated within a try block.

Page 94: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Multithreaded ProgrammingMultithreading is a conceptual programming

paradigm where a program is divided into two or more subprograms, which can be implemented at the same time in parallel.

The thread is similar to a program that has a single flow of control.

Page 95: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Creating ThreadsThreads are implemented in the form of objects

that contain a method called run().The run() method should be invoked by an object

of the concerned thread.This can be achieved by creating the thread and

initiating it with the help of another thread method called start().

By creating a thread class:

Define a class that extends Thread class and override its run() method with the code required by the thread.

Page 96: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

By Converting a class to a thread:Define a class that implements

Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.

Page 97: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Declaring the Classclass Mythread extends Thread{

}Implementing the run () method:Public void run(){

}

Page 98: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Starting New ThreadMyThread aThread = new MyThread ();aThread.start();

Stopping a Thread:aThread.stop ();This statement causes the thread to move to

the dead state. A thread will also move to the dead state automatically when it reaches the end of its method.

Page 99: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Blocking a ThreadA thread can also be temporarily suspended

or blocked from entering into the runnable and subsequently running state by using either of the following thread methods

sleep () // Blocked for a specified time.

suspend () // Blocked until further orders.

wait () // Blocked until certain condition occurs.

Page 100: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Life Cycle of a ThreadDuring the life time of a thread, there are

many stated it can enter,1. Newborn state.2. Runnable state.3. Running state.4. Blocked state.5. Dead state.

Page 101: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Newborn StateSchedule it for running using start () method.Kill it using stop () method.Runnable State:

The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution.If we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using yield () method.

Page 102: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Running StateRunning means that the processor had give its

time to the thread for its execution.It had been suspended using suspend () method.

A suspended thread can be revived by using the resume () method.

It has been made to sleep, We can put a thread to sleep for a specified time period using the method sleep(time)where time is milliseconds. This means that the thread is out of the queue during this time period. The thread re-enters the runnable state as soon as this time period is elapsed.

Page 103: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

It has been told to wait until some event occurs. This is done using the wait () method. The thread can be scheduled to run again using the notify () method.

Blocked State:A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

Page 104: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Dead StateEvery thread has a life cycle. A running

thread ends its life when it has completed executing its run () method. A thread can be killed as soon as it is born, or while it is running or even when it is in “not runnable” (blocked) condition.

Page 105: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Programclass A extends Thread

{

public void main ()

{

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

{

if (i == 1) yield ();

System.out.println (“\t From Thread A: I =“ +i);

}

System.out.println “Exit from A”); } }

Page 106: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

class B extends Thread{ public void run () { for (int j =1; j<=5;j++) { System.out.println (\t From Thread N: j” +j); if (j ==3) stop () { }

Page 107: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (Exit from B”); }}class C extends Thread{ public void run () { for (int k =1; k<=5; k++) {

Page 108: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (\t From Thread C: k=“ +k);if (k ==1){ try { sleep (1000); }Catch (Exception e){ } }

Page 109: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

}System.out.println (“Exit from C”); }}class ThreadMethods{ public static void main (String args []) { A threadA = new A;

Page 110: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

B threadB = new B(); C threadC = new C(); System.out.println (“Start thread A”); threadA.start (); System.out.println (“Start thread B”); threadB.start (); System.out.println (“Start thread C”);threadC.start (); System.out.println (“End of Main Thread”); }}

Page 111: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Thread Exceptionscatch (ThreadDeath e){ // Killed thread}

catch (InterruptedException e){ // Can not handle it in the current state}

Page 112: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

catch (IllegalArgumentException e){

// Illegal method argument}catch (Exception e){ // Any other}

Page 113: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

Implementing the ‘RUNNABLE” Interfaceclass x implements Runnable{ public void main () { for (int i = 1; i <=10; i++ { System.out.println ( \t ThreadX:” +i) } }}

Page 114: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

System.out.println (End of ThreadX”); }}class RunnableTest{ public static void main (String args []) { X runnable = new X(); Thread threadX = new Thread 9runnable);

Page 115: By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import java.lang.math; Class squareroot { public static void main (String args[]) { double.

threadX.start(); System.out.println (End of Main Thread”); }}