Polymorphism Inheritance Encapsulation Abstraction Class Object Method

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

Module 1

1. Explain different Object-oriented concepts in java

1. Polymorphism
2. Inheritance
3. Encapsulation
4. Abstraction
5. Class
6. Object
7. Method

Polymorphism: Polymorphism refers to the ability of OOPs programming


languages to differentiate between entities with the same name efficiently. This is
done by Java with the help of the signature and declaration of these entities.
Inheritance: Inheritance is an important pillar of OOP(Object Oriented
Programming). It is the mechanism in java by which one class is allow to inherit
the features(fields and methods) of another class.
Encapsulation: Encapsulation is defined as the wrapping up of data under a single
unit. It is the mechanism that binds together code and the data it manipulates.
Another way to think about encapsulation is, it is a protective shield that prevents
the data from being accessed by the code outside this shield.
Abstraction: Data Abstraction is the property by virtue of which only the essential
details are displayed to the user.The trivial or the non-essentials units are not
displayed to the user. Ex: A car is viewed as a car rather than its individual
components.
Class: A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects of one type
Object: It is a basic unit of Object Oriented Programming and represents the real
life entities. A typical Java program creates many objects, which as you know,
interact by invoking methods
2. Explain different data types available in java and its sizes with a sample
example program.
3. Develop a java program to explain type conversions.
4. Explain selection statements in detail with example programs.
1. If
2. Switch
The example below uses the weekday number to calculate the weekday name:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
5. Develop a java program to search an element in the array.

6. What is an array? Explain in detail about array types in java with an example
program.

Array
1. An array is a collection of variables of homogeneous type that occupy
contiguous memory locations.
2. Arrays of any type can be created and may have one or more dimensions.
3. A specific element in an array is accessed by its index.
4. Arrays offer a convenient means of grouping related information. In Java all
arrays are dynamically allocated
Types of Arrays
1. One Dimensional
2. Two Dimensional
Module 2
1. Compare and contrast method overloading and overriding in java

Method Overloading:
Method Overloading is a Compile time polymorphism. In method overloading,
more than one method shares the same method name with different signature in
the class. In method overloading, return type can or can not be be same, but we
must have to change the parameter because in java, we can not achieve the
method overloading by changing only the return type of the method.
Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, derived
class provides the specific implementation of the method that is already provided
by the base class or parent class. In method overriding, return type must be
same or co-variant (return type may vary in same direction as the derived class).
Output :

2. Discuss the role of abstract class in java. Explain in detail with an example
program
3. Justify your answer, why java does not support Multiple Inheritance through
classes?

Why Java doesn’t support multiple inheritance?


C++ , Common lisp and few other languages supports multiple inheritance while
java doesn’t support it. Java doesn’t allow multiple inheritance to avoid the
ambiguity caused by it. One of the example of such problem is the diamond
problem that occurs in multiple inheritance.
Multiple Inheritance is a feature of object oriented concept, where a class can
inherit properties of more than one parent class. The problem occurs when there
exist methods with same signature in both the super classes and subclass. On
calling the method, the compiler cannot determine which class method to be
called and even on calling which class method gets the priority.
Consider the below Java code. It shows error.

// First Parent class


class Parent1
{
void fun()
{
System.out.println("Parent1");
}
}
// Second Parent Class
class Parent2
{
void fun()
{
System.out.println("Parent2");
}
}
// Error : Test is inheriting from multiple classes
class Test extends Parent1, Parent2
{
public static void main(String args[])
{
Test t = new Test();
t.fun();
}
}
Output : Compile Error
From the code, we see that, on calling the method fun() using Test object will
cause complications such as whether to call Parent1’s fun() or Parent2’s fun()
method.
1. The Diamond Problem:
The below Java program throws compiler error when run. Multiple inheritance
causes diamond problem when allowed in other languages like C++.
// A Grand parent class in diamond
class GrandParent
{
void fun()
{
System.out.println("Grandparent");
}
}
// First Parent class
class Parent1 extends GrandParent
{
void fun()
{
System.out.println("Parent1");
}
}
// Second Parent Class
class Parent2 extends GrandParent
{
void fun()
{
System.out.println("Parent2");
}
}
// Error : Test is inheriting from multiple classes
class Test extends Parent1, Parent2
{
public static void main(String args[])
{
Test t = new Test();
t.fun();
}
}
Output :
Error :
prog.java:31: error: '{' expected
class Test extends Parent1, Parent2
^
1 error

