0% found this document useful (0 votes)
77 views40 pages

Unit 1

The document summarizes key aspects of Java architecture and programming. It discusses that Java architecture includes three main components: the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). The JVM executes Java bytecode by converting it to machine code. The JRE provides the runtime environment for the JVM. And the JDK is the development environment and includes tools needed for Java programming like a compiler and documentation generator.

Uploaded by

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

Unit 1

The document summarizes key aspects of Java architecture and programming. It discusses that Java architecture includes three main components: the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). The JVM executes Java bytecode by converting it to machine code. The JRE provides the runtime environment for the JVM. And the JDK is the development environment and includes tools needed for Java programming like a compiler and documentation generator.

Uploaded by

Prabesh Karki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Unit 1: Programming in Java

PART 1

Java Architecture:
Java architecture refers to the overall design and structure of the Java programming
language, its runtime environment, and the tools used to develop Java applications.
Java architecture has three major components: JRE, JDK and JVM. Java Architecture
explains each and every step on how java programs are compiled and executed. The
Java architecture is built on the principles of platform independence, security, and
reliability.

Figure: Java Architecture

Components of Java Architecture

Java architecture includes three major components. They are:


1. Java Virtual Machine (JVM)
2. Java Runtime Environment (JRE)
3. Java Development Kit (JDK)
1. Java Virtual Machine (JVM)
When a Java program is compiled by compiler, it is translated into an intermediate
form called bytecode by java compiler contained by JDK. The bytecode is platform-
independent, meaning that it can be executed on any hardware or operating system
that has a JVM installed. This bytecode is not an executable code for target machine
but rather it is object code for JVM.
Java has an amazing feature, “WORA” (Write Once, Run Anywhere). We may write our
code once and use it anywhere, on any operating system, according to the feature.
Because of the Java Virtual Machine (JVM), our Java program can execute on any
platform. It is a Java platform component that provides us with a platform through
which to run Java programs. The primary function of the JVM is to translate bytecode
to machine code. The JVM executes the byte codes by
interpreting the bytecode and converting it into
machine code that can be executed by the
underlying hardware.
Primarily, the byte codes are generated by Java JVM
compiler in the form of class files (.class). Then JVM
class loader will load these class files for execution.
Then the JVM byte code verifier will check the byte
code and ensures the following:
 The code follows JVM specifications.
 There is no unauthorized access to memory.
 The code doesn’t cause any stack overflows.
 There is no illegal data conversions in code such as float to object references.
Once the code is verified, JVM will convert the byte code into machine code. JVM may
also use JIT compiler which will help JVM to execute the program faster as JIT compiler
will cache the code for future reuse. Finally, the hardware specific machine code is
created and JVM loads and verifies the machine code in memory. The machine code is
specific to the hardware and operating system, and the JVM takes care of generating
the appropriate machine code for the target system. The machine code generated by
the Java Virtual Machine (JVM) is executed by the underlying hardware and operating
system of the computer on which the Java program is running.
The JVM also provides other services, such as memory management, security, and
class loading. It is responsible for managing the execution of Java programs and
ensuring that they run efficiently and securely.
Q. JVM provides a layer of abstraction between the Java program and the underlying
hardware and operating system. Elaborate this statement.
Q. How does JVM allow Java programs to be executed on a wide range of platforms
without requiring any changes to the code? Explain.
2. Java Runtime Environment (JRE)
It provides an environment in which Java programs are executed. JRE refers to a
runtime environment in which bytecode can be executed. JRE provides the runtime
environment for JVM to execute (i.e. to convert bytecode to machine code). It
implements the JVM and provides all the class libraries and other support files that JVM
uses at runtime. So JRE is a software package that contains what is required to run a
program. Basically, it’s an implementation of the JVM which physically exists.
Q. How does JRE helps in byte code to machine code conversion? Explain.
3. Java Development Kit (JDK)
It is the tool necessary to: Compile, Document and Package Java programs. The JDK
completely includes JRE (which contains tools for programmers) and all other tools
needed in Java development that includes an interpreter/loader, a compiler (javac), an
archiver (jar), a documentation generator and so on. In short, it contains JRE +
development tools.
It is a software development environment used in the development of Java applications
and applets. Java Development Kit holds JRE, a compiler, an interpreter or loader, and
several development tools in it. 

*Java architecture can be summarized by following steps.


 Java compiler converts java source code into bytecode.
 After that JVM converts the byte code into machine code.
 The machine code is then executed by machine under the supervision of
Operating system.

Java program execution process: (compiling and running java program)


The execution of a Java program involves several steps, which can be summarized as
follows:
1. The first step in executing a Java program is to write the code using a text editor
or an Integrated Development Environment (IDE).

2. The Java code is compiled into bytecode using the Java compiler (javac). The
bytecode is a platform-independent format that can be executed on any system
that has a Java Virtual Machine (JVM) installed. The bytecode will be stored in
class files (.class) format.

3. The JVM class loader loads the bytecode class files into memory and verifies that
it is a valid Java program. The JVM byte code verifier will check the byte code
and ensures the following:
 The code follows JVM specifications.
 There is no unauthorized access to memory.
 The code doesn’t cause any stack overflows.
 There is no illegal data conversions in code such as float to object references.

4. Once the code is verified, JVM will convert the byte code into machine code. The
JVM also performs various tasks such as memory management and garbage
collection.

5. JVM may also use JIT compiler which will help JVM to execute the program faster
as JIT compiler will cache the code for future reuse.

6. Finally, the hardware specific machine code is created and JVM loads and verifies
the machine code in memory. The machine code is specific to the hardware and
operating system, and the JVM takes care of generating the appropriate machine
code for the target system. The machine code generated by the Java Virtual
Machine (JVM) is executed by the underlying hardware and operating system of
the computer on which the Java program is running.

Java Buzzwords
The features of Java are also known as Java buzzwords. The list of major Java
feature or buzzwords are given below:
1. Simple: Java is designed to be easy to learn and use, with a syntax that is
similar to other popular programming languages such as C++ and C#.

2. Object-oriented: Java is an object-oriented programming language, which


means that it is based on the concept of objects that can have properties and
methods.

3. Portable: Java code is portable, which means that it can be moved easily from
one platform to another (one OS or hardware architecture to another), as long
as there is a JVM available on each platform.

4. Platform independent: Java programs can run on any platform that has a Java
Virtual Machine (JVM) installed, which means that a program written on one
platform can be run on any other platform without modification. When we say
that Java is platform-independent, it means that it is not tied to a particular
operating system or hardware architecture. This is because Java programs are
compiled into bytecode, which is then interpreted by the Java Virtual Machine
(JVM) at runtime.

