0% found this document useful (0 votes)
5 views37 pages

Java Unit-3

Uploaded by

anugrahd017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views37 pages

Java Unit-3

Uploaded by

anugrahd017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-3

Packages in Java
A package is a collection of classes and interfaces. It acts as a container for
classes and interfaces. Java provides the following built-in packages:

[Link], [Link], [Link], [Link], [Link], etc.

Creating a package:

To create a package, simple include a ‘package’ command as the first


statement in a Java source file. Any classes declared within that file will belong
to the specified package. The ‘package’ statement defines a namespace in
which classes are stored. The general form is:

package pkg;

Where, pkg is the name of the package

Java uses the file system directories to store the packages. It involves the
following steps:

1. Declare the package at the beginning of the file


2. Define the class under the package
3. Create a subdirectory under the directory where the main source files
are stored
4. Store the package file in the subdirectory
5. Compile the package file

Example:

package p1;

public class Sample

public void show()

[Link](“Inside the package”);


}

Accessing a package:

The classes in the package can be imported into a new file by using the
‘import’ statement. It takes the following general form:

import packagename.*;

or

import [Link];

Example:

import [Link].*;

import [Link].*;

import [Link];

Sample program using package:

//[Link]

package p1;

public class Sample

public void show()

[Link](“Inside the package”);

Then, compile the package file:

D:\Programs\p1>javac [Link]
This command produce [Link] file under the directory ‘p1’

Then, create a main file:

//[Link]

import java.p1.*’

class Demo

public static void main(String args[])

Sample ob=new Sample();

[Link]();

Then, compile main file:

D:\Programs>javac [Link]

Run the program:

D:\Programs> java Demo

Inside the package

Classpath:

The classpath is a parameter in the JVM or java compiler that specifies the
location of user-defined classes and packages. The parameter may be set
either on the command line or through an environment variable.

Eg:-C:\> set classpath=D:\Programs

This command instructs all user-defined classes are defined under the
directory “Programs” in D drive.
Interfaces in Java

Java does not support multiple inheritance. Java provides an alternative


approach known as interface to support the concept of multiple inheritance.
An interface defines what a class must do but not how it does. An interface
defines the structure of the methods and final variables.

Defining an interface:

The general form of an interface definition is:

interface interface_name

Methods declarations:

Variables declarations;

Where, interface is the keyword that defines interface and interface_name is a


valid identifier. Methods declarations will contain only a list of methods
without the body. All variables are declared as constants using ‘final’ keyword.

Example:

interface Shape

public void area();

Implementing interfaces:

After defining an interface, one or more classes can implement that


interface. To implement an interface, use the ‘implements’ keyword in a class
definition and then create the methods defined by the interface. The general
form is:
class class_name implements interface_name

Body of the class

Example:

class Circle implements Shape

public void area()

[Link](“Area ofcircle”);

Here, Shape is the interface and area() is the method of this interface.

Sample program using interface:

interface Shape

public void area();

class Circle implements Shape

public void area()

[Link](“Area of circle”);
}

class Demo

public static void main(String arts[])

Circle c1=new Circle();

[Link]();

Implementing multiple interfaces:

In Java, we can derived from a single class and implements as many


interfaces. When a class implements more than one interfaces, they are
separated by commas. It takes the following form:

class class_name extends super_class implements interface-1, interface-2, …

Body of the class

Eg:-

class B extends A implements I1, I2, I3

}
Where, A is the superclass and I1, I2 and I3 are interfaces

Example:

interface Animal

public void eat();

interface WildAnimal

public void roar();

class Tiger implements Animal, WildAnimal

public void eat()

[Link](“Animal eats..”);

public void roar()

[Link](“Animal roars..”);

}
Extending interface:

Like classes, interface can also be extended. That is, an interface can be sub
interfaced from other interface. The sub interface will inherit all the members
of the super interface. It takes the general form:

interface interface-2 extends interface-1

Member of interface;

Example:

interface Animal

public void eat();

interface WildAnimal extends Animal

public void roar();

class Tiger implements WildAnimal

public void eat()

[Link](“Animal eats..”);

}
public void roar()

[Link](“Animal roars..”);

