By Balaji.VP 9791118054 vpbala2000@gmail.com Simple Program Import 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); } } Explanation of the Program The 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 []) Explanation of the Program Public: 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. Second Program Import java.lang.*; Class hall { float len; float bre; void getdata (float a, float b) { len = a; bre = b; } } Second Program Class 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) } } JAVA Tokens Most 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. 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. Constants JAVA Constants Numeric Constants Character Constants Integer Cons Real Cons 123, 0.0085, -0.75, Char Cons String Cons ‘X’, ‘5’ “Hello” Escapes Sequences ‘\b’ --- > Back Space. ‘\f’ --- > Form Feed. ‘\n’ --- > New line. ‘\t’ --- > Horizontal Tab. Data Types Data types are two types Primitive and Non- Primitive. Primitive Non- Primitive Numeric Non-Numeric Class, Arrays, Interface. Integer, Float Char, Boolean Size Integer Type Byte Short Int Long Size 1 (Byte) 2 4 8 Floating Point: Float Double 4 8 Declaration and Giving Values Int a; Float a,b; Double s; Byte b; Char c1,c2,c3; Int a = 10; Float x = 20.36; Char c1 = ‘a’ Reading data from Keyboard Import 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; 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) { } System.out.println (“Num = “ +num); System.out.println (“Num1 = “ +num 1); } } Output: Enter a Number: 123 Enter the Next Number: 123.45 Num = 123, Num1 = 1234.45 Scope of the Variables Java 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. Symbolic Constants Symbolic 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 Arithmetic and Relational Operators 1. a – b 2. a + b 10. == is equal to 11. != is not equal to 3. a * b 4. a / b 5. a % b 6. < is less than 7. <= is less than or equal to 8. > is greater than 9. >= is greater than or equal to Logical Operators && || ! logical AND logical OR logical NOT Ex: if (age > 55 && salary < 1000) if (number <0 || number >1000) Assignment Operators a = a+1 a = a -1 a = a* (n +1) a = a / (n+1) a=a%b y = ++m s not equal to y = m++ Ex: m = 5; y = ++m y=6 but y = m++ means, y = 5 but m = 6 Conditional Operator Exp1 ? Exp2 : Exp3 Ex: a =10; b = 15; x = (a>b) ? a : b In terms of if statement if (a>b) x = a; else x = b; Bitwise Operator These 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 Special Operator There are two special operator is there, 1. instanceof 2. selection operator (.) Instanceof: person instanceof student If 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() If statement import 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} 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; } 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); } } Else If Ladder class 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) 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 ”); } } } Switch case class 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”); 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; 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”); } } catch (Exception e ) { System.out.println (“I/O Error”); } } } While Loop class while { public static void main (String args []) { StringBuffer string = new StringBuffer (); char c; System.out.println (“Enter a string”); try { while ( ( c = (char)System.in.read() ) != ‘\n’) { string.append (c); } } Catch (Exception e) { System.out.println (“Error in input”); } System.out.println (“You have entered”); System.out.println (string); } } Output: Enter a string I am a good boy You have entered I am a good boy Do-while class do { public static void main (String args []) { int row, column, y; System.out.println (“Multiplication Table \n”); row = 1; do { column = 1; do { y = row * column; System.out.println (“ “ +y); column = column + 1; } while (column <=3) { System.out.println (“\n”); row = row + 1; } } while (row <=3) } } Output: 1 2 2 4 3 6 3 6 9 class for { public static void main (String args []) { long p; int n; double q; System.out.println (“ 2 to power –n n n’); p = 1; 2 to power 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); } } Output: 2 to power –n 1 o.5 0.25 0.00195313 n 0 1 3 9 2to power n 1 2 4 512 Class, Objects and Methods Java 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. Define Class class 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. Adding Methods Type 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. Example class rectangle { int length, width; void getdata (int x, int y) { length = x; width = y; } int rectArea () { int area = length * width; return (area); } Creating Objects Objects 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 (); or rectangle rect = new rectangle (); Accessing Class Members Objectname.varibale name; Objectname.methodname (parameter – list) Ex: rect.length = 15; rect.width = 10; Calling Methods: rect. getdata (10,15); 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(); Constructor Constructor 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. Ex rectangle (int x, int y) { length = x; width = y; } Method Overloading In 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. Example class room { float length; float breath; room (float x, float y) { length = x; breath = y; } room (float x) { length = breath = x; } int area () { return (length * breath); } Static Members Lt 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. 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. Restrictions The 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. Inheritance The 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) Define Sub-Class class subclass name extends super class { variables declaration ; methods declaration ; } Example class Room { int length; int breadth; Room ( int x, int y) { length = x; breadth = y; } int area () { return (length * breadth) } } class BedRoom extends Room { int height; BedRoom (int x, int y, int z) { super (x,y); height = z; } int volume () { return (length * breadth * height) } } 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); } } Subclass Constructor Subclass 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. 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. Example class super { int x; super (int x) { this.x = x; } Void display () { System.out.println (“Super X” +x); } } class sub extends super { int y; sub (int x, int y) { super (x); this.y = y; } void display () { System.out.println (“Super x =“ +x); System.out.println (“Sub y = ” +y); } } class override { public static void main (String args[]) { sub s1 = new sub (100, 200(; s1.dispaly (); } } Final Class A class that can not be sub classed is called a final class. This is achieved in Java using the keyword final. ex: final class Aclass Finalizer 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. 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. Abstract Methods and Class We 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: abstract class shape { variables ; abstract void draw () { } } 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. 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. Interface Java 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. 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; } 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(); } Extending Interface Interface 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. Ex interface (name2) extends (name 1) { Body of name2; } interface ItemConstants { int code = 1001; String name = “Fan”; } Interface Item extends ItemConstants { void display (); } Implementing Interface interface area { final static float pi = 3.14F; float compute (float x, float y) } Class rectangle implements area { public float compute (float x, float y) { return (x * y); } } class circle implements area { public float compute (float x, float y) { return (pi * x * x); } } 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)); System.out.println (“Area of the Circle =“ +area.compute (10,0)); } } Exceptions Handling An 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” 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). Common Java Exceptions ArithmeticException 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. FileNotFoundException Caused by an attempt to access a nonexistent file. IOException Caused 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. Syntax try { Statement that causes an exception ( Exception object creator) } catch { Statement that handles the exception (Exception handler) } Program class error { public static void main (String args []) { int a [] = {5,10}; int b = 5; try { int x = a[2] / b – a[1]; } catch (ArithmeticException e) { System.out.println (“Division by zero”) ; } catch (ArrayIndexOutofBoundException e) { System.out.println (“Array index error”); } catch { System.out.println (“Wrong data type”); } int y = a[1] / a[0]; System.out.println (“Y = “ +y); } } Using finally statement Java 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. Multithreaded Programming Multithreading 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. Creating Threads Threads 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. 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. Declaring the Class class Mythread extends Thread { } Implementing the run () method: Public void run() { } Starting New Thread MyThread 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. Blocking a Thread A 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. Life Cycle of a Thread During 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. Newborn State Schedule 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. Running State Running 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. 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. Dead State Every 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. Program class 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”); } } 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 () { } System.out.println (Exit from B”); } } class C extends Thread { public void run () { for (int k =1; k<=5; k++) { System.out.println (\t From Thread C: k=“ +k); if (k ==1) { try { sleep (1000); } Catch (Exception e) { } } System.out.println (“Exit from C”); } } class ThreadMethods { public static void main (String args []) { A threadA = new A; 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”); } Thread Exceptions catch (ThreadDeath e) { // Killed thread } catch (InterruptedException e) { // Can not handle it in the current state } catch (IllegalArgumentException e) { // Illegal method argument } catch (Exception e) { // Any other } Implementing the ‘RUNNABLE” Interface class x implements Runnable { public void main () { for (int i = 1; i <=10; i++ { System.out.println ( \t ThreadX:” +i) } } } System.out.println (End of ThreadX”); } } class RunnableTest { public static void main (String args []) { X runnable = new X(); Thread threadX = new Thread 9runnable); threadX.start(); System.out.println (End of Main Thread”); } }