5. Secured: Java has built-in security features, such as automatic memory


management, that help to prevent common security vulnerabilities such as
buffer overflows and memory leaks.

6. Robust: Java is designed to be a robust language, with features such as


automatic memory management, exception handling, and type checking, which
help to prevent common programming errors and ensure that code runs
smoothly.

7. Architecture neutral: Java is an architecture-neutral language, which means


that Java programs can run on any architecture that has a Java Virtual Machine
(JVM) installed. This makes Java code highly portable and allows it to be run on
a wide range of platforms, from desktop computers to embedded devices.

8. Interpreted: Java code is compiled into bytecode, which can be interpreted by


the JVM at runtime. This allows Java programs to be written once and run
anywhere, without the need for recompilation on different platforms.

9. High performance: Java's high-performance virtual machine, known as the


HotSpot JVM, is designed to optimize the performance of Java applications.

10. Multithreaded: Java supports multithreading, which allows multiple


threads of execution to run concurrently within a single program.

11. Distributed: Java has built-in support for distributed computing, making
it easy to create applications that run across multiple machines on a network.

12. Dynamic: Java supports dynamic class loading, which allows new classes
to be loaded and integrated into a program at runtime. This feature is useful for
creating flexible, modular programs that can be extended and customized as
needed.

Path and Classpath variables


Why do you set a java path?
The path and classpath variables are the most important environment variable of the
Java which are used to locate the files used during java program execution.
We do not need to set path and classpath variables to compile and run java program
while using IDE like Eclipse. Environment variables are required to compile and run
java program using CMD.
When you save your file in the java directory i.e. where java is installed, it is not
necessary to set a path. But if you are saving your file outside the directory, it is fairly
necessary to set the path beforehand.

A. Path variable in Java:


The path variable is a mediator between developer and the operating system which is
used by the operating system to find executable files when you enter a command in
the command line in CMD. For example, if you enter "java" in the command line, the
operating system uses the path variable to find the Java executable file. Once you
installed Java on your machine, it is required to set the PATH environment variable to
conveniently run the executable files (javac.exe, java.exe, javadoc.exe, and so on)
from any directory without having to type the full path of the command, such as: C:\
javac TestClass.java. Path variable is used to set the path for all Java executable files
or Java software tools like javac.exe, java.exe, javadoc.exe, and so on.

B. Classpath Variables:

Classpath is system environment variable which acts as mediator between developer


and compiler and JVM. It is used by the Java compiler and JVM to determine the
location of required class files. classpath variable is used to set the path for java
classes files that developer develops. The classpath is a parameter that tells the Java
Virtual Machine (JVM) where to find user-defined classes and packages.
The classpath can be set using the "CLASSPATH" environment variable or using the "-
classpath" option when starting the JVM. For example, to set the classpath to include
the "myclasses" directory and the "mylib.jar" JAR file, you can use the following
command:

In this example, "MyClass" is the name of the main class that is being executed.

Sample java program


A Java program typically consists of the following basic features:
 Class declaration: Every Java program starts with a class declaration. Every
single java program is enclosed inside a class. And the file name of that
program is same as enclosing class name of that program. The class
declaration defines the properties and behaviors of the program.
 Main method: Every Java program must have a main method. It is the entry
point of the program, and it is executed when the program is run.
 Variables: Java is a strongly-typed language, which means that every variable
must be declared with a specific data type. Variables are used to store data
values that can be used in the program.
Here is an example Java program “Sample.java”:
import java.*;

public class Sample


{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Note:
Save this file as Sample.java
To compile: javac Sample.java (in CMD)
To Execute: java Sample (in CMD)
Output: Hello World
How to get console user input in Java?
Java Scanner class allows the user to take input from the console. It belongs to
java.util package.
Syntax: Scanner sc = new Scanner(System.in);
Ex: import java.util.*;
class UserInputDemo
{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
System.out.print("Enter a string:");
String str=s.nextLine(); //reads string
System.out.print(“You have entered:” +str);
}
}

PART 2

Arrays
Q. A non-empty array A of length n is called on array of all possibilities if it contains all
numbers between 0 and A.length-1 inclusive. Write a method named isAllPossibilities
that accepts an integer array and returns 1 if the array is an array of all possiblities,
otherwise it returns 0. (5)[2077]

Q. An array is called balanced if it's even numbered elements (a[0], a[2], etc.) are
even and its odd numbered elements (a[1], a[3],etc.) are Odd. Write a function named
is Balanced that accepts an array of integers and returns 1 if the array is balanced
otherwise it returns 0. [5][2075]

Java array is a data structure used to store a fixed-size sequence of elements of the
same data type. In Java, arrays are indexed. The first element is indexed as 0, the last
element as n-1, and so on.
Arrays are classified into two types:
 Single dimensional Array
 Multidimensional Array

1. Single Dimensional Array

It is also called 1-D array. To declare an array in Java, you need to specify the data
type of the elements that the array will hold and the size of the array. For example, to
declare an array of integers that can hold five elements, you can use the following
code:
int[] numbers = new int[5];
In this code, the ‘int’ keyword specifies the data type of the elements that the array
will hold, and the ‘5’ specifies the size of the array. The ‘new’ keyword is used to
allocate memory for the array.
You can also initialize the elements of an array when you declare it, like this:
int[] numbers = {1, 2, 3, 4, 5};
This code creates an array of integers with five elements and initializes them to the
values 1, 2, 3, 4, and 5.
To access the elements of 1-D array, you can use the array index, which starts at
zero. For example, to access the first element of the numbers array, you can use the
following code:
int firstNumber = numbers[0];
In this code, numbers[0] accesses the first element of the numbers array.
You can also use loops to iterate over the elements of an array. For example, to print
all the elements of the numbers array, you can use the following code:
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
In this code, numbers.length returns the size of the numbers array, and the for loop
iterates over the array elements using the index variable i.

2. Multidimensional Array