Exception handling:

An exception is a condition that is caused by a run time error in a


program. When the Java compiler encounters an error such as dividing an
integer by zero, it creates an exception object and throws it. If the exception
object is not handled properly, the compiler will display an error message and
will terminate the program.

If we want to continue the program with the execution of the remaining


code, then we should try to catch the exception and handle the exception
properly. The exception handling mechanism performs the following tasks:

1. Find the problem


2. Inform that an error has occurred (throw the exception)
3. Receive the error information ( catch the exception)
4. Take correct actions (handle the exception)
Syntax of exception handling:

Java provides the keywords ‘try’ and ‘catch’ to handle the exception

try

Statement;

catch(Exception_type e)

Statement;
}

Here, the try block contains the statement that may cause an exception. The
catch block contains the statement that handles the exception. It is
diagrammatically expressed as

Try block

Statements that may


causes an exception Exception object creator

throw

Catch block

Statements that Exception handler


handle an exception

The try block contains one or more statements that generate an exception.
If anyone statement generates an exception, the remaining statements in the
try block are skipped and execution jumps to the catch block. The catch block
contains one or more statements that are necessary to processes the
exception.

Example:

class Demo

public static void main(String arts[])

{
int a=25, b=0, c;

try

c=a/b;

[Link](“Result is “+c);

catch(ArithmeticException e)

[Link](“Division by zero not possible”);

[Link](“Thank you..“);

} Output

} Division by zero not possible

Thank you..

Multiple catch statements:

It is possible to have more than one catch statement in the catch block as
shown below:

try

Statement;

catch(Exception_type-1 e)

Statement;
}

catch(Exception_type-2 e)

Statement;

-------------

catch(Exception_type-n e)

Statement;

When an exception in a try block is generated, the try block throws the
exception to the corresponding catch statement.

Example:

import [Link].*;

class Demo

public static void main(String arts[])

int a, b, c;

Scanner ob =new Scanner ([Link]);

try

[Link](“Enter first number”);

a=[Link]();
[Link](“Enter second number”);

b=[Link]();

c=a/b;

[Link](“Result is “+c);

catch(ArithmeticException e)

[Link](“Division by zero not possible”);

catch(InputMismatchException e)

[Link](“You must enter integer values”);

catch(Exception e)

[Link](“Some other error has occurred”);

Output-1

Enter first number 28

Enter second number 0

Division by zero not possible


Output-2

Enter first number 28

Enter second number 23.56

You must enter integer values

finally statement:-

Finally block in Java can be used to put clean-up code such as closing a file,
closing database connection, etc. Java finally block is always executed whether
the exception is handled or not. Java finally block follows try or catch block.

Syntax:

try try

{ {

//statements //statements

} }

catch(Exception_type e) finally

{ {

// statements // final code

} }

finally

// final code

}
Eg:-

try

[Link](5/0);

catch(ArithmeticExceptionae)

[Link](“Division by zero not possible…”);

finally

[Link](“I am always executed”);

Output:

Division by zero not possible…

I am always executed

Nested try

We can use a try statement within another try statement. This structure is
called nested-try.

Syntax:

t ry

//statement

try
{

// statement

catch(Exception_type e)

// statement

catch(Exception_type e)

// statement

Example:

import [Link].*;

class Nested

public static void main(String args[])

Scanner ob=new Scanner([Link]);

int a;

try

[Link]("Enter the divisor:");


a=[Link]();

try

[Link](10/a);

catch(ArithmeticException e)

[Link](“Division by zero not possible”);

catch(InputMismatchException e)

[Link](“Please enter integer value”);

Output:

Enter the divisor:0

Division by zero not possible

Enter the divisor: abc

Please enter integer value


throws keyword:

The throws keyword delegates the responsibility of the exception


handling to the caller of the method. We can do this by including a throws
keyword in the method’s declaration.

Syntax:

type methodname(paramaters) throws exception_list

// method body

Where, exception_list is a comma-separated list of the exceptions that a


method can throw.

Example:

class Demo

static void f1()throws ArithmeticException

[Link](5/0);

public static void main(String args[])

try

f1();

}
catch(ArithmeticException e)

