Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified...

49
ava Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java, S P University.

Transcript of Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified...

Page 1: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Java Programming 3Dr. Priti Srinivas Sajja

Introductory concepts of java

programming as specified in MCA

302:Object Oriented Programming

Using Java, S P University.

Page 2: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• An exception is an abnormal condition that arise in a code

sequence at run time. An exception therefore, is a run time error.

• If the facility of exception handling is not supported by a programming environment, through error code one can handle error, which is a cumbersome task.

• Java solves this problem by offering run time management of errors.

• A java exception is an object that describes an exceptional condition that has occurred in a piece of a code.

Exception Handling

Page 3: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• When an exception condition arise, an object representing that exception is created and thrown in the method that cause the error.

• This method may choose to handle that exception or pass it to other method.

• Not only by a run time system of Java, bur manually also an exception is created and thrown.

Page 4: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• Java exception handling is managed through five key words:

– try, catch, throw, throws and finally.• Program statement which you’d like to monitor are enclosed in try (and

catch) block.

• If any exception occurs, within that try block, it is thrown.

• Your code can catch the exception thrown and takes necessary action.• System generated exception are thrown automatically by the java run time

system. • To manually throw the exception, use the keyword throw. • Any exception which must be thrown out of the method, must be

specified with the throws clause. • Any code that absolutely must be executed before a method returns, is

put in finally block.