From the code, we see that: On calling the method fun() using Test object will
cause complications such as whether to call Parent1’s fun() or Child’s fun()
method.
Therefore, in order to avoid such complications Java does not support multiple
inheritance of classes.

4. Discuss the role of constructor and explain different types of constructors


available in java.
A constructor initializes an object when it is created. It has the same name as its
class and is syntactically similar to a method. However, constructors have no
explicit return type.
Typically, you will use a constructor to give initial values to the instance variables
defined by the class, or to perform any other start-up procedures required to
create a fully formed object.
All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member variables
to zero. However, once you define your own constructor, the default constructor
is no longer used.

Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}

Java allows two types of constructors namely −


• No argument Constructors
• Parameterized Constructors
No argument Constructors
As the name specifies the no argument constructors of Java does not accept any
parameters instead, using these constructors the instance variables of a method
will be initialized with fixed values for all objects.

Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}

You would call constructor to initialize objects as follows


public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}

This would produce the following result


100 100

Parameterized Constructors
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a
method, just declare them inside the parentheses after the constructor's name.

Example
Here is a simple example that uses a constructor −
// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows −
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}

This would produce the following result −


10 20
5. Explain different types of inheritances supported by Java with example
programs
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
6. Demonstrate the final keyword usage in java programming language
The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only. We will have detailed learning of these.
Let's first learn the basics of final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It
will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value
can never be changed.
2) Java final method
If you make any method as final, you cannot override it.
Module 3
1. Justify your answer how packages provide abstraction with an example
program
Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces. Packages are used for:
• Preventing naming conflicts. For example there can be two classes with
name Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
• Making searching/locating and usage of classes, interfaces, enumerations
and annotations easier
• Providing controlled access: protected and default have package level
access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access
specifier) is accessible by classes in the same package only.
• Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply
write an import class from existing packages and use it in our program. A
package is a container of a group of related classes where some of the classes
are accessible are exposed and others are kept for internal purpose.
We can reuse existing classes from the packages as many time as we need it in
our program.
How packages work?
Package names and directory structure are closely related. For example if a
package name is college.staff.cse, then there are three directories, college, staff
and cse such that cse is present in staff and staff is present college. Also, the
directory college is accessible through CLASSPATH variable, i.e., path of parent
directory of college is present in CLASSPATH. The idea is to make sure that
classes are easy to locate.
Package naming conventions : Packages are named in reverse order of
domain names, i.e., org.geeksforgeeks.practice. For example, in a college, the
recommended convention is college.tech.cse, college.tech.ee, college.art.history,
etc.

Adding a class to a Package : We can add more classes to a created package


by using package name at the top of the program and saving it in the package
directory. We need a new java file to define a public class, otherwise we can add
the new class to an existing .java file and recompile it.

Subpackages: Packages that are inside another package are the


subpackages. These are not imported by default, they have to imported
explicitly. Also, members of a subpackage have no access privileges, i.e., they
are considered as different package for protected and default access specifiers.
Example :
import java.util.*;

util is a subpackage created inside java package.

Accessing classes inside a package


Consider following two statements :
// import the Vector class from util package.
import java.util.vector;

// import all the classes from util package


import java.util.*;

First Statement is used to import Vector class from util package which is
contained inside java.
Second statement imports all the classes from util package.

