JavaProgramming notes-Unit2
JavaProgramming notes-Unit2
DEFINING PACKAGE:
Packages are containers for classes that are used to keep the class name space
compartmentalized. Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.
import java.io.*;
Here we are importing classes of java.iopackage. Here, javais a directory name and
iois another sub directory within it. The ‘*’represents all the classes and interfaces of
that io sub directory. We can create our own packages called user-defined packages
or extend the available packages. User-defined packages can also be imported into
other classes and used exactly in the same way as the Built-in packages.
ADVANTAGES OF PACKAGES:
Packages are useful to arrange related classes and interfaces into a group. This
makes all the classes and interfaces performing the same task to put together in the
same package. For example , in Java, all the classes and interfaces which perform
input and output operations are stored in java.io. package.
Packages hide the classes and interfaces in a separate sub directory, so that accidental
deletion of classes and interfaces will not take place.
The classes and interfaces of a package are isolated from the classes and interfaces of
another package. This means that we can use same names for classes of two different
classes. For example, there is a Date class in java.util package and also there is
another Date class in java.sql package.
A group of package called a library. The classes and interfaces of a package are likes
books in a library and can be reused several times. This reusability nature of packages
makes programming easy.
Just think, the package in Java are created by JavaSoft people only once, and millions
of programmers all over the world are daily by using them in various programs.
User-defined packages
Built-in packages:
These are the packages which are already available in Java language. These packages
provide all most all necessary classes, interfaces and methods for the programmer to
perform any task in his programs. Since, Java has an extensie library of packages, a
programmer need not think about logic for doing any task. For everything, there is a
method available in Java and that method can be used by the programmer without
developing the logic on his own. This makes the programming easy. Here, we introduce
some of the important packages of Java SE:
Java.lang:langstandsforlanguage.Thispackagegotprimaryclassesandinterfacesessential
for developing a basic Java program. It consists of wrapper classes(Integer, Character,
Float etc), which are useful to convert primitive data types into objects. There are
classes like String, SttringBuffer, StringBuilder classes to handle strings. There is a
thread class to create various individual processes. Runtime and System classes are
also present in java.lang package which contain methods to execute an application and
find the total memory and free memory available inJVM.
Java.util:util stands for utility. This package contains useful classes and interfaces
like Stack, LinkedList, Hashtable, Vector, Arrays, etc. thses classes are collections.
There are also classes for handling Date and Time operations.
Java.io:io stands for input and output. This package contains streams. A stream
represents flow of data from one place to another place. Streams are useful to store
data in the form of files and also to perform input-output relatedtasks.
Java.awt:awt stands for abstract window toolkit. This helps to develop GUI(Graphical
user Interfaces) where programs with colorful screens, paintings and images etc., can
be developed.
It consists of an important sub package, java.awt.event, which is useful to provide
action for components like push buttons, radio buttons, menus etc.
Javax.swing:this package helps to develop GUI like java.awt. The ‘x’ in javax
represents that it is an extended package which means it is a package developed from
another package by adding new features to it. In fact, javax.swing is an extended
package ofjava.awt.
Java.net:net stands for network. Client-Server programming can be done by using this
package. Classes related to obtaining authentication for network, creating sockets at
client and server to establish communication between them are also available in
java.netpackage.
Java.applet:applets are programs which come from a server into a client and get
executed on the client machine on a network. Applet class of this package is useful to
create and use applets.
Java.text:this package has two important classes, DateFormat to format dates and
times, and NumberFormat which is useful to format numericvalues.
User-Defined packages:
Just like the built in packages shown earlier, the users of the Java language can also
create their own packages. They are called user-defined packages. User-defined
packages can also be imported into other classes and used exactly in the same way as
the Built-in packages.
While creating a package except instance variables, declare all the members and
the class itself as public then only the public members are available outside the
package to other programs.
package pack;
public
classAddition
{ d1 = a;
d2 = b;}
}}
pack import
pack.Addition; class
Use
ob1.sum();
}
}
Output:
Program 3: Write a program to add one more class Subtraction to the same package
pack.
d1 = a;
d2 =
b;
Program 4: Write a program to access all the classes in the package pack.
//To import all the classes and interfaces in a class using import
pack.*; import pack.*;
class Use
ob1.sum();
Subtraction(30.2,40.11); ob2.difference();
}
In this case, please be sure that any of the Addition.java and Subtraction.java programs
will not exist in the current directory. Delete them from the current directory as they
cause confusion for the Java compiler. The compiler looks for byte code in
Addition.java and Subtraction.java files and there it gets no byte code and hence it flags
some errors.
UNDERSTANDING CLASSPATH:
If the package pack is available in different directory, in that case the compiler should be
given information regarding the package location by mentioning the directory name of
the package in the classpath.
The CLASSPATH is an environment variable that tells the Java compiler where to look
for class files toimport.
If our package exists in e:\sub then we need to set class path as follows:
We are setting the classpath to e:\sub directory and current directory (.) an
%CLASSPATH% means retain the already available classpath as it is.
Creating Sub package in a package: We can create sub package in a package in the
format: package packagename.subpackagename;
Here, we are creating pack2 subpackage which is created inside pack1 package.
To use the classes and interfaces of pack2, we can write import statement as:
import pack1.pack2;
Program 5: Program to show how to create a subpackage in a package.
//Creating a subpackage in a
ACCESSING A PACKAGES:
Access Specifier: Specifies the scope of the data members, class and methods.
private members of the class are available with in the class only. The scope of
private members of the class is “CLASS SCOPE”.
public members of the class are available anywhere . The scope of public members
of the class is "GLOBAL SCOPE".
default members of the class are available with in the class, outside the class and
in its sub class of same package. It is not available outside the package. So the
scope of default members of the class is "PACKAGE SCOPE".
protected members of the class are available with in the class, outside the class and in
its sub class of same package and also available to subclasses in different package
also.
Program 6: Write a program to create class A with different access specifiers.
//create a package
public class A
public int b = 2;
protected int c =
3; int d = 4;
//class B of same
package package
same;
import
same.A;
public class
{
public static void main(String args[])
System.out.println(obj.a
);
System.out.println(obj.b
);
System.out.println(obj.c
);
System.out.println(obj.d
);
}}
package
another;
import same.A;
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
abstract methods.
implement it.
All the methods of the interface should be implemented in its implementation classes.
If any one of the method is not implemented, then that implementation class should be
declared as abstract.
Exception Handling
Exception
Is an abnormal condition that arises in a code sequence at runtime.
Java Exception is an object that describes an exceptional condition that has occured
in a piece of code.
When an exceptional condition arises, an Object representing that exception is
created and thrown in the method that causes the error.
The method may choose to handle it or pass it to its caller.
Caller may choose to handle it or pass it to its caller. And so on till main method.
If main is also not interested to process the exception, then it will be thrown to JRE,
which uses default Exception Handler mechanism to process it.
Exception can be generated by JRE or can be manually generated.
keywords
Exception handling is managed via the following keywords
try
catch
finally
Throw
Throws
try block
Program statements that you want to monitor for exception are kept in the try block.
If an exception occured in the try block, it is thrown to its catch block.
Catch block
To process the Exception
That is write the code (may vary for each type of exception) that should get executed
when an exception is raised.
A try block can follow multiple catch blocks.
Each catch block can process a specific type of exception.
In multiple catch statements it is imortant to remember that exception subclasses
must come before any of their super classes.
From java 1.7 , java support multi catch blocks.
finally block
This block get executed after the completion of try block.
This block gets executed irrespective of whether the exception is raised or not, if
raised wheter it is handled or not.
Useful for closing file handles and freeing up of any other resources that might have
been allocated at the begining.
Every try block must be followed by at least one catch block or finally block.
try with resources
Runtime automatically closes the resources (if they are not already closed) after the
excecution of the try block.
try( BufferedReader br=
new FileReader(“ex1.txt”) ) {
}
catch(){}
This works only on classes that have implemented AutoCloseable interface.
Exception Types
Throwable
Exception
ClassNotFoundException(checked)
IOException
InterruptedException
RuntimeException(un checked)
ArithmeticExcepton
NumberFormatException
ArrayIndexOutOfBoundsException
ExceptionInInitializerError
Error
Un caught Exceptions
Class Ex1
{
pubic static void main(String args[])
{
int d=0;
int a=40/d;
}
}
Exception caught by default Exception handler of JRE.
Displays the string describing the exception, prints the stack trace from the point at
which exception occured and terminates the program.
Java.lang.ArithmeticException: / by Zero
at Ex1.main (Ex1.java : 6)
Example2
Class Ex1
{
static void meth1(){
int d=0; int a=40/d;
}
pubic static void main(String args[])
{
meth1();
}
}
Exception raised in meth1(), not handled, thrown to main(), not handled, thrown to
JRE.Exception caught by default Exception handler of JRE.
prints the stack trace as follows
Java.lang.ArithmeticException: / by Zeo
at Ex1.meth1 (Ex1.java : 4)
at Ex1.main (Ex1.java : 8)
Example_Porgram:
/*program with the following statements and observe the output.
System.out.prinrtn("Hello");
System.out.printtn("NGIT");
System.out.prinrtn(10/0);
System.out.prinrtn("Have a nice day");
System.out.prinrtn("Bye");
*/
class demo1
{
public static void main(String args[])
{
System.out.println("Hello");
System.out.println("NGIT");
System.out.println(10/0);
System.out.println("Have a nice day");
System.out.println("Bye");
}
}
Advantage of Handling an Exception
Stops abnormal termination.
Instead of printing the stack trace we can display user friendly messages to the user
related to the exception.
Allows us to fix the error.
Example_Program:
/* to demonstrate advantage of handling exception.
program to get the following output in same order
Use exception handling
Hello
NGIT
10/0 is invalid operation
All the Best
Bye
*/
class demo2
{
public static void main(String rags[])
{
System.out.println("Hello");
System.out.println("NGIT");
try
{
System.out.println(10/0);
}
catch(ArithmeticException ae)
{
System.out.println(ae.getMessage());
System.out.println(ae);
}
System.out.println("All the Best");
System.out.println("Bye");
}
}
Example_Program:
//demonstration of finally block.
class demo3
{
public static void main(String[] args)
{
int a=1,b=0,c;
try
{
c=a/b;
}
catch(ArithmeticException ae)
{
System.out.println(" Error: denominotor cant be zero");
}
finally
{
System.out.println("This will execute");
}
}
}
Example_Program:
// To demonstration finally block another example
class demo4
{
public static void main(String[] args)
{
int a=10,b=5,c;
try
{
c=a/b;
System.out.println("result= "+c);
}
catch(ArithmeticException ae)
{
System.out.println(" Error "+ae);
}
finally
{
System.out.println("This will execute");
}
}
}
Example_Program:
/*Program to demonstrate ArrayIndexOutOFBoundsException*/
class demo5
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};
System.out.println(a[0]);
System.out.println(a[1]);
try
{
System.out.println(a[5]);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("Invalid index");
}
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
}
}
Example_Program:
/*program to demonstrate NullPointerException for Scanner class object
*/
import java.util.*;
class demo6
{
public static void main(String args[])
{
Scanner s=null;
try
{
int a=s.nextInt();
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
System.out.println("End of the program");
}
}
Example
Example_Program:
//To demonstrate multiple catch blocks
class demo7
{
public static void main(String[] args)
{
int a[]={10,20,30,40,50,60};
try
{
// int c=a[10]/0;
int c=a[1]/0;
System.out.println("result= "+c);
}
catch(ArithmeticException ae)
{
System.out.println(" Error "+ae);
}
catch(ArrayIndexOutOfBoundsException ab)
{
System.out.println("Error : "+ab);
}
finally
{
System.out.println("this will execute");
}
}
}
Example_Program:
//To demonstrate multi-catch block
class demo8
{
public static void main(String[] args)
{
int a[]={10,20,30,40,50,60};
try
{
int c=a[10]/0;
// int c=a[1]/0;
System.out.println("result= "+c);
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException ae)
{
System.out.println("Error : "+ae);
}
finally
{
System.out.println("this will execute");
}
}
}
Example_Program:
//To demonstrate catch all catch block
class demo9
{
public static void main(String[] args)
{
int a[]={10,20,30,40,50,60};
try
{
int x=Integer.parseInt("5a");
int c=a[10]/0;
System.out.println("result= "+c);
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException ae)
{
System.out.println("Error : "+ae);
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
finally
{
System.out.println("this will execute");
}
}
}
Throw
To Manually throw an exception object.
Syntax:
throw throwable_instance.
The object thowable_instance must be an instance of Throwable class type.
When you manually throw an exception object from the try block ,it checks for the
matching catch block among the catch blocks which follows the try block.
If there is a match, the exception is caught by that catch block and it can process that
exception(optional).
After processing, if needed the method can rethrow the exception object to its caller
to give an oppurtunity to the caller to know about this exception and to process.
This caller can rethrow the exception object to its caller. And so on.
If ther is no matching catch block, the exception object is thrown to its caller.
If the caller also does not handle that exception, it will be thrown to its caller and so
on till the main method.
If main method also do not handle it, it will be thrown to JRE.
At a time we can throw only one Exception object.
If we need to report more that one exception, we need to chain the exceptions with
their cause exceptions.
Example_Program:
// To demonstrate throw keyword
class demo12
{
static void meth1()
{
try
{
int x=12/0;
}
catch(ArithmeticException e)
{
System.out.println("caught inside method:"+e);
throw e;
}
}
public static void main(String args[])
{
try
{
meth1();
}
catch(ArithmeticException e)
{
System.out.println("Recaught:"+e);
}
}
}
Example_Program:
// To demonstrate throw keyword- another example
class demo13
{
static void meth1()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("caught inside method:"+e);
throw e;
}
}
public static void main(String args[])
{
try
{
meth1();
}
catch(NullPointerException e)
{
System.out.println("Recaught:"+e);
}
}
}
Throws
If a method is capable of causing an exception that it does not handle, it must specify
this behaviour so that callers of this method can guard themselves against that
exception.
Not necessary for exceptions that are subclasses of RuntimeException class.
The overridden method can declare the same exceptions as that of its super class.
The overridden method can be defined as not throwing any exceptions.
Can add any new RuntimeExceptons (un checked).
Can't and any new Checked Exceptions.
Can narrow down to the Exception subclasses declared in the parent class.
Can't specify super classes of the chekced exceptions declared in the parent class.
Example_Program:
// To demonstrate final rethrow
import java.io.*;
class demo15
{
static void meth1(int x) throws IOException,InterruptedException
{
try
{
if(x == 0)
throw new IOException();
else
throw new InterruptedException();
}
catch(Exception e)
{
throw e;
}
}
public static void main(String args[])
{
try
{
meth1(0);
}
catch(IOException | InterruptedException e)
{
System.out.println(e);
}
}
}
we can create our own Exceptions by extending from the class Exception.
Example_Program:
// User defined exceptions
import java.util.*;
class Vote extends Exception
{
Vote(String str)
{
super(str);
}
}
class demo16
{
public static void meth1(int age) throws Vote
{
if(age<18)
throw new Vote("Not eligible to vote");
System.out.println("Eligible to vote");
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter your age:");
int age=s.nextInt();
try
{
meth1(age);
}
catch(Vote v)
{
System.out.println("Error "+v);
}
}
}
Multithreading
Multitasking
Executing multiple tasks simultaneously.
Each task consists of cpu bound instructions and I/O bound instructions.
During I/O instruction execution, the cpu(processor) will be idle.
Multi tasking utilizes this time by assigning others tasks to the processor.
By making processor busy, the throughput (number of jobs that can be completed in
unit time) can be increased.
OS will use different cpu scheduling algorithms to share processor time among
multiple tasks.
A task can be atleast a program. We cant further subdivide.
Advantages
Reduces idle time of the cpu (increase throughput)
Quick response time.
Multithreading
Specialized form of multitasking.
Each task can be a thread.
A program can consists of two or more threads that can run concurrently.
Each thread defines a separate path of execution.
Threads are light weight, they share the same address space.
Context switching is easier.
Java provides built in support for multithreading.
In java the execution of main method itself is a thread created automatically when the
program started.
Creating a thread
We can create a new thread in two ways
1. by extending Thread class.
2. by implementing Runnable interface.
sleep()
Syntax: sleep(long millisec);
Static method
Makes the current thread to suspend its execution for specified millis secods.
If the thread is interrupted before the sleep time expires, it throws
InterruptedException.
class demo1
{
public static void main(String args[])
{
MyThread m=new MyThread();
m.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread:"+i);
}
}
}
class demo4
{
public static void main(String args[])
{
FifthTable f=new FifthTable();
SixthTable s=new SixthTable();
f.start();
s.start();
}
}
Thread priorities
An integer value that specify relative priority of one thread to another.
Among the threads of equal priority, JRE (Thread shedular) may schedule threads in
any order for execution.
Methods:
setPriority(int priority)
int getPriority()
Priority value ranges from 0(low) to 10(high).
Normal priority is 5.
These are represeted by final static variables in Thread class
Thread.MIN_PRIORITY
Thread.MAX_PRIORITY
Thread.NORM_PRIORITY
Thread schedular may give preference to high priority threads while scheduling
threads for execution.
Thread priorities are only to influence the thread schedular.
Can't rely on them.
for(int i=0;i<10;i++)
System.out.print("\nchild thread "+i);
}
System.out.println(Thread.currentThread().getPriority());
for(int i=0;i<1000;i++)
System.out.print("\nMain thread "+i);
}
}
Context switching
A thread can voluntarily relinquish control.
A thread can be preempted by a higher priority thread.
yield()
Pauses the currently executing thread temporarily for giving a chance to the
remaining threads of the same priority to execute.
If there is no waiting thread or all other waiting threads have a lower priority then the
same thread will continue its execution.
The yielded thread when it will get the chance for execution is decided by the thread
scheduler.
class demo7
{
public static void main(String args[])
{
MyThread m=new MyThread();
m.start();
for(int i=0;i<100;i++)
{
System.out.println("Main Thread "+i);
}
}
}
isAlive() : helps us to know whether the thread has finished its execution or not.
join() : makes the the caller thread to wait until the thread on which join() has
invoked completes it execution.
synchronization
Wihen two or more threads needs access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by
which this is achieved is called synchronization.
Monitor
How to synchronize
Method synchronization
Whichever the methods of the resource(object) you want to synchronize, decalare
those methods with synchronized modifier.
All objects have implicit monitor.
To enter an objects monitor, just call any synchronized method.
Note:
While a thread is inside a synchronized method, all other threads that try to call it (or
any other synchronized method) on the same object have to wait.
class Display
{
public void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.println(name);
}
}
}
class Mythread extends Thread
{
Display d;
String name;
Mythread(Display d,String name)
{
this.d=d;
this.name=name;
}
class Display
{
public synchronized void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning : ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print(name);
System.out.println();
}
}
}
class Mythread extends Thread
{
Display d;
String name;
Mythread(Display d,String name)
{
this.d=d;
this.name=name;
}
Synchronized block
If you want to synchronize access to objects of a class that was not designed for
multithreaded access (that is the class does not use snchronzed methods).
If the class was created by a third party, we do not have access to the code.
Then we can acquire lock on the object with synchronized block.
syntax
synchronized(target_instance)
{
target_instance.method1();
}
Example_Program : Synchronized block example.
class Display
{
public void wish(String name)
{
synchronized(this)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning : ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print(name);
System.out.println();
}
}
}
}
Note:
Static and non static synchronized methods will not block each other (ie they can run
at the same time from different threads since they acquire lock on different things).
Causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
wakes up all the threads that are waiting on this object's monitor.
One of the thread will be granted access by the Thread Schedular.
These three methods are not from Thread class, these are from Object class.
Note:
1) There exists a very rare possibility that the waiting thread resumes without
notify(). (for no apparent reason)
Oracle recommends that calls to wait() should take place with in a loop that checks
the condition on which the thread is waiting.
2) IllegalMonitorStateException
Thrown to indicate that a thread has attempted to wait on an object's monitor Or to
notify other threads waiting on an object's monitor without owning the specified
monitor.
3) You must call the wait(), notify() or notifyAll() from a synchronized context.
class Buffer
{
int a;
boolean produced = false;
if(produced)
{
System.out.println("Producer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
a=x;
System.out.println("Product" + a + " is produced.");
produced = true;
notify();
}