Page 5: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• Here is the general form:• try{• // block of code to monitor }• catch( Exceptiontype1 ob1)• {//exception handling code…1}• catch( Exceptiontype1 ob2)• {//exception handling code…2}• //…• Finally {//… must be executed before return}• Here exception type is the type of exception that has occurred.

Page 6: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• All exception types are subclasses of the built in class Throwable. Thus Throwable is at the top of the exception class hierarchy.

• Immediately below this Throwable into two branches.

• One branch is headed by Exception. And there is an important subclass of Exception that is called RuntimeException.

• The another branch is Error, which defines exceptions that are not expected to be caught under normal conditions.

• Error is used by the Java run time system to indicates errors. Eg. Stack overflowrun time error given by the Java.

Throwable

Exception

RuntimeException

Error

Page 7: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Excepti on Handling

class ex1{ public static void main(String args[]){ int d=0; int a=42/0;}}• Results in javac ex1.javaex1.java:4: Arithmetic exception. int a=42/0; ^

When java run time system detects the

attempt to divide by zero, it constructs a

new exception and then throws the

exception (outside the method).

This cause the execution of the program

stopped.

That is such exception must be caught

within the program and dealt with

immediately.

Page 8: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• Here we have not specified any such exception handling code, so the exception is caught by a default handler of the Java.

• Any exception that that is not caught by your program will ultimately processed by the default handler.

• The default handler displays a string describing the exception and terminates the program.

Page 9: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Exception Handling (see ex2.java)

class ex2{ public static void main(String args[]){ int d, a try { d=0;

a=42/d; System.out.println(“message…”);

} catch (ArithmeticException e) { System.out.println(“Division by 0”);}

}}

Page 10: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Continuing after Exception Handling (see ex3.java)class ex3{ public static void main(String args[]){ int d, a; try { d=0; a=42/d; System.out.println("No..."); } catch (ArithmeticException e) { System.out.println("Division by 0"); System.out.println("System will say :" +e); a=0;//setting a==0 and continue.... }System.out.println("a:= " + a );

}}

Page 11: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Multiple Catches: (see ex4.java)• class ex4{• public static void main(String args[]){• int a[] ={5,10};• int b=5;• try { int x=a[1]/(b-a[0]);} // change it to int x=a[2]/b-a[1]• catch(ArithmeticException e) • {System.out.println("Division by zero...");}• catch(ArrayIndexOutOfBoundsException e)• { System.out.println("Array index error...");}• catch(ArrayStoreException e)• {System.out.println(“Wrong data type...");}

• int y=a[1]/a[0];• System.out.println("Y is = "+y);• } }

Page 12: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• So far, you have only been catching exceptions that are thrown by java run time system.

• The general form of throw is – Throw ThrowableInstance

• Here the ThrowableInstance must be an object of type throwable or a subclass of throwable.

• Simple types such as integer, char and String are non-throwable.

• There are two way you can obtain a throwable object– Using a parameter into a catch statement– Creating one with new operator.

Throw:

Page 13: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• class ThrowDemo{

• static void demoproc(){

• try{ throw new NullPointerException("Demo");

• } catch (NullPointerException e){

• System.out.println("Caught inside demo"); throw e;}

• }

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

• try{ demoproc();

• } catch (NullPointerException e){

• System.out.println("Recaught: "+e); }

• }}

Throw:

Caught inside demo

Recaught:

java.lang.NullPointerException:

Demo

Page 14: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• If a method is capable of causing an exception that it does not handle, it must specify them with the throws statement.

• A throws clause lists the types of exceptions that a method might throw.

• This is necessary for all exceptions except Error type or RuntimeException, or any of their subclasses.

Throws:

Page 15: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• When exceptions are thrown, execution may take non-linear path(disturbed).

• The finally block will execute weather or not an exception is thrown.

• This can be useful in operation like closing the files and releasing the resources before returning.

• The finally clause is optional, however one try statement requires at least one catch or one finally clauses.

• If a finally block is attached with a try, it will be executed upon conclusion of try.

Finally:

Page 16: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• class FinallyDemo{• static void procA(){• try{ System.out.println("Inside A");• throw new RuntimeException("Demo");• }finally {System.out.println("Procedure A Finally

completed");}• }• static void procB(){• try{ System.out.println("Inside B");• return;• } finally {System.out.println("Procedure B Finally

completed");}• }

Finally:

Page 17: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• static void procC(){• try{ System.out.println("Inside C");• } finally{System.out.println("Procedure C Finally

completed");}• }• public static void main(String args[]){• try{ procA();• }catch (Exception e){• System.out.println("Exception is caught");}• procB();• procC();• } }

Finally:

Page 18: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Inside AProcedure A Finally completedException is caughtInside BProcedure B Finally completedInside CProcedure C Finally completed

Output:

Page 19: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Java’s Built-in Exception:

• ArithmeticException: Arithmetic error, such as divide by zero.

• ArrayIndexOutOf BoundsException: Using array subscript out of bound

• ArrayStoreException: Assignment to an array element of an incompatible type

• ClassCastException: Invalid Cast.

• IllegalArgumentException: Illegal argument used to invoke a method.

Page 20: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Java’s Built-in Exception:

• NegativeArraySizeException : Array created with a negative size.

• NumberFormatException : Invalid conversion of string to a number format.

• StringIndexOutOfBounds : Attempt to index outside the bounds of a string.

Page 21: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Java’s java.lang Exception:

• ClassNotFoundException : Class not found.• ClassNotSupportedException: Attempt to

clone an object that doesnot implement the cloneable interface.

• InstantiationException : Attempt to create an object of an abstract class.

• IllegalAccessException : Access to a class is denied.

Page 22: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Java’s java.lang Exception:

• InterruptedException : One thread has been interrupted by another thread.

• NoSuchFieldException: A requested field does not exist.

• NoSuchMethodException : A requested method does not exist.

Page 23: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Interface:

• An interface is basically a kind of class.• Like classes interface contains methods and

variables.• The interface defines the abstract method and

final fields only.• That means interfaces do not supply any code to

implement these methods.• It is necessary to implement an interface and it

is the responsibility of a class which wants to use it.

Page 24: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Interface:

• To implement• access class classname[extends superclass]• [implements interface [,interface…]]• {//class body….• }

Think……..• Can we use public as access? • Can we extend an interface?

Page 25: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Inheritance and Interfacesclass Student{

int rollNumber;void getNumber(int n) { rollNumber=n;}

void putNumber() {System.out.println(“RollNo:“ +rollNumber);}

}class Test extends Students{ float part1, part2;void getMarks(float m1, float m2) {part1=m1; part2=m2;}

void putMarks() {System.out.println(“Marks Obtained”); System.out.println(“ Part1= “ + part1); System.out.println(“ Part2= “ + part2); }}

interface Sports{ float sportWt=6.0; void putWt();}

Page 26: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Inheritance and Interfacesclass Results extends Test implements Sports{ float total; public void putWt(){System.out.println(“SporWt= “+ sportWt);}

void display () { putNumber(); putMarks(); PutWt();total= part1+part2+sportWt;System.out.println(“Total= “+ total);}}

class Hybrid{ public static void main(String args[]){ Results student1= new Results(); student1.getNumber(1234); student1.getMarks(27.5, 33.0); student1.display();}}

Student

Test

Result

Sports

Page 27: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Packages:

• By organizing classes into packages achieve the following benefits:– Classes contained in can be easily reused.

– Two classes in two different package can have same name.

– Hides classes and make program simple and modular.

– Provides a way for separating design from coding.

Page 28: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Frequently Used Java API Packages:

Java

applet

net

awt

io

util

lang

Page 29: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Using System Packages:

Colour

Graphics

Font

Image

awtJava

Use import java.awt.*;

Page 30: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Using Package:

Creating a package:package firstPackage;public class FirstClass {……. body of class….. }

Accessing the package:Import firstPackage.*;

Page 31: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Package Example

package package1; public class ClassA{ public void displayA()

{System.out.println("Class A");} } //-------------- end of ClassA ---------

• Make a directory called package1 and Write this file under the name ClassA.java and compile it. It will not run. WHY?

Page 32: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Package Example

• Go to main/higherlevel directory (contains subditectory as package1) and write, compile and execute the following file.

import package1.ClassA;class PackageTest1{ public static void main(String args[]){

ClassA ObjectA = new ClassA(); ObjectA.displayA();} }

Page 33: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Reading characters from console:

• import java.io.*;• class Read{• public static void main(String args[]) throws IOException{• char c;• BufferedReader br= new BufferedReader(new

InputStreamReader(System.in));• System.out.println("Enter characters:, 'q' to quit");• do{• c=(char)br.read();• System.out.println(c);• } while (c!='q');• } }

Page 34: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• An enum type is a type whose fields consist of a fixed set of constants.

• Common examples include compass directions (values of NORTH,

SOUTH, EAST, and WEST) and the days of the week.

• Because they are constants, the names of an enum type's fields are in uppercase letters.

• For example, no od days in week can be defined as follows:public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

Enum types:

Page 35: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day)

{ case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; }

} // ond of tell like I method………….

Page 36: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); //--------------------EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY);

seventhDay.tellItLikeItIs(); } // end of main} // end of class

Page 37: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• The output is:Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best. Weekends are best.

Output is…

Page 38: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• The enum declaration defines a class (called an enum type). • The enum class body can include methods and other fields.

• The compiler automatically adds some special methods when it creates an enum.

• For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

• This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

• For example, this code from the Planet class example below iterates over all the planets in the solar system.

• //for (Day day : Day.values()) { System.out.printf(p);} (not checked yet….)

Page 39: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

What is thread?

• Thread is a short form of Threads of control.• Thread of control is path taken by program during

execution.

• Having multiple threads of control is like executing task from two lists.

• Each thread begins execution at a predefined well known location eg. main().

• Threads are single-minded in their purpose, always executing the next statement in the sequence.

Page 40: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• Each thread executes its code independently of other threads in the program.

• The threads have access to various types of data. That is for

each independent thread, there is separate list of private/local variables, if they have to be shared, a copy is made.

• Objects and instances can be shared with permission by two or more threads.

• Static variables are automatically shared between threads in a Java program.

Page 41: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Non blocking I/O:

• Non Blocking I/O: when server is not available, or busy, separate thread can be extended to the task and focus can be given on other tasks.

• Alarms and timers: The program set the timer and continues processing. When time expires, the program receives some sort of message/signal.

• Independent tasks : Such as autosave in word processor

• Multiple CPUs

Page 42: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• There are two ways to create a thread.– Extend the java.lang.Thread class– Implement the java.lang.Runnable interface.

• Once you have a Thread object, you call its start method to start the thread.

• When a thread is started, its run method is executed.

• Once the run method returns or throws an exception,

the thread dies and will be garbage-collected.

Page 43: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• Every Thread has a state and a Thread can be in one of these six states.

• new. A state in which a thread has not been started.

• runnable. A state in which a thread is executing.

• blocked. A state in which a thread is waiting for a lock to access an object.

• waiting. A state in which a thread is waiting indefinitely for another thread to perform an action.

• timed__waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action.

• terminated. A state in which a thread has exited.

• The values that represent these states are encapsulated in the java.lang.Thread.State enum. The members of this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED.

Page 44: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,
Page 45: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Method Return Type Description

currentThread( ) Thread Returns an object reference to the thread in which it is invoked.

getName( ) String Retrieve the name of the thread object or instance.

start( ) void Start the thread by calling its run method.

run( ) void This method is the entry point to execute thread, like the main method for applications.

sleep( ) void Suspends a thread for a specified amount of time (in milliseconds).

isAlive( ) boolean This method is used to determine the thread is running or not.

activeCount( ) int This method returns the number of active threads in a particular thread group and all its subgroups.

interrupt( ) void The method interrupt the threads on which it is invoked.

yield( ) void By invoking this method the current thread pause its execution temporarily and allow other threads to execute.

join( ) void

This method and join(long millisec) Throws InterruptedException. These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.

Thread class methods:

 

Page 46: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

class MyThread extends Thread{ String s=null;

MyThread(String s1){ s=s1; start(); } // constructor of the thread………………..

public void run(){ System.out.println(s); }

} // end of MyThread class

//-------------------------------------new class-------------------------------public class RunThread{ public static void main(String args[]){ MyThread m1=new MyThread("Thread started....");}

}

C:>javac RunThread.javaC:>java RunThreadThread started....

Page 47: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

• class MyThread1 implements Runnable{ Thread t; String s=null; //constructor ------------------------------------------------------- MyThread1(String s1){ s=s1; t=new Thread(this);

t.start(); } //--------------------------run method------------------------------public void run() { System.out.println(s); } }//=========================new class================

public class RunableThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); }}

Implementing Runnable Interface

Page 48: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

import java.io.IOException;public class Threads extends Thread{ public static void main(String[] args){

Thread th = new Thread(); System.out.println("Numbers are printing line by line after 5 seconds : "); try{ for(int i = 1;i <= 10;i++) { System.out.println(i);

th.sleep(5000); } } catch(InterruptedException e){ System.out.println("Thread interrupted!"); //----------------------------------- } }}

Page 49: Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,

Main Reference:Patrick Naughton and Herbert Schildt, The Complete Reference Java 2, Third Edition, Tata McGraw Hill Pub., 1999.Visit pritisajja.info to download this show….