Java arrays can be multidimensional, meaning that they can hold more than one arrays
as elements. The multidimensional array with two arrays as elements is 2-D array and
that with three arrays as elements is 3-D array. In Java, multidimensional arrays are
represented as arrays of arrays, where each element of the array is another array.
Two-dimensional array
It is a way to represent data in a tabular or matrix format, where data is arranged in
rows and columns.
To declare a two-dimensional array in Java, you need to specify the number of rows
and columns. For example, to declare a two-dimensional array of integers with 3 rows
and 4 columns, you can use the following code:
int[][] matrix = new int[3][4];
In this code, matrix is a two-dimensional array with 3 rows and 4 columns.
You can initialize the elements of this array using a nested loop.
For example, to initialize the elements of the matrix array with random integers
between 0 and 9, you can use the following code:
import java.util.Random;
int[][] matrix = new int[3][4];
Random random = new Random();
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
matrix[i][j] = random.nextInt(10);
}
}
In this code, random is a java.util.Random object that generates random integers
between 0 and 9. The nested loops iterate over each element of the matrix array and
assign it a random integer value.
For example, to initialize the elements of the matrix array manually by entering by
user, you can use the following code:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int[][] matrix = new int[3][4];
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
System.out.print("Enter element [" + i + "][" + j + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
In this code, scanner is a java.util.Scanner object that reads input from the user. The
nested loops iterate over each element of the matrix array and prompt the user to
enter a value for each element. The nextInt() method of the Scanner class reads the
next integer value entered by the user and assigns it to the current element of the
array.
To access the elements of a two-dimensional array in Java, you need to use two
indices, one for the row and one for the column. For example, to access the element in
the second row and third column of the matrix array, you can use the following code:
int element = matrix[1][2];
In this code, matrix[1][2] accesses the element in the second row and third column of
the matrix array.

foreach in Java
foreach loop provides an alternative approach to traverse the array or collection in
Java. The advantage is that it eliminates the possibility of bugs and makes code more
readable. It traverses each element one by one. The drawback is that, it cannot
traverse elements in reverse order and cannot have option to skip any element
because it does not work on an index basis. But, it is recommended to use it because it
makes the code readable.
Syntax: for(data_type variable_name: array_name)
{
//body of foreach loop
}
Example:
class forEachDemo{
public static void main(String args[]){
int a[]={10, 11, 12, 13};
for(int i:a)
{
System.out.println(i);
}
}
}
Classes and objects
Q. Define class. How do you create a class in Java? Differentiate class with interface.
[5][2076]

Class is a blueprint of real world objects that specifies what data and what methods will
be included in objects of the class. The class is a description group of objects having
similar properties. A class is also called user defined data type or programmers defines
data type because we can define new data types according to our needs by using
classes.
Syntax: class <class_name>{
field;
method;
}
Objects are instances of classes. We can say that objects are variables of class type.
Memory for instance variables are not allocated at the time of class declaration rather
at the time of object creation. Thus, we can say that objects have physical
existence and classes are only concepts.

Creating objects: It can be done using the new operator. The new operator
dynamically allocates (that is, allocates at run time) memory for an object and returns
a reference to it. This reference is the address in memory, of the object allocated by
new. This reference is then stored in the variable. Thus, in Java, all class objects must
be dynamically allocated.
Syntax: Class_name object_varibale = new Class_name();
Ex: Box mybox = new Box();
Simple example of class and objects:
public class Car
{
String model;
int year;
public Car (String model, int year) //Constructor
{
this.model = model;
this.year=year;
}
public void info()
{
System.out.println("The model of car manufactured in " + year + " "+" is"
+
model);
}

public static void main(String[] args)


{
Car myCar = new Car("Toyota", 2021);
myCar.info();
}
}

Types of modifiers
There are two types of modifier keywords in Java. They are:
1. Access modifiers: private, default, protected and public
2. Non-access modifiers: static, final, abstract, synchronized and volatile.

Access modifiers in Java


Access Modifiers in java specifies the visibility and accessibility of class, methods and
member variables. It also set access levels for classes, variables, methods and
constructors. There are four types of access modifiers in Java. They are:
1. private: The methods, classes, constructors, and variables that are declared
private are only accessible within the encapsulating class of java program. It
cannot be accessed outside the class. Using private access modifier is the main
way that an object encapsulates itself and hides data from the outside world.

2. default: In default access modifier, no keyword is used to define an access


modifier for a class, field, method etc. The access level of default access modifier
is only within the package but not outside of the package (i.e. all the class of
same package). If no access level is specified to methods, classes, constructors,
and variables then, it will be the default.

3. protected: Variables, methods and constructors which are declared protected


inside a certain class in one package can be accessed with in that package and
outside the package but only by the child classes in other packages. It cannot be
accessed from outside the package if a child class is not created there. The
protected access modifier is inapplicable to classes and interfaces.

4. public: A class, variable, methods, constructor, interface which are declared


public can be accessed from everywhere i.e. any other class and packages. It
can be accessed within the class and package and, outside the class and
package.
Method Overloading
In java, we can define more than one method with the same name but either with
different number of parameters or with different types of parameters to make them
unique. This technique is called method overloading. Polymorphism is supported by
Java through method overloading. Method overloading helps to increase the readability
of the program. In method overloading the return type of the method does not matter.
The two way to overload the method in java are:
 By changing the number of parameters.
 By changing the type of parameter.
Example:
public class method_overloading
{
static int sum(int a, int b){
return a+b;
}

static int sum(int a, int b,int c){ //changing the number of parameter
return a+b+c;
}

static float sub(float x, float y){


return x-y;
}

static double sub(double x,double y){ //changing the type of parameter


return x-y;
}

public static void main(String args[]) {


System.out.println(sum(4,5));
System.out.println(sum(7,10,11));
System.out.println(sub(10.4f,2.5));
System.out.println(sub(8.9,4.5));
}
}

Inheritance
Q. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple
inheritance with suitable example.(1+2+7)[2074]

Inheritance is a mechanism in which one class inherits the properties and features of
another class. Inheritance represents IS-A relationship. In inheritance, a new class
called child class or sub class is created based on existing classes (called parent class)
in order to inherit the existing classes’ features and properties. In the new class, new
methods and fields can also be added. With the use of inheritance, the information is
made manageable in a hierarchical order. A class that is derived from another class is
Subclass. The class from where a subclass inherits the features is called
superclass/base class/parent class.
Inheritance uses the concept of the code reusability. It allows to use the field
and method of the existing class in the new class. Reusing the existing code saves time
and money and increases the program’s reliability.
Syntax for deriving a subclass from existing class:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword is used to inherit the properties of class. The meaning of
“extends” is to increase the functionality.

Types of inheritance

1. Single inheritance
2. Multiple Inheritance
3. Hierarchical inheritance
4. Multilevel inheritance

1. Single inheritance:

In single inheritance, a class is derived from only one existing class.


2. Multiple inheritance

In multiple inheritance, a class is derived from more than one existing classes. Java
does not support. The multiple inheritance. In Java, multiple inheritance
can be implemented by interface.

3. Hierarchical inheritance

In hierarchical inheritance, two or more classes inherit the properties of one existing
class. Two or more classes are derived from one base class.

Example:
4. Multi-level inheritance

The mechanism of deriving a class from another subclass is known as multilevel


inheritance. The process can be extended to an arbitrary number of levels.
Method Overriding
The process of redefining the inherited method of the super or parent class in the
derived or child class is called method overriding. It is used to provide the runtime
polymorphism. Method overriding is a feature in Java that allows a subclass to provide
its own implementation (i.e. redefined body part) of a method already defined in its
superclass. The method in the subclass must have the same name, return type, access
modifier and parameters as the method in the superclass.
Here are the rules for using method overriding in Java:
 The method in the subclass must have the same method signature (i.e., name,
return type, and parameter list) as the method in the superclass.
 The access level or modifier of the method in the subclass must be the same or
more accessible than the access level of the method in the superclass. The
method in the subclass cannot be more restrictive than the method in the
superclass. For example, if the method in the superclass is declared as public,
the method in the subclass cannot be declared as private or protected.
 The @Override annotation is used in Java to indicate that a method in a class is
overridden form of a method with the same signature in a superclass or
interface. However, using the @Override annotation in Java is not
compulsory, it’s optional and using it can help prevent errors and improve
code readability, as it makes it clear that a method is intended to override a
method in a superclass or interface, and the compiler can check if the method
signature matches. If the method signature doesn't match, the compiler will
generate an error, which can help catch coding mistakes early on.
Example:
class Plant
{
void color(){
System.out.println(“It is green color”);
}
}
class Flower extends Plant
{
@Override
void color(){
System.out.println(“It is yellow color flower”);
}

public static void main(String args[])


{
Flower obj = new Flower();
obj.color();
}
}

Difference between Method overloading and method overriding

Method Overloading Method Overriding

It refers to having same method, same


It refers to having the same method
signature but different class connected
but different signatures.
through inheritance.

It is used to increase readability of It is used to provide specific


program. implementation of method.

Parameter must be different. Parameter must be same

It is example of compile time


It is example of runtime polymorphism.
polymorphism.

It occurs in two classes that have IS-A


It is performed within class.
relationship.

Interface
Q. Differentiate class with interface.[5][2076]
Q. Describe the responsibility of Serializable interface.
Q. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple
inheritance with suitable example.(1+2+7)[2074]
Q. Why multiple inheritance is not allowed in Java using classes? Give an example.(5)
[2077]

In java, interface is a way to add the abstraction level in java programming. An


interface is an abstract type which acts as a blueprint for a class that implements that
interface. In general terms, an interface can be defined as a container that stores the
signatures or declarations of the set of methods to be implemented in the code
segment. The set of methods declared by interface are implemented by a class
implementing the interface.
 Interfaces are syntactically similar to classes. The interface keyword is used to
declare an interface, followed by the interface name and a set of curly braces
which contains interface body.
 Interface body contains methods signatures (methods declarations) and constant
variables. But unlike class, an interface has only the signature of methods (i.e.,
method name, return type, and parameter types) but no implementation (i.e.
methods are declared without any body).
 All interface methods are public by default and cannot be modified. Therefore,
access modifiers such as public or private cannot be used to restrict access to the
methods.
 There is no need to write abstract keyword before declaring methods in an
interface because an interface is implicitly abstract.
 The interface does not have instance variables but can have constant variables.
These interface variables are implicitly public, static, and final. So, any
variable declared inside the interface should be a constant.
 An interface can extend multiple interfaces using the extends keyword, which
means that an interface can inherit from one or more other interfaces.
 An interface cannot contain a constructor (as it cannot be used to create objects).
 In java, one or more class implements the interface. Any number of classes can
implement an interface. Also, one class can implement any number of interfaces.
The interface implementing class uses implement keyword to requires a class to
implement interface. A class implements an interface by providing implementations
for all the methods declared in the interface. Class should override all the abstract
methods declared in the interface.
 Note: A class can extend only one class but not more than one classes which is
because java does not support multiple inheritance. But, an interface can extend
from one or many interfaces. Similarly, one class can extend any number of
interfaces. This is how we can achieve multiple inheritance in java using interfaces.
Example:
public class Example{ public class Rectangle implements
Shape
public interface Shape {
{ private double length;
double getArea(); private double width;
double getPerimeter(); public Rectangle(double length,
} double width)
{
public class Circle this.length = length;
implements Shape this.width = width;
{ }
private double radius;
public Circle(double @Override
radius) public double getArea()
{ {
this.radius = radius; return length * width;
} }

@Override @Override
public double getArea() public double getPerimeter()
{ {
return Math.PI * return 2 * (length + width);
radius * radius; }
} }

@Override public static void main(String[] args)


public double {
getPerimeter() { Circle ci=new Circle(3);
return 2 * Math.PI * Rectangle re=new Rectangle(5,
radius; 2);
} ci.getArea();
} ci.getPerimeter();
re.getArea();
re.getPerimeter();
}
}

Reasons to use interface:


 To add abstractions in java programs.
 To achieve multiple inheritance.
 To achieve loose coupling.

Q. Why Java doesn’t support multiple inheritance? How can we achieve


multiple inheritance in Java using interfaces?

C++, and commonly other languages supports multiple inheritance using purely only
the classes. While java doesn’t support it. Java doesn’t allow multiple inheritance
because it can lead to several ambiguity problems. One of such problem is the
“diamond problem” that occurs during multiple inheritance in Java. So, to avoid such
problem Java does not support multiple inheritance.
Diamond problem
The diamond problem arises when a class inherits from two or more classes that have
a common superclass and those two inherited classes also have a common method
with the same signature.
We will discuss this problem with the help of the diagram given
alongside. The figure shows multiple inheritance because Class
D extends both classes B & C. And, classes B and C both are
derived from class A.
Now let’s assume we have a method in class A and class B &C
overrides that method in their own way. Now here, since D is
extending both B & C, so, if D wants to access that method then
D will be unsure or undecidable which method to call (either the
overridden method in B or the overridden method in C). This is the Ambiguity problem
which can cause the compiler to be unable to decide which method implementation to
use. That’s the main reason why Java doesn’t support multiple inheritance.
Example of diamond problem
class C extends A
class A {
{ public void foo() {
public void foo() { System.out.println("C.foo()");
}
System.out.println("A.foo()"); }
} class D extends B, C // compile error: can’t inherit
} from multiple classes
{
class B extends A public static void main(String[] args)
{ {
public void foo() { D d = new D();
d.foo(); // ambiguous call to foo() method
System.out.println("B.foo()"); }
} }
}
In this example, classes B and C both inherit from class A and override the foo()
method. Class D tries to inherit from both classes B and C, but this is not
allowed in Java as it does not support multiple inheritance and here if we try
to compile this code, compiler throws an error: "cannot inherit from multiple
classes".
Way of achieving multiple inheritance in java:
In Java, multiple inheritance can be achieved through interfaces.
In Java, a class can extend only one class but not more than one classes which is
because java does not support multiple inheritance. But, an interface can extend from
one or many interfaces. Similarly, one class can extend any number of interfaces. This
is how we can achieve multiple inheritance in java using interfaces.
Example:
interface A public class Main {
{ public static void main(String[]
void methodA(); args) {
} MyClass myClass = new
interface B MyClass();
{ myClass.methodA();
void methodB(); myClass.methodB();
} }
class MyClass implements A, B }
{
public void methodA() {
System.out.println("methodA()
called");
}
public void methodB() {
System.out.println("methodB()
called");
}
}
Interface Vs Class

Non-access modifiers in Java


Non-access modifiers in Java are: final, static, abstract, synchronized and volatile.

1. Final Modifier

The final modifier in java can be used with classes, method and member variables. To
use it, just write final in beginning of variable, method or class. It is used to restrict the
user. It means that, the variable, class or a method with final modifier keyword makes
that the programmer cannot modify or change the value anymore. The actual meaning
depends on whether it is applied to a class, a variable, or a method. The final modifier
is used for following purposes:
a. To define constants (final keyword when used with variable)
Final keyword is used with variable to declare them as a constant. Once the value is
assigned to final variable, it cannot be changed during the runtime.
Example:
public class Circle{ void area()
private final float pi=3.14; {
private int r; float a=pi*r*r;
Circle(int x) System.out.println(“area”,a);
{ }
Pi=3.1; //cannot be changed }
because Pi is
//defined as final.
r=x;
}

b. To prevent Overriding (final keyword when used with method)


The final access modifier can be used to prevent a method in parent class being
overridden by child class. This can be done by declaring that method in parent class as
a final method.
Example:
class Dog public static void main(String
{ args[])
final void eat(){ {
System.out.println(“Eating”); Animal obj= new Animal();
} obj.eat();
} }
}
class Animal extends Dog
{ Output: error: “eat() in Animal
void eat() cannot override eat() in Dog”
{
System.out.println(“eating This program when compiled,
meat”); compiler throws an error saying that
} “eat() in Animal cannot override
eat() in Dog”
c. To prevent Inheritance (final keyword when used with class)
Final access modifier can be use with class declaration to prevent it from further
inherited by other class. It is because final class cannot be further inherited by other
classes.
Example:
Final class A
{
//code;
}

Class B extends A // throws error


{
//code;
}

2. Static Modifier

Static variables and methods belong to the class rather than an instance of the class.
In Java, the static modifier is used to declare a variable, method, or inner class as a
class-level entity rather than an instance-level entity. When a variable or method is
declared as static, it belongs to the class as a whole, and there is only one copy of it
regardless of how many objects of that class are created.
a. Static variables: A static variable is shared by all instances of the class. If a
value is assigned to a static variable, it becomes available to all instances of the
class, and any modification to it will be reflected across all instances.
b. Static methods: A static method can be called directly on the class without
creating an instance of the class. This is useful when you need to perform a task
that doesn't require any object-specific state.
c. Static blocks: A static block is used to initialize the static variables or perform
any other static initialization tasks. It is executed once when the class is loaded
into memory, before any instances of the class are created.
d. Static inner classes: A static inner class is a nested class that is declared as
static. It can be accessed without creating an instance of the enclosing class,
and it cannot access non-static members of the enclosing class.

3. Abstract modifier

In Java, the abstract modifier is used to declare a class or method that has no
implementation and must be implemented by a subclass. Abstract classes cannot be
instantiated directly, and can only be used as a base class for other classes that extend
them. Abstract methods must be overridden by a subclass to provide a concrete
implementation.
Here are some key features of abstract classes and methods in Java:
a. Abstract classes: An abstract class is a class that is declared using the abstract
keyword and has at least one abstract method. Abstract classes can have both
abstract and non-abstract methods, and can also have variables, constructors,
and static methods. However, abstract classes cannot be instantiated directly,
and can only be used as a superclass for other classes that extend them.

b. Abstract methods: An abstract method is a method that is declared using the


abstract keyword and has no implementation. Abstract methods must be
declared in an abstract class, and they must be overridden by a subclass to
provide a concrete implementation. If a class contains an abstract method, it
must also be declared as an abstract class.

c. Implementation by Subclasses: When a subclass extends an abstract class


that contains abstract methods, it must provide a concrete implementation for
each of the abstract methods. Failure to do so will result in a compilation error.

d. Benefits: The main benefit of using abstract classes and methods is that they
allow for greater flexibility and code reuse in object-oriented programming.
Abstract classes provide a common interface for a group of related classes, while
abstract methods allow subclasses to provide their own implementation of a
method while adhering to a common interface.

Inner class (Non-static nested class)


Java inner class or also called non-static nested class is a class that is declared inside
the class or interface. A non-static nested class or inner class is a class within another
class. It has access to members (including private members too) of the enclosing class
(outer class). The purpose of inner classes is to group classes that belong together,
which makes your code more readable and maintainable.
Syntax:
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Since the inner class exists within the outer class, you must instantiate the outer class
first, in order to instantiate the inner class.
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Example:
public class OuterClass
{
private int x = 10;

// Inner class
public class InnerClass
{
public int getX( ){
return x;
}
}

public static void main(String[] args) {


OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.getX()); // Output: 10
}
}
In this example, InnerClass is an inner class of the OuterClass. It has access to the
private variable x of the outer class. In main method, at first, an instance of the
OuterClass is created then, only an instance of the InnerClass is created using the new
keyword with the outer class instance. Finally, the getX method of the inner class is
called to retrieve the value of x.

Packages
Related classes can be bundled together in a collection called a package. Packages are
containers for similar classes that helps programmer to manage different classes.
When we create any Java program the java.lang package is imported by default. We
need not to write the package name at the top of the program.
The main advantages of using a package are that it helps you to organize your work
because:
 You can set the control over access to the components of a package.
 Packages helps to manage classes and hence the searching/locating and usage
of classes, interface etc. are simplified.
 You can enlarge the "name space", and prevents naming conflicts: for example,
the Vector class in one package, java.util package differs from the Vector class
in another package, NL.uva.wins.datastructures.
 It simplifies the naming of classes, For example: after importing the java.awt
class you can use short names like Button and TextField instead of the full
names java.awt.Button and java.awt.TextField, respectively.
Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions. Some of the existing packages in Java are: java.lang, java.io etc.

Creating a Package

When creating a package, you should choose a name for the package and put a
package statement with that name at the top of every classes source files that you
want to include in that package. the package statement should be in the first line of
the source file.
Creating a package in Java involves the following steps:
1. Choose a suitable package name for your package according to the naming
convention. This name should be in lowercase letters and separated by dots if it
contains multiple words. For example, if you are creating a package for a
calculator program, you could name the folder "com.mycompany.calculator".

2. Create a package: Create a new folder for your package with the package name.

3. Create your Java classes: Create one or more Java classes which you want to
include in your package.

4. Add the package declaration: For including classes in your package, add the
package declaration at the top of each Java class file, to specify which package
the class belongs to. For example, if your package name is
"com.mycompany.calculator", you would add the following line to the top of your
Java class:
package com.mycompany.calculator;
Example: In this example, we have a class named MyClass that is included in the
myapp package.
package com.example.myapp;
public class MyClass
{
public void display(){ //must be public to get accessed from
another package
System.out.println("Hello, world!");
}
public static void main(String[] args)
{
MyClass c=new MyClass();
c.display();
}
}

Using Package or accessing or importing the package’s content to other file

There are two main ways of accessing classes in another package. One way is to add
the full package name in front of every class name.
Example:
jav.util.Date today=new java.util.Date()
Another is using the import keyword to import a specific class or whole package. The
import statement will be given at the top of the file just below the package statement.

Example:
import java.util.*;
Date today= new Date();
Different way of accessing the package
1. Importing a Single Class of a package: The statement import java.lang.String;
imports the class String from the java.lang package (Here lang is inner package
which lies inside java package). After this statement, the signature of the
getDisplayCustom method can be defined by
public void getDisplayCustom(String g){ }
instead of by
public void getDisplayCustom(java.lang.String g){ }

2. Importing All Classes inside a package: If you want to import all the classes
and interfaces from a package, for instance, the entire java.lang package, use the
import statement with the asterisk (*) wildcard character.
import java.lang.*;
Importing all classes of a package may slow down compilation, but has no other
effects on efficiency.

Example:
Import myapp.*; //must import myapp.* which means all in myapp to
access //classes in it.
public class NextClassOfNextPackage
{
public static void main(String[] args)
{
System.out.println("I am next class of next package");
MyClass a=new MyClass(); //You can instantiate class of
imported package.
a. display(); //You can use method of imported package’s class
using its
//object.
}
}

PART 3

Exception Handling
What is exceptional handling and why it should be handled?
Exceptions are unexpected events that disrupt the normal flow of program execution,
such as division by zero, null pointer exceptions, and file I/O errors. Exception handling
is a mechanism in Java that allows developers to handle and recover from runtime
errors and exceptions that occur during program execution, while keeping the
application’s normal flow intact. The good thing about exception handling is that java
developer can handle the exceptions in such a way so that the program doesn’t get
terminated suddenly and the user get a meaningful error message.
An exception can occur for many reasons. Some of them are:
 If we want to access the array index which is out of range or size of array.
 Opening an unavailable file
 Loss of network connection during network related task
 Invalid SQL query operation
 Invalid arithmetic operations such as divide by zero case
 Invalid user input like invalid type input
 Device/hardware failure
The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error. The hierarchy of Java Exception
classes is given below:

What is difference between exception and error?


In Java, both errors and exceptions are subclasses of the Throwable class, but they
represent different types of problems that can occur during program execution.
a. Exception: An exception is a problem that can occur during the normal execution
of a program. It is a signal that something unexpected has happened or an error
has occurred that needs to be handled. Exceptions are divided into two
categories: checked exceptions and unchecked exceptions. Checked exceptions
are those that the compiler requires to be caught or declared, while unchecked
exceptions are those that can be thrown at runtime and do not need to be
caught or declared.
b. Error: An error, on the other hand, is a problem that typically occurs when
something has gone terribly wrong with the JVM or the hardware running the
JVM. Errors are usually not recoverable, and they indicate serious problems that
can't be handled by the application code. Examples of errors include
OutOfMemoryError, StackOverflowError, and NoClassDefFoundError.

Some basic keywords in Exception Handling

In Java, there are several keywords that are used in exceptional handling. Here are
some of the basic keywords:
a. try: The try block contains the code that may throw an exception.

b. catch: The catch contains the code that handles the exception thrown by try
block. Catch block catches the exception and handles it appropriately. It is
followed by the type of exception that it can catch.

c. finally: The finally block is used to execute code after the try block, regardless
of whether an exception is thrown or not. Code inside finally block is always
executed regardless either exception occurs or not in try block. This block is
typically used to clean up resources, such as closing files or database
connections.

d. throw: The throw keyword is used to explicitly throw an exception. It is typically


used in custom exception handling code to indicate that an error has occurred.
e. throws: The throws keyword is used in the method signature to indicate that
the method may throw an exception. This allows the caller to catch and handle
the exception appropriately.

Different techniques for exceptional handling in java


1. try-catch: The try-catch block is used to handle exceptions that may occur in a
block of code. The try block contains the code that may throw an exception, and the
catch block catches the exception and handles it accordingly.

2. throw: The throw keyword is used to manually throw an exception. This is useful
when you need to handle a specific exception case or when you want to create your
own exception class.

3. throws: The throws keyword is used to declare the exceptions that a method may
throw. This allows the calling code to handle the exception appropriately.

4. finally: The finally block is used to define a set of statements that will be executed
after the execution of the try and catch blocks, regardless of whether an exception
is thrown or not. The finally block is often used for releasing resources or cleaning
up after the try block.

5. Multiple catch blocks: In some cases, a single try block may throw multiple types of
exceptions. In this case, multiple catch blocks can be used to handle each exception
type differently.
6. Custom Exception Classes: Custom exception classes can be created to handle
specific types of exceptions that are not covered by the built-in exception classes.
This allows for more specific and customized exception handling.

1. try-catch blocks

Java provides a structured way to handle exceptions using try-catch blocks. The try
block includes the code that might generate an exception. The catch block includes the
code that is executed when there occurs an exception inside the try block and the
catch block catches the exception and handles it appropriately.
try{
//code
}
catch(exception) {
// code
}
Example:
import java.*;
public class TryCatchDemo
{
public static void main(String[] args)
{
try {
int d = 5 / 0;
System.out.println("Print" + d);
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
//or, simply you can handle as:
//System.out.println("Cannot divide by zero”);
}
}
}

2. try-finally blocks

Q.Can we use try block without using a catch block in Java?

Example:
public class TryWithFinally
{
public static int method()
{
try {
System.out.println("Try Block with return type");
return 10;
} finally {
System.out.println("Finally Block always execute");
}
}
public static void main(String[] args)
{
System.out.println(method());
}
}

3. Using try-catch-finally blocks for exception handling

Java finally block is always executed whether an exception is handled or not.


Therefore, it contains all the necessary statements that need to be printed regardless
of the exception occurs or not.
Syntax:
try{
//statements that may cause an exception
}
catch(Exception e){
//statements that will execute if exception occurs
}
finally{
//statements that execute whether the exception occurs or not
}
Example:
import java.util.Scanner;

public class DivideByZeroException {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

try {
System.out.print("Enter the numerator: ");
int numerator = input.nextInt();

System.out.print("Enter the denominator: ");


int denominator = input.nextInt();

int result = numerator / denominator;


System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Program execution complete.");
}
}
}
Cases of finally block used in exception handling with preceding try-catch
blocks:
Q. When does the finally block is mandatory in while handling exception?
In Java, the finally block is used to define a set of statements that will be executed
after the execution of the try and catch blocks, regardless of whether an exception is
thrown or not. The finally block is optional, but there are cases where it is necessary to
use it, such as:
 When you need to release resources: If your code allocates system resources,
such as file handles or network connections, you should use the finally block to
release these resources when they are no longer needed. This is important to
avoid resource leaks and ensure the program runs efficiently.

 When you need to perform clean-up operations: The finally block can be used to
clean up or reset the state of your program. For example, if you are working
with a database, you might want to close the database connection in the finally
block to ensure that it is always closed, even if an exception is thrown.

 When you need to perform final actions: If you need to perform some final
actions before exiting the program, such as logging or sending a notification, you
can use the finally block to do this. This is particularly useful in long-running
programs that need to be shut down gracefully.
In summary, the finally block is not always mandatory when handling exceptions, but it
is useful in situations where you need to release resources, perform clean-up
operations, or perform final actions.

Other cases are:


4. Java Throw Keyword

The throw keyword is used to manually throw an exception. This is useful when you
need to handle a specific exception case or when you want to create your own
exception class.
The Java throw keyword is used to throw an exception explicitly or manually. We
specify the exception object which is to be thrown. The Exception has some message
with it that provides the error description. These exceptions may be related to user
inputs, server, etc.
Syntax for Java Throw keyword is given below:
throw new exception_class(“error message”);
Example
Throw an exception if age is below 18 (print “Access denied”). If age is 18 or older,
print “Access granted”:
5. Java throws keyword

In Java, the throws keyword is used in method signatures to indicate that the method
may throw one or more types of exceptions. When a method is declared with the
throws keyword, the calling code is required to handle or propagate any checked
exceptions that the method may throw.
Example:
public void readFile(String filename) throws IOException
{
// code to read a file
}
In this example, the readFile method takes a filename as input and may throw an
IOException if an error occurs while reading the file. By including the throws keyword
in the method signature, we are indicating to the calling code that it must handle or
propagate the IOException if it is thrown.
It's important to note that if a method declares that it throws a checked exception, the
calling code must handle or propagate the exception. This can be done by either
catching the exception with a try-catch block or declaring the exception with the throws
keyword in the calling method's signature. If the exception is not handled or
propagated, the compiler will generate an error.
Example:
public class Example {
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}

Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Example {


public static void main(String[] args) {
try {
String filename = "example.txt";
readFile(filename);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}

public static void readFile(String filename) throws FileNotFoundException {


File file = new File(filename);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}

User defined Exception or Custom Exception or Creating Exception class

In Java, a user-defined exception is an exception that you define yourself by creating a


new class that extends one of the existing exception classes or one of their subclasses.
A user-defined exception is used to handle situations in your code where none of the
built-in exception classes are appropriate, or where you need to provide more specific
information about the error that occurred. For example, you might define a user-
defined exception to handle errors related to invalid user input, database connection
failures, or other specific situations that are not covered by the built-in exception
classes.
To define a user-defined exception, you create a new class that extends the Exception
class or one of its subclasses, such as RuntimeException. The new class should have a
constructor that takes a String message as input and passes it to the superclass
constructor using the super keyword.
Once you have defined a user-defined exception class, you can use it in your code just
like any other exception. You can throw the exception using the throw keyword, and
catch it using a try-catch block. You can also include the exception in the method
signature using the throws keyword.
Defining your own exceptions can make your code more readable and easier to
maintain. By using descriptive exception names, you can make it easier to understand
what went wrong when an error occurs. Additionally, by creating your own exceptions,
you can provide more specific information about the error that occurred, which can
help you to debug and fix problems more quickly.
Here's an example of a user-defined exception class:

In this example, we define a new exception class called InvalidInputException that


extends the Exception class. The class includes a constructor that takes a String
message as input and passes it to the superclass’s constructor (i.e. Exception
superclass’s constructor) of derived InvalidInputException class using the super
keyword.
Once you have defined a user-defined exception class, you can use it in your code just
like any other exception. For example, here's how you might use the
InvalidInputException class:

In this example, we use the InvalidInputException class to indicate that the user input
is invalid. If the input is less than zero, we throw a new InvalidInputException with a
descriptive error message. In the main method, we catch this exception and print the
error message to the console.
Note that when you define a user-defined exception class, you should provide a clear
and informative error message in the constructor. This will help developers diagnose
and fix problems more quickly. Additionally, you should only define new exceptions
when none of the existing exception classes are appropriate for your specific use case.
Difference between throw and throws

Concurrency
Concurrency is the ability of a program to execute multiple tasks simultaneously. In
Java, there are several ways to achieve concurrency. The most approach to achieve
concurrency in Java is threads.

Threads
One of the simplest ways to achieve concurrency in Java is through threads. A thread
is a lightweight process that runs within a larger process. By creating multiple threads
within a program, each thread can execute a different task simultaneously. Java
provides a Thread class and Runnable interface to create and manage threads. For
example= A word processor can have one thread running in foreground as an editor
and another in the background auto saving the document!
In Java thread programming, multithreading is a process by which we can execute
multiple threads simultaneously.
Advantages of threads:
 This leads to maximum utilization of CPU.
 Multithreading is used to achieve multitasking.
The path of execution of each thread is different, And they are independent so that
even if an exception comes in one thread, it does not affect other threads.
A multithreaded program contains two or more parts that run simultaneously. Each
part of such a program is called a thread. It is mostly used to create games and
animations.
Types of threads:
There are two types of thread in this. First user thread and second daemon thread.
Daemon threads are used when we want to clean the application and they are used in
the background.

Life cycle of a thread:

Here are the different states of a thread in Java:


1. New: An instance of thread is in this state when it has been created but has not yet
started. The thread is not considered alive at this point.
2. Runnable: The thread is in this state when it has been started by using start()
method and is ready to run, but the JVM has not yet allocated a processor to
execute it. The thread may be waiting for resources or for its turn to run.
3. Running: The thread is in this state when the JVM has allocated a processor to
execute it. The run() method of the thread is being executed.
4. Blocked/Waiting/Sleeping: The thread is in this state when it is waiting for a
resource or waiting for another thread to perform an action or if it has to some I/O
operation. A thread may enter this state when it calls sleep(), wait() etc. methods.
The thread can be in waiting, sleeping, or blocked state.
5. Terminated: The thread is in this state when its run() method has completed, and
it has exited.
Example of multithreading by extending Threads class: (importing library is not
necessary here)
public class ThreadExample extends Thread {
public void run () {
System.out.println("run method");
}
public static void main ( String[] args ) {
ThreadExample p1 = new ThreadExample ();
ThreadExample p2 = new ThreadExample ();
System.out.println("p1 State : "+p1.getState());
System.out.println("p2 State : "+p2.getState());
p1.start();
System.out.println("p1 State : "+p1.getState());
System.out.println("p2 State : "+p2.getState());
p2.start();
System.out.println("p1 State : "+p1.getState());
System.out.println("p2 State : "+p2.getState());
}
}
Output:
p1 State : NEW
p2 State : NEW
p1 State : RUNNABLE
run method
p2 State : NEW
p1 State : TERMINATED
run method
p2 State : RUNNABLE
Here in this program, multithreading is done by extending or inheriting Thread class.
The new thread can be created by creating object of child class of Thread class. The
Start() method of Thread class is called by child class (i.e. ThreadExample) to make
the thread ready or runnable. When the thread in runnable state, it is automatically
calls run() (since it is a constructor) method for executing the code inside run() method
by thread. Here, getState() method of Thread class returns the current state of thread.
When object or thread is created it is in NEW state, when start method is called, it is in
RUNNABLE state, and it will automatically call run() method.
example of multithreading in Java using the Runnable interface:

public class MultithreadingExample implements Runnable {


public void run() {
System.out.println("Thread is running.");
}

public static void main(String[] args) {


MultithreadingExample example = new MultithreadingExample();
Thread thread = new Thread(example);
thread.start();
}
}
In this example, we define a class called MultithreadingExample that implements the
Runnable interface. The run() method is defined to simply print a message indicating
that the thread is running.
In the main() method, we create an instance of the MultithreadingExample class and
then create a new Thread object, passing in the example object as the argument to the
Thread constructor. We then start the thread by calling its start() method.
Output:
Thread is running.

Old questions
i. What is package? How can you create your own package in Java? Explain with
example. (1+4) [2078]
ii. Describe the responsibility of Serializable interface. Write a program to read an
input string from the user and write the vowels of that string in VOWEL.TXT and
consonants in CONSOLNANT.TXT (2+8) [2077]
iii. A non-empty array A of length n is called on array of all possibilities if it contains
all numbers between 0 and A.length-1 inclusive. Write a method named
isAllPossibilities that accepts an integer array and returns 1 if the array is an
array of all possiblities, otherwise it returns 0. (5)[2077]
iv. When does the finally block is mandatory in while handling exception? Describe
with a suitable scenario. (5)
[2077]
v. What is the task of manifest file? Write the procedure to create it. [2 + 3][2077]
vi. Why multiple inheritance is not allowed in Java using classes? Give an example.
(5)[2077]
vii. Why synchronization in essential in multithreading? Describe. (5)[2077]
viii. Write short notes on. [2.5+2.5][2077]
a. JAVA beans and JAR file
b. MVC design pattern
ix. Why do we need to handle the exception? Distinguish error and exception, Write
a program to demonstrate your own exception class. [1+2+7]
[2075]
x. An array is called balanced if it's even numbered elements (a[0], a[2], etc.) are
even and its odd numbered elements (a[1], a[3],etc.) are Odd. Write a function
named is Balanced that accepts an array of integers and returns 1 if the array is
balanced otherwise it returns 0. [5][2075]
xi. Define the chain of constructor. What is the purpose of private constructor? [5]
[2075]
xii. Write down the life cycle of thread. Write a program to execute multiple threads
in priority base. [2+3][2075]
xiii. When do we use final method and final class? Differentiate between function
overloading and function overriding.[2+3][2075]
xiv. Give any two differences between class and bean. Write the steps to create JAR
files. [2+3][2075]
xv. What is exception handling? Discuss the use of each keyword (try, catch, throw,
throws and finally) with suitable Java program.[2076]
xvi. Define class. How do you create a class in Java? Differentiate class with
interface.[5][2076]
xvii. Write a simple Java program that reads a file named "Test.txt" and displays its
contents.[5][2076]
xviii. Discuss MVC design pattern with example.[5][2076]
xix. Define Java Bean. How is it different from other Java programs? What is design
pattern?[5][2076]
xx. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple
inheritance with suitable example.(1+2+7)[2074]
xxi. .Write an object oriented program to find area and perimeter of rectangle. (5)
[2074]
xxii. 5. Write a simple java program that reads data from one file and writes the data
to another file (5) [2074]
xxiii. Describe multithreading in Java.(5)[2074]
xxiv. What is multithreading? How can you write multithreaded programs in java?
Discuss with suitable example.(10)[2073]
xxv. Write an object oriented program to find the area and perimeter of rectangle.(5)
[2073]
xxvi. Write the simple java program that reads data from one file and writes data to
another file.(5)[2073]
xxvii. What is exception handling? Discuss exception handling in detail with suitable
example. (10)[2071]

Old questions of unit 2 and 3

You might also like