[Link](“Division by zero not possible”);

throw keyword:

The throw keyword in Java is used to explicitly throw an exception from a


method or any block of code. The throw keyword is mainly used to throw
custom or user-defined exceptions.

Syntax: throw Exception_object;

Example:

try

ArithmeticExceptionae=new ArithmeticException();

throw ae; // or throw new ArithmeticException();

catch(ArithmeticException ae)

[Link](“Division by zero not possible”);

User-defined Exception:

We can create our own exception class to handle the user-defined


exception. We can do this by extending any built-in exception class like
Exception and using throw keyword.
Example:

import [Link].*;

class InvalidRollnoException extends Exception

class Demo

public static void main(String args[])

Scanner ob=new Scanner([Link]);

int rno;

[Link]("Enter the rollno:");

rno=[Link]();

try

if(rno<1)

throw new InvalidRollnoException();

[Link](rno);

catch(InvalidRollnoException e)

{
[Link](“Rollno is invalid”);

Output:

Enter the rollno: -5

Rollno is invalid

Chained Exception:

Chained exception helps to identify a situation in which one exception


causes another exception in an application. For example, consider a method
which throws an ArithmeticException because of an attempt to divide by zero.
But, the actual cause of exception was an I/O error which is caused by the
divisor to be zero. The method will throw the ArithmeticException to the caller.
The caller would not know about the actual cause of an exception. Chained
exception is used in such situations. Java exception class provides two methods
to handle chained exception.

1. initCause():- It initializes or sets the actual cause of an exception


2. getCause():- It returns the actual cause associated with current
exception
Example:

import [Link].*;

class Chained

public static void main(String args[])

try
{
ArithmeticException ae=new ArithmeticException("division by zero error");

[Link](new IOException("input error"));

throw ae;

catch(ArithmeticException ae)

[Link]("Caught:"+ae);

[Link]("Actual cause:"+ [Link]()); }

Output

Caught: [Link]: division by zero error

Actual cause: [Link]: input error

Built-in Exception Classes:

Built-in exception classes are exceptions which are available in Java


libraries. The exception classes are,

1. ArithmeticException: It is thrown when an exceptional condition has


occurred in an arithmetic operation. Eg: Division by zero error
2. ArrayIndexOutOfBoundsException: It is thrown an array has been
accessed using an illegal index.
3. InputMismatchException:It is thrown when the user does not provide
the proper type of input.
4. StringIndexOutOfBoundsException:It is thrown a character of a string
has been accessed using an illegal index.
5. NumberFormatException: It is thrown when an attempt is made to
convert a string with improper format into a numeric value.
6. IOException: It is thrown when an input-output operation failed or
interrupted.
7. SQLException:It occurs if there is an error in the database access.
8. InterruptedException: It is thrown when a thread is waiting, sleeping, or
doing some processing, and it is interrupted.
9. ClassNotFoundException: It is thrown when we try to access a class
whose definition is not found.
[Link]: It is thrown when a file is not accessible or does
not open.
Checked and unchecked exceptions:

Checked exceptions are the exceptions that are checked at compile-time. If


some code within a method throws a checked exception, then the method
must either handle the exception or it must specify the exception using throws
keyword. Otherwise, the compiler generates an error message.

Example:

1. IOException
2. SQLException
3. InterruptedException
4. ClassNotFoundException
5. FileNotFoundException
Unchecked exceptions are the exceptions that are not checked at compile-
time. So, it is not forced by the compiler to either handle or specify the
exception.

Example:

1. ArithmeticException
2. NumberFormatException
3. InputMismatchException
4. ArrayIndexOutOfBoundsException
5. StringIndexOutOfBoundsException
Multithreading

Java supports the concept of multithreading which enables to execute two


or more parts of a program concurrently. Each part is known as a thread. A
thread is a separate execution part of a program. Multithreading means
performing multiple tasks at the same time during the execution of the
program.

Creating threads:-

Threads are objects in Java. It can be created by using two different


mechanisms.

1. Create a class that extends the Thread class


2. Create a class that implements the Runnable interface
Extending the Thread class: The steps for creating a thread by using this
mechanism are,

1. Create a class by extending the Thread class and override the run()
method
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
2. Create a thread object
MyThread t1=new MyThread();
3. Start execution of a thread
[Link](); // start() method call run method to execute a thread

Example:

class MyThread extends Thread


{
public void run()
{
[Link](“Thread is running…”);
}
}
class Demo
{
public static void main(String args[])
{
MyThread t1=new MyThread();
[Link]();
} Output:
} Thread is running…

Implementing the Runnable interface: The steps for creating a thread by using
this mechanism are,

1. Create a class by implementing the Runnable interface and override


run() method
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
2. Create the object t of the class
MyThread ob=new MyThread();
3. Create a thread object and pass class object as parameter
Thread t1=new Thread(ob);
4. Start execution of a thread
[Link]();// start() method call run method to execute a thread

Example:

class MyThread implements Runnable


{
public void run()
{
[Link](“Thread is running…”);
}
}
class Demo
{
public static void main(String args[])
{
MyThread ob=new MyThread();
Thread t1=new Thread(ob);
[Link]();
}
}

Output:

Thread is running…

Thread Life Cycle:

A thread goes through various stages in its life cycle. They

1. New born state


2. Runnable state
3. Running state
4. Blocked state
5. Dead state
A thread is always in one of these five states. It can move from one state to
another via a variety of ways as shown below:

A thread is always in one of these five states. It can move from one state to
another via a variety of ways as shown below:
New born

start()

stop()

Runnable

run() Dead

stop()
Running
resume()

notify() wait()

suspend()

sleep() stop()

Blocked

1. New born state: When we create a thread, the thread is born and is said
to be in born state. At this state, the thread calls the following methods:
a. start(): It initiates the thread’s execution
b. stop(): It terminates the thread’s execution
2. Runnable state: The runnable state means that the thread is ready for
execution and is waiting for the availability of the processor. The thread
is in runnable state, after the invocation of start() method.
3. Running state: Running means that the processor has given its time to
the thread for its execution. The thread is in running state, after the
invocation of run() method. During the execution, the thread is in one of
the following situations:
a. It has been suspended using suspend() method. A suspended
thread can be restarted by using the resume() method.
b. It has been made to sleep. We can put a thread to sleep for a
specified time period using the method sleep().
c. 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.

4. Blocked state: A thread is said to be blocked when it is prevented from


its execution. This happens when the thread is suspended, sleeping or
waiting. A blocked thread is considered “not runnable” but not dead and
therefore fully qualified to run again.
5. Dead state: A running thread ends its life cycle when it has completed
executing its run() method. It is a natural death. We can kill a thread
using stop() method at any state.

Thread Priorities:-

In Java, each thread is assigned a priority, which affects the order in which it is
scheduled for running. By default, all threads have same priority and therefore
they share the processor on a First-Come First-Serve manner. Java permits to
set the priority of a thread using the setPriority() method as follows:

[Link] (int_number);

Where, int_number is an integer value to which the thread’s priority is set. The
Thread class defines several priority constants:

MIN_PRIORITY=1

NORM_PRIORITY=5

MAX_PRIORITY=10

The int_number assume one of these constants or any value between 1 and
10. The default setting is NORM_PRIORITY.

Example:

class Mythread1 extends Thread


{
public void run()
{
[Link](“I am first thread…”);
}
}
class Mythread2 extends Thread
{
public void run()
{
[Link](“I am second thread…”);
}
}
class Demo
{
public static void main(String args[])
{
Mythread1 t1=new Mythread1();
Mythread2 t2=new Mythread2();
t1. setPriority(Thread.MIN_PRIORITY);
t2. setPriority(Thread.MAX_PRIORITY);
[Link]();
[Link]();
}

Output:

I am second thread…

I am first thread…

getPriority() mathod: It returns the current priority of a thread.

Example:

Mythread1 t1=new Mythread1();


Mythread2 t2=new Mythread2();
t1. setPriority(1);
t2. setPriority(10);
[Link](“Priority of first thread:”+t1. getPriority());
[Link](“Priority of second thread:”+t2. getPriority());

Output:

Priority of first thread: 1

Priority of second thread: 10

Synchronization:

It is the capability to control the access of multiple threads to any shared


resources. The “synchronized” keyword in Java is used to provide mutually
exclusive access to a shared resources with multiple threads. The
synchronization is mainly used to prevent thread interference and consistency
problem.

Eg:-

synchronized void disp()

Here, the disp() method can access only one thread at a time.

Program to implement multithreading

class Mythread1 extends Thread

public void run()

try

[Link]("i am thread-1");

[Link](1000);

[Link]("end of thread-1");
}

catch(InterruptedException e)

[Link](e);

class Mythread2 extends Thread

public void run()

try

[Link]("i am thread-2");

[Link](1000);

[Link]("end of thread-2");

catch(InterruptedException e)

[Link](e);

}
}

