Q. Explain different features of java.
Ans.i)Compile And interpreted- java is two state programming
language Java compiler converts source code into bytecode then
java interpreter interprets bytecode into machine code.
ii)Platform independent & portable:- You can download the Java
applet from Www buy a remote computer for a local system via
Internet execute it locally.
iii)Object oriented:- Java is true oop language all programmes are
presented with in object and classes.
iv)Simple , small,& familier:- Java doesn’t use pointer also
eliminates operator overloading and multiple inheritance it modify
from concept of C++.
v)Robust and secure- Java is robust language provides many
safeguards to ensure reliable code java system not only verify
memory access but also ensure that no virus are communicated
with an applet Java.
vi)Distributed:- Java is designed as distributed language for
creating applications on Internet.
vii)Multithreaded and interactive:- Multithreaded means handling
multiple tasks simultaneously graphical application features make
Java interactive.
viii)High performance:- Java performance is imperative For an
interpreted languages.
Q.2) What is constructor ? Explain with suitable example.
Ans. A constructor is a special member function in object-oriented
programming languages like C++, Java, and others, which is
automatically called when an object of the class is created. The
main purpose of a constructor is to initialize the data members of
the class when an object is instantiated. Unlike other member
functions, a constructor has the same name as the class and does
not have any return type, not even void. This automatic invocation
of the constructor makes it very useful for setting up default
values or initial settings for an object, ensuring that it is ready to
use immediately after creation.
There are different types of constructors, such as default
constructors (which take no parameters), parameterized
constructors (which take arguments to initialize objects with
specific values), and copy constructors (which initialize an object
using another object of the same class). Constructors can also be
overloaded, meaning a class can have more than one constructor
with different parameter lists.
Let us consider a class named Student which has two data
members: name and rollNumber. When we create an object of this
class, we want these two values to be automatically assigned. To
achieve this, we use a constructor. Inside the class, we define a
constructor with the same name as the class, i.e., Student. This
constructor takes two parameters – one for the name and one for
the roll number. When an object of the Student class is created,
such as Student s1("Amit", 101);, the constructor is automatically
called, and it assigns the values "Amit" to name and 101 to
rollNumber. This process ensures that every time a new student
object is created, the data members are initialized with
meaningful values. Later, we can use a display function to print
these values. This automatic and structured way of assigning
initial values to an object at the time of its creation is the main
use of a constructor.
Q.3)What is inheritance ? Explain its type.
Ans. Inheritance is one of the fundamental concepts of object-
oriented programming (OOP). It is a mechanism that allows one
class (called the derived class or child class) to inherit the
properties and behaviors (i.e., data members and member
functions) of another class (called the base class or parent class).
Inheritance promotes code reusability, as common functionality
defined in the base class does not need to be rewritten in the
derived class. It also helps in building a hierarchical classification,
making programs easier to manage and understand. In the
derived class, we can use the members of the base class as well
as define new members. The derived class can also override
functions of the base class to provide specific implementations.
Types of Inheritance:
1. Single Inheritance
In this type, a single derived class inherits from a single base
class. This is the simplest form of inheritance.
Example: A Car class inherits from a Vehicle class.
2. Multiple Inheritance
In multiple inheritance, a derived class inherits from more
than one base class. This means the derived class has
multiple parent classes.
Example: A SmartPhone class inherits from both Camera and
Mobile classes.
(Note: In some languages like Java, multiple inheritance is
not supported using classes but is possible through
interfaces.)
3. Multilevel Inheritance
In this type, a class is derived from another derived class,
creating a chain of inheritance.
Example: A SportsCar class inherits from Car, which in turn
inherits from Vehicle.
4. Hierarchical Inheritance
In hierarchical inheritance, multiple classes inherit from a
single base class.
Example: Classes Dog, Cat, and Cow all inherit from a
common base class Animal.
Q.4)What is package?Explain it with suitable example.
Ans. A package in programming, especially in Java, is a way to
organize classes, interfaces, and sub-packages into a single,
structured unit. It acts like a folder in a file system, grouping
together related code to make it more manageable, readable,
and reusable. Packages help avoid name conflicts by providing
a namespace for classes. For example, two classes with the
same name can exist in different packages without causing any
errors. Java provides two types of packages: built-in packages
(like java.util, java.io, etc.) and user-defined packages, which
are created by the programmer to suit specific needs. By using
packages, developers can keep their code modular, organized,
and secure, especially in large applications.
Ex. Let us understand the concept of a package with a practical
example in Java. Suppose we are developing a school
management system and we want to group all the student-
related classes separately. To do this, we can create a package
named studentinfo. Inside this package, we can create a class
called Student that contains details and functions related to
students. We declare the package at the top of the class file
using the package keyword. For instance, in the file
Student.java, we write package studentinfo; and define the
Student class below it. This class might have a method called
display() which prints student information. Now, to use this
class in another file, such as Test.java, we use the import
statement like import studentinfo.Student;. Then, in the main
method, we create an object of the Student class and call its
method. This whole structure shows how a package helps in
logically grouping classes and makes the code easier to
organize and reuse. It also avoids naming conflicts when the
program grows in size. Thus, packages are very useful in
managing large Java applications efficiently.
Q.5)What is exception handling ? Explain in detail.
Ans. Exception handling is a powerful mechanism in
programming languages like Java, C++, and Python that is
used to handle runtime errors gracefully without crashing the
program. An exception is an unwanted or unexpected event
that disrupts the normal flow of the program's execution. These
can occur due to various reasons such as division by zero, file
not found, invalid user input, or array index out of bounds. If
exceptions are not properly handled, they can cause the
program to terminate unexpectedly, leading to poor user
experience or data loss.
Exception handling provides a structured way to detect and
respond to errors during program execution. It allows
developers to write code that can catch errors, take appropriate
action, and allow the program to continue or shut down
gracefully. In Java, the exception handling mechanism is built
using try, catch, throw, throws, and finally blocks. The code
that might cause an exception is placed inside the try block. If
an exception occurs, it is caught by the matching catch block,
where appropriate actions (like displaying a message or
correcting the error) are taken. The finally block contains code
that is always executed, whether an exception is thrown or not,
typically used to release resources like closing files or database
connections.
Q.6)What is method overloading ? Explain with suitable
example.
Ans. Method overloading is a feature in object-oriented
programming (especially in Java, C++, etc.) that allows a class
to have more than one method with the same name but
different parameters. This is done to increase the readability,
flexibility, and reusability of the code. The methods must differ
in their number of parameters, type of parameters, or the order
of parameters. The return type can be different, but it is not
considered for method overloading on its own. When a method
is called, the compiler determines which version of the method
to execute based on the arguments passed. This is also known
as compile-time polymorphism, because the method to be
executed is determined at compile time.
Ex. Consider a class called Calculator that performs addition.
We can create multiple methods named add(), but with
different parameters. For instance, one add() method can take
two integers and return their sum, another add() can take
three integers, and another might take two double values. Even
though all methods are named add, they perform slightly
different tasks depending on the input types and number of
arguments. When we call add(5, 10), it invokes the method
with two integers. If we call add(5.5, 4.5), it calls the version
that accepts two doubles. This simplifies the design of the class
by avoiding the need to create separate method names like
addInt(), addDouble(), or addThreeNumbers().
Q.7) What is AWT in java.
Ans. AWT, which stands for Abstract Window Toolkit, is a part
of Java’s standard library used to create Graphical User
Interface (GUI) components in Java applications. It is provided
in the java.awt package and includes classes for creating
windows, buttons, menus, labels, text fields, and other
graphical components. AWT is one of the earliest GUI toolkits in
Java and is based on native GUI components provided by the
operating system, which means it uses the system’s default
look and feel. This makes AWT platform-dependent, as the
appearance of GUI components may vary across different
operating systems.
AWT follows the event-driven programming model, where user
interactions such as mouse clicks or keyboard input are
handled using event listeners. The AWT hierarchy is built
around several key classes, such as Frame (for creating
windows), Button, Label, TextField, and layout managers like
FlowLayout, BorderLayout, etc., which help organize
components in a container.
Although AWT is simple and easy to use, it has some limitations
in terms of appearance and flexibility. For more advanced and
consistent GUI features, Java later introduced Swing, which is a
more powerful and platform-independent GUI toolkit built on
top of AWT.
One of the important features of AWT is its event-handling
mechanism, which allows programs to respond to user actions
like button clicks or key presses using event listeners and
adapters. Despite being somewhat outdated compared to Swing
and JavaFX, AWT still serves as a strong foundation for
understanding GUI programming in Java and is useful for
creating simple, platform-specific interfaces.
Q.8)Write short note on applet life cycle.
Ans. An applet in Java is a small program designed to run
within a web browser or an applet viewer. Unlike standalone
Java applications, applets follow a specific life cycle controlled
by the browser or viewer. The life cycle includes several
predefined methods that are automatically invoked at different
stages of the applet’s execution. These methods are used to
manage the creation, execution, and destruction of the applet,
ensuring proper operation during its life span.
The first method in the applet life cycle is init(), which is called
only once when the applet is first loaded. It is used for
initialization, such as setting up variables, creating GUI
components, or loading resources. After that, the start()
method is called, and it is also called every time the applet
becomes active again (for example, when the user returns to
the web page). This method is typically used to start
animations, threads, or other tasks that need to run while the
applet is active.
Next, the paint(Graphics g) method is called whenever the
applet needs to render output on the screen. This method takes
a Graphics object as a parameter and is used to draw text,
shapes, or images within the applet window. It is called not
only after start() but also whenever the applet is repainted due
to resizing or exposure.
When the applet is no longer visible or the user navigates away
from the web page, the stop() method is called. This is used to
pause any ongoing activity like animations or background
threads. Finally, when the applet is about to be removed
permanently from memory, the destroy() method is called. This
method is used for cleanup operations, such as closing files or
releasing system resources.
Q.9) Write short notes on stream class In java.
Ans. In Java, the Stream classes are part of the java.io package
and are used for input and output operations, commonly known
as I/O operations. A stream represents a continuous flow of
data, either from an input source (such as a keyboard, file, or
network) or to an output destination (such as a screen, file, or
printer). Java treats all I/O as a stream of data, making it
easier to perform read and write operations in a consistent
way. Streams abstract the details of the device or medium,
allowing the programmer to work with data in a platform-
independent and uniform manner. This makes stream classes
extremely useful for handling files, network connections,
console input/output, and more.
There are two main types of streams in Java: Byte Streams and
Character Streams. Byte Streams handle raw binary data and
use classes like InputStream and OutputStream. For example,
FileInputStream and FileOutputStream are used to read and
write binary data from and to files. On the other hand,
Character Streams handle text data and use classes like Reader
and Writer. For example, FileReader and FileWriter are
commonly used to read and write character data from and to
files. To make I/O operations more efficient, Java provides
buffered versions of these streams, such as BufferedReader and
BufferedWriter, which reduce the number of interactions with
the actual data source or destination by using a buffer in
memory.
Additionally, Java’s stream classes support filtering and data
processing through advanced classes like DataInputStream,
DataOutputStream, PrintWriter, and ObjectInputStream. These
classes allow for reading and writing Java primitive data types
and objects, which is particularly useful for developing complex
applications. Java also introduced a new Stream API in Java 8
(found in java.util.stream) for processing collections in a
functional style, but this is different from the I/O stream
classes. Overall, stream classes in Java are a powerful and
flexible toolset for managing all kinds of data input and output
efficiently and reliably.
Q.10) What is interface ? Explain with suitable example.
Ans. An interface in Java is a blueprint of a class that contains
only abstract methods (method declarations without a body)
and constants (variables that are final and static). It is used to
achieve abstraction and multiple inheritance in Java. Unlike a
class, an interface cannot contain method implementations
(though from Java 8 onwards, it can have default and static
methods with bodies). Interfaces are used when different
classes may have different implementations of the same set of
methods. This helps in writing flexible and loosely-coupled
code.
When a class implements an interface, it agrees to provide
implementations for all the methods defined in the interface.
This ensures that the class follows a specific set of rules or
behaviors. Interfaces are particularly useful in large
applications where you want to define a standard structure that
multiple classes can follow. It also allows polymorphism, where
the same interface can be used to refer to objects of different
classes.
Example:-
Let’s consider a simple example to understand interfaces.
Suppose we have an interface called Animal that declares a
method makeSound(). Now, we create two classes: Dog and
Cat, both of which implement the Animal interface. The Dog
class provides its own version of makeSound() that prints “Dog
barks”, while the Cat class provides an implementation that
prints “Cat meows”. Although both classes have different
behaviors, they follow the same interface. This allows us to
write code like Animal a = new Dog(); or Animal a = new Cat();
and call a.makeSound(); — the correct version of the method is
executed depending on the actual object. This shows how
interfaces help in achieving polymorphism and flexible code
design.
Q.11) Write short notes on -i) Final keyword ii)Abstract class.
i)Final keyword:- In Java, the final keyword is used as a
modifier that can be applied to variables, methods, and classes,
each with a specific purpose. When a variable is declared as
final, its value cannot be changed after it is initialized. This
makes it a constant. For example, final int MAX = 100; means
that MAX will always hold the value 100 and cannot be
reassigned. When a method is declared as final, it cannot be
overridden by subclasses. This is useful when you want to
prevent altering the behavior of a method in inheritance.
Similarly, when a class is declared final, it cannot be subclassed
(i.e., no other class can extend it). For example, the String
class in Java is a final class, which means no one can create a
subclass of it. The final keyword helps in maintaining security,
consistency, and preventing unintended changes in a program’s
behavior, making it a valuable feature in object-oriented
programming.
ii)Abstract class:- Abstract class is a class that cannot be
instantiated on its own and typically used as base class for
other classes.It is declared using abstract keyword.It have both
abstract method or concrete methods.An abstract class have
instance variable.
Syntax:-
abstract class shape ()
{abstract void draw();}
iii) wrapper class:- In java a wrapper class is a class that
provides a way to use primitive data types like int , char etc. as
object.The java is designed to work with objects and primitive
data types are not objects.wrapper class encapsulate or wrap
primitive datatype into object.This allows primitive datatype to
be used In situations where objects are required.Conversion of
primitive value into on object of corresponding wrapper class is
called as autoboxing.Converting an object of wrapper type to
its corresponding primitive value is called unboxing.
Q.13) What is thread ? explain thread lifecycle in detail.
Ans. In Java, a thread is a lightweight subprocess, a smallest
unit of execution within a program. Threads allow a program to
perform multiple tasks simultaneously, which is known as
multithreading. This improves the performance and
responsiveness of applications, especially in tasks like
downloading files, processing data, or managing user
interfaces. Each thread runs independently, but they share the
same memory space, making communication between threads
efficient. Threads can be created in Java by either extending
the Thread class or implementing the Runnable interface. Once
a thread is started using the start() method, it begins its
execution in a separate path.
The life cycle of a thread in Java consists of five main stages:
New, Runnable, Running, Blocked/Waiting/Sleeping, and
Terminated. These states describe how a thread behaves from
creation to completion. The Java Virtual Machine (JVM) and
thread scheduler manage these transitions automatically based
on system resources and conditions.
1. New: When a thread object is created using the Thread class
or Runnable interface, but the start() method hasn't been
called yet, the thread is in the new state.
2. Runnable: Once the start() method is called, the thread
enters the runnable state. In this state, the thread is ready
to run but waiting for the CPU to schedule it for execution.
3. Running: When the thread scheduler selects the thread from
the runnable pool and assigns it CPU time, the thread is in
the running state. This is when the run() method is being
executed.
4. Blocked / Sleeping / Waiting: A thread moves to a non-
runnable state if it is waiting for a resource, sleeping for a
fixed time, or waiting for another thread’s action. For
example, calling sleep(), wait(), or trying to access a
synchronized block held by another thread can cause a
thread to enter this state. Once the condition is resolved, the
thread returns to the runnable state.
Q.14)What is looping statement ? Explain any one with suitable
example.
Ans. A looping statement in Java is used to execute a block of
code repeatedly as long as a specified condition is true. Loops
help reduce code repetition and are widely used in situations
where the same task needs to be performed multiple times, such
as printing numbers, processing arrays, or performing
calculations. Java provides several types of looping statements:
for loop, while loop, and do-while loop. Each has a specific syntax
and use case, but the basic idea remains the same—to repeat code
execution based on a condition.
The for loop is one of the most commonly used loops in Java. It is
used when the number of iterations is known in advance. The for
loop has three main parts: initialization, condition, and update.
These parts are all written in one line, which makes it compact
and easy to understand.
Syntax:
for(initialization; condition; update) {
// code to be executed
public class ForLoopExample {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
Q.15) What is class & object ? Explain in detail ?
Ans. OBJECT : An entity that has state and behaviour is known as
an object e.g., chair, bike, marker, pen, table, car, etc. It can be
physical or logical (tangible and intangible). The example of an
intangible object is the banking system. An object has three
characteristics:
State: represents the data (value) of an object.
Behaviour: represents the behaviour (functionality) of an object
such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique
ID. The value of the ID is not visible to the external user.
However, it is used internally by the JVM to identify each object
uniquely.
CLASS: A class is a group of objects which shares common
characteristics/ behavior and common properties/attributes. It is
a user-defined blueprint or prototype from which objects are
created.
A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Q16. Explain Try, catch ?
ANS:- Try and catch both are Java keywords and used for
exception handling. The try block is used to enclose the suspected
code. Suspected code is a code that may raise an exception during
program execution. For example, if a code raise arithmetic
exception due to divide by zero then we can wrap that code into
the try block.
try{
int a = 10;
int b=0
int ca/b;
The catch block also known as handler is used to handle the
exception. It handles the exception thrown by the code enclosed
into the try block. Try block must provide a catch handler or a
finally block. The catch block must be used after the try block
only. We can also use multiple catch block with a single try block.
try{
int a = 10;
int b=0
int ca/b; // exception
}catch(ArithmeticException e){
System.out.println(e);
} To declare try catch block, a general syntax is given below
Try
catch(ExceptionClass ec)
).