Built-in Packages
These packages consist of a large number of classes which are a part of Java
API.Some of the commonly used built-in packages are:
1) java.lang:
2) java.io:
3) java.util:
4) java.applet:
5) java.awt:
6) java.net:

User-defined packages
These are the packages that are defined by the user. First we create a directory
myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package
names.
2. Develop a java program to implement multiple inheritance.
interface Backend {

// abstract class
public void connectServer();
}

class Frontend {

public void responsive(String str) {


System.out.println(str + " can also be used as frontend.");
}
}

// Language extends Frontend class


// Language implements Backend interface
class Language extends Frontend implements Backend {

String language = "Java";

// implement method of interface


public void connectServer() {
System.out.println(language + " can be used as backend language.");
}

public static void main(String[] args) {

// create object of Language class


Language java = new Language();

java.connectServer();

// call the inherited method of Frontend class


java.responsive(java.language);
}

Output
Java can be used as backend language.
Java can also be used as frontend.
3. Develop a java program for interface to find areas of different shapes.

Output :
Area of Rectangle is 200
Area of Circle is 706.85
4. Compare and contrast String and StringBuffer in java Programming Language
String String Buffer
It is an immutable class and its object It is a mutable classes which can be
can’t be modified after it is created used to do operation on string object
Methods are not synchronized All methods are synchronized in this
class.
It is fast Multiple thread can’t access at the
same time therefore it is slow
If a String is created using constructor Heap Space
or method then those strings will be
stored in Heap Memory as well as
SringConstantPool
5. What is String in java? Explain different methods in String Class with an
example Program.
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double
quotes:
In Java, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use double quotes to represent a string in Java
length() method
The length() method returns the length of a specified string.

Example
Return the number of characters in a string:
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(txt.length());

Output : 26

charAt() method
The charAt() method returns the character at the specified index in a string.

Example
Return the first character (0) of a string:
String myStr = "Hello";
char result = myStr.charAt(0);
System.out.println(result);

Output : H

trim() method
The trim() method removes whitespace from both ends of a string.

Example
String myStr = " Hello World! ";
System.out.println(myStr);
System.out.println(myStr.trim());

Output :
Hello World!
Hello World!

indexOf() method
The indexOf() method returns the position of the first occurrence of specified
character(s) in a string.
Example
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("planet"));

Output : 6

replace() method
The replace() method searches a string for a specified character, and returns a
new string where the specified character(s) are replaced.

Example
String myStr = "Hello";
System.out.println(myStr.replace('l', 'p'));

Output : Heppo

6. Write a program to illustrate the usage of the following methods of StringBuffer


class. Explain the output in each case. Delete(), deleteChatAt(), append(),
charAt().

delete()
The java.lang.StringBuffer.delete() method removes the characters in a
substring of this sequence. The substring begins at the specified start and
extends to the character at index end - 1 or to the end of the sequence if no such
character exists. If start is equal to end, no changes are made.
package com.tutorialspoint;
Example
import java.lang.*;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("Java lang package");
System.out.println("buffer = " + buff);
// deleting characters from index 4 to index 9
buff.delete(4, 9);
System.out.println("After deletion = " + buff);
}
}

Let us compile and run the above program, this will produce the following result −
buffer = Java lang package
After deletion = Java package

deletecharat()
The java.lang.StringBuffer.deleteCharAt() method removes the char at the
specified position in this sequence. This sequence is shortened by one char.
Example
package com.tutorialspoint;
import java.lang.*;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("Java lang package");
System.out.println("buffer = " + buff);
// deleting character from index 4 to index 9
buff.delete(4, 9);
System.out.println("After deletion = " + buff);
buff = new StringBuffer("amit");
System.out.println("buffer = " + buff);
// deleting character at index 2
buff.deleteCharAt(2);
System.out.println("After deletion = " + buff);
}
}

Let us compile and run the above program, this will produce the following result −
buffer = Java lang package
After deletion = Java package
buffer = amit
After deletion = amt