class Demo

public static void main(String args[ ])

Mythread1 t1=new Mythread1();

Mythread2 t2=new Mythread2();

[Link]();

[Link]();

Output:

i am thread-1

i am thread-2

end of thread-1

end of thread-2

Enumeration:

An enumeration is a user-defined data type which contains a list of named


constants. An enumeration is created using the enum keyword.

Syntax:

enum Identifier

Value-1, Value-2, Value-3, …….., Value-n;


}

Where, identifier is a user-defined enumerated data type which can be used to


declare variables that can have one of the values enclosed within the braces
(known as enumerated constants).

After this definition, we can declare variables to be of this type as follows:

Identifier V1, V2, V3, ……, Vn;

Example:

enum DayName

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;

class Demo

public static void main(String args[])

DayNameday1, day2;

day1=DayName. SUNDAY;

day2=DayName. FRIDAY;

[Link](day1); Output

[Link](day2); SUNDAY

} FRIDAY

}
The values() and valueOf() methods:-

The values() method returns an array that contains a list of enumeration


constants. The valueOf() method returns the enumeration constant whose
value corresponding to the string passed.

enum Color

RED, GREEN, BLUE, YELLOW, ORANGE;

class Demo

public static void main(String args[])

Color c1;

c1=[Link](“GREEN”);

[Link](c1); // GREEN

Color c2[];

c2=[Link]();

for(inti=0;i<[Link];i++)

[Link](c2[i]);

} Output

} RED

GREEN
BLUE

YELLOW

ORANGE

Wrapper classes:

A wrapper class is a class which contains the primitive data types. In other
words, wrapper classes provide a way to use primitive type as object.

Primitive type Wrapper class


Int Integer
Float Float
Long Long
Short Short
Double Double
Byte Byte
Boolean Boolean
Char Character

Eg:- Integer m=new Integer(20);

Integer n=10; Output

[Link](m); 20

[Link] println(n); 10

Autoboxing:

The automatic conversion of primitive data types into its corresponding


wrapper class is known as autoboxing. For example, int to Integer, float to
Float, double to Double, etc

Example:

int num=10;
Integer ob;

ob=num; //autoboxing

[Link](num); Output

[Link](ob); 10

10

The automatic conversion of wrapper types into its corresponding primitive


types is known as auto-unboxing. It is the reverse process of autoboxing.

Example:

Integer ob=10;

int num;

num=ob; //auto-unboxing

[Link](num); Output

[Link](ob); 10

10

Output functions in Java: Output functions are defined under System class

1. [Link](): Prints the output and moves to the next line.


[Link](“hello world”);
2. [Link](): Prints the output and moves at the end of the line.
[Link]. print(“Hai”);

Input functions in Java: Input functions are defined under the Scanner class.
The Scanner class is defined under [Link] package.

1. nextInt(): Reads an integer from keyboard


2. nextFloat(): Reads a floating point value from keyboard
3. nextDouble(): Reads a double type value from keyboard
4. nextByte(): Reads a byte type value from keyboard
5. nextShort(): Reads ashort type value from keyboard
6. nextLong(): Reads a long type value from keyboard
7. nextLine(): Reads a line of text from keyboard
8. next() : Reads a single word from keyboard
Example:

import [Link].*;

class Demo

public static void main(String args[])

Scanner ob=new Scanner([Link]);

int n;

[Link] (“Enter an integer number”);

n=[Link]();

[Link] (“Number is “+n);

You might also like