append()
This method updates the value of the object that invoked the method. The
method takes boolean, char, int, long, Strings, etc.
Example
public class Test {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Test");
sb.append(" String Buffer");
System.out.println(sb);
}
}

Output : Test String Buffer

charat()
The java.lang.StringBuffer.charAt() method returns the char value in this
sequence at the specified index. The first char value is at index 0, the next at
index 1, and so on, as in array indexing.
Example
package com.tutorialspoint;
import java.lang.*;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("Tutorials Point");
System.out.println("buffer = " + buff);
// returns the char at index 4
System.out.println("character = " + buff.charAt(4));
buff = new StringBuffer("amrood admin ");
System.out.println("buffer = " + buff);
// returns the char at index 6, whitespace gets printed here
System.out.println("character = " + buff.charAt(6));
}
}

Let us compile and run the above program, this will produce the following result −
buffer = Tutorials Point
character = r
buffer = amrood admin
character =
Module 4
1. With an example program illustrate user defined exception handling

// A Class that represents use-defined expception


class MyException extends Exception
{
}
// A Class that uses above MyException
public class setText
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
2. What are the uses of ‘throw’ and ‘throws’ clauses for exception handling?

Throw
The throw keyword in Java is used to explicitly throw an exception from a method
or any block of code. We can throw either checked or unchecked exception. The
throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance

Example:
throw new ArithmeticException("/ by zero");

But this exception i.e, Instance must be of type Throwable or a subclass of


Throwable. For example Exception is a sub-class of Throwable and user defined
exceptions typically extend Exception class. Unlike C++, data types such as int,
char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement
is executed and the nearest enclosing try block is checked to see if it has a
catch statement that matches the type of exception. If it finds a match, controlled
is transferred to that statement otherwise next enclosing try block is checked and
so on. If no matching catch is found then the default exception handler will halt
the program.

Example
// Java program that demonstrates the use of throw
class Test
{
public static void main(String[] args)
{
System.out.println(1/0);
}
}

Output : Exception in thread "main" java.lang.ArithmeticException: / by zero


Throws
throws is a keyword in Java which is used in the signature of method to indicate
that this method might throw one of the listed type exceptions. The caller to these
methods has to handle the exception using a try-catch block.
Syntax:
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the
exceptions which a method might throw.

In a program, if there is a chance of raising an exception then compiler always


warn us about it and compulsorily we should handle that checked exception,
Otherwise we will get compile time error saying unreported exception XXX
must be caught or declared to be thrown. To prevent this compile time error
we can handle the exception in two ways:
1. By using try catch
2. By using throws keyword
We can use throws keyword to delegate the responsibility of exception handling
to the caller (It may be a method or JVM) then caller method is responsible to
handle that exception.

Example
// Java program to illustrate error in case
// of unhandled exception
class tst
{
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}

Output : error: unreported exception InterruptedException; must be caught or


declared to be thrown
Explanation: In the above program, we are getting compile time error because
there is a chance of exception if the main thread is going to sleep, other threads
get the chance to execute main() method which will cause InterruptedException.

// Java program to illustrate throws


class tst
{
public static void main(String[] args)throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}

Output : Hello Geeks


Explanation: In the above program, by using throws keyword we handled the
InterruptedException and we will get the output as Hello Geeks
Important points to remember about throws keyword:
• throws keyword is required only for checked exception and usage of throws
keyword for unchecked exception is meaningless.
• throws keyword is required only to convince compiler and usage of throws
keyword does not prevent abnormal termination of program.
• By the help of throws keyword we can provide information to the caller of
the method about the exception.

3. What is a Thread? Explain different ways of creating thread with example


programs

Java Threads
Threads allows a program to operate more efficiently by doing multiple things at
the same time.
Threads can be used to perform complicated tasks in the background without
interrupting the main program.
A thread is a:
• Facility to allow multiple activities within a single process
• Referred as lightweight process
• A thread is a series of executed statements
• Each thread has its own program counter, stack and local variables
• A thread is a nested sequence of method calls
• Its shares memory, files and per-process state

Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:

Extend Syntax
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}

Another way to create a thread is to implement the Runnable interface:

Implement Syntax
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}

Running Threads
If the class extends the Thread class, the thread can be run by creating an
instance of the class and call its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}

Output
This code is outside of the thread
This code is running in a thread
If the class implements the Runnable interface, the thread can be run by passing
an instance of the class to a Thread object's constructor and then calling the
thread's start() method:

Implement Example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}

Output
This code is outside of the thread
This code is running in a thread
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot
extend any other class, but by implementing the Runnable interface, it is possible
to extend from another class as well, like: class MyClass extends OtherClass
implements Runnable.
4. What is Daemon Thread? Demonstrate Daemon thread with an example
Daemon thread is a low priority thread (in context of JVM) that runs in
background to perform tasks such as garbage collection (gc) etc., they do not
prevent the JVM from exiting (even if the daemon thread itself is running) when
all the user threads (non-daemon threads) finish their execution. JVM terminates
itself when all user threads (non-daemon threads) finish their execution, JVM
does not care whether Daemon thread is running or not, if JVM finds running
daemon thread (upon completion of user threads), it terminates the thread and
after that shutdown itself.

Daemon thread examples


Example 1: DaemonThreadExample1.java
This example is to demonstrate the usage of setDaemon() and isDaemon()
method.
public class DaemonThreadExample1 extends Thread{
public void run(){
// Checking whether the thread is Daemon or not
if(Thread.currentThread().isDaemon()){
System.out.println("Daemon thread executing");
}
else{
System.out.println("user(normal) thread executing");
}
}
public static void main(String[] args){
/* Creating two threads: by default they are
* user threads (non-daemon threads)
*/
DaemonThreadExample1 t1=new DaemonThreadExample1();
DaemonThreadExample1 t2=new DaemonThreadExample1();

//Making user thread t1 to Daemon


t1.setDaemon(true);
//starting both the threads
t1.start();
t2.start();
}
}

Output:
Daemon thread executing
user(normal) thread executing
Example 2: DaemonThreadEx2.java
If you call the setDaemon() method after starting the thread (start() method), it
would throw IllegalThreadStateException. This clearly means that you can call
setDaemon() method only before starting a thread.
public class DaemonThreadEx2 extends Thread {
public void run(){
System.out.println("Thread is running");
}
public static void main(String[] args){
DaemonThreadEx2 t1=new DaemonThreadEx2();
t1.start();
// It will throw IllegalThreadStateException
t1.setDaemon(true);
}
}

Output:
Exception in thread "main" Thread is running
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at beginnersbook.com.DaemonThreadEx2.main(DaemonThreadEx2.java:13)

5. With an example, demonstrate the concept of thread synchronization.


When we start two or more threads within a program, there may be a situation
when multiple threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues. For example, if multiple
threads try to write within a same file then they may corrupt the data because
one of the threads can override data or while one thread is opening the same file
at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure
that only one thread can access the resource at a given point in time. This is
implemented using a concept called monitors. Each object in Java is associated
with a monitor, which a thread can lock or unlock. Only one thread at a time may
hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared
resources within this block. Following is the general form of the synchronized
statement −
Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}

Multithreading Example with Synchronization


Here is the example which prints counter value in sequence and every time we
run it, it produces the same result.
Example
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd) {
threadName = name;
PD = pd;
}

public void run() {


synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces the same result every time you run this program −

Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

6. What are the different ways to handle exceptions? Explain

How to Handle an Exception


Java provides two different options to handle an exception. You can either use
the try-catch-finally approach to handle all kinds of exceptions. Or you can use
the try-with-resource approach which allows an easier cleanup process for
resources.

Java try and catch


The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
The try and catch keywords come in pairs:

Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
If an error occurs, we can use try...catch to catch the error and execute some
code to handle it:

Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

The output will be:


Something went wrong.

Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:

Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

The output will be:


Something went wrong.
The 'try catch' is finished.
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many
exception types available in Java: ArithmeticException, FileNotFoundException,
ArrayIndexOutOfBoundsException, SecurityException, etc:

Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or
older, print "Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}

The output will be:


Exception in thread "main" java.lang.ArithmeticException: Access denied - You
must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

If age was 20, you would not get an exception:

Example
checkAge(20);

The output will be:


Access granted - You are old enough!
Module 5
1. Write a Java program to write data into a text file using FileWriter.

import java.io.FileWriter; // Import the FileWriter class


import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Output : Successfully wrote to the file.

2. Demonstrate to read data (BufferReader) from a file and write data into
another text file using BufferWriter

Java BufferedReader class declaration


Let's see the declaration for Java.io.BufferedReader class:
public class BufferedReader extends Reader
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.

Output:
Welcome to javaTpoint.

Java BufferedWriter Class declaration


Let's see the declaration for Java.io.BufferedWriter class:
1. public class BufferedWriter extends Writer
Output : success
testout.txt : Welcome to javaTpoint

3. Write a java program to write data into a text file using FileWriter.

Java FileWriter class declaration


Let's see the declaration for Java.io.FileWriter class:
1. public class FileWriter extends OutputStreamWriter
Output : Success...
testout.txt : Welcome to javaTpoint.
4. Explain Character Streams in detail.
In Java, characters are stored using Unicode conventions (Refer this for details).
Character stream automatically allows us to read/write data character by
character. For example FileReader and FileWriter are character streams used to
read from source and write to destination.
BufferedReader
Java BufferedReader class is used to read the text from a character-based input
stream. It can be used to read data line by line by readLine() method. It makes
the performance fast. It inherits Reader class.

BufferedWriter
Java BufferedWriter class is used to provide buffering for Writer instances. It
makes the performance fast. It inherits Writer class. The buffering characters are
used for providing the efficient writing of single arrays, characters, and strings.

FileWriter
Java FileWriter class is used to write character-oriented data to a file. It is
character-oriented class which is used for file handling in java. Unlike
FileOutputStream class, you don't need to convert string into byte array because
it provides method to write string directly.

FileReader
Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class. It is character-oriented class which is used for
file handling in java.
StringWriter
Java StringWriter class is a character stream that collects output from string
buffer, which can be used to construct a string. The StringWriter class inherits the
Writer class. In StringWriter class, system resources like network sockets and
files are not used, therefore closing the StringWriter is not necessary.

StringReader
Java StringReader class is a character stream with string as a source. It takes an
input string and changes it into character stream. It inherits Reader class. In
StringReader class, system resources like network sockets and files are not
used, therefore closing the StringReader is not necessary.

InputStreamReader
An InputStreamReader is a bridge from byte streams to character streams: It
reads bytes and decodes them into characters using a specified charset. The
charset that it uses may be specified by name or may be given explicitly, or the
platform's default charset may be accepted.

OutputStreamWriter
OutputStreamWriter is a class which is used to convert character stream to byte
stream, the characters are encoded into byte using a specified charset. write()
method calls the encoding converter which converts the character into bytes. The
resulting bytes are then accumulated in a buffer before being written into the
underlying output stream. The characters passed to write() methods are not
buffered. We optimize the performance of OutputStreamWriter by using it with in
a BufferedWriter so that to avoid frequent converter invocation.

CharArrayReader
The CharArrayReader is composed of two words: CharArray and Reader. The
CharArrayReader class is used to read character array as a reader (stream). It
inherits Reader class.

CharArrayWriter
The CharArrayWriter class can be used to write common data to multiple files.
This class inherits Writer class. Its buffer automatically grows when data is
written in this stream. Calling the close() method on this object has no effect.
5. What are the methods available in the Character Streams? Discuss
6. What are the methods available in the PrintWriter Class? Discuss.

You might also like