JavaAnskey_Gou
JavaAnskey_Gou
Features of java
1. Simple:Java is a small and simple language. Java does not use pointers, preprocessor
header files, goto statement and many others. It also eliminates operator overloading and
multiple inheritance. Java is modeled on C and C++ languages. So it is familiar to
programmers.
3. Portable :Portability is a major aspect of the Internet because there are many different
types of computers and operating systems connected to it. If a Java program needs to be
run on virtually any computer connected to the Internet, there needed to be some way to
enable program to execute on different systems. Java ensures portability through 2 types:
a. Bytecode generation (runs on any machine)
b. Machine-independent data type sizes.
4. Platform independent:Java code can be executed on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
6. Robust :It has strict compile time and run time checking for data types. It is designed as a
garbagecollection language relieving programmers of virtually all memory management
problems. Java also includes the concept of exception handling which captures series errors
and eliminates any risk of crashing the system.
8.Complied and Interpreted: Java supports crossplatform code through the use of Java
bytecode. Byte codes are not machine instructions and therefore, in the second stage, Java
interpreter generates machine code that can be directly executed by the machine that is
running the Java program.
5. What are Java tokens? List and explain the different types of Java Tokens.
Java Tokens
Java tokens are the smallest units in a Java program that are meaningful to the compiler. When a
Java program is compiled, the source code is broken into these tokens.
1. Keywords
Keywords are reserved words that have predefined meanings in Java. They cannot be used as
variable names, class names, or identifiers.
Examples:
2. Identifiers
Identifiers are the names given to variables, classes, methods, etc. They are created by the
programmer and must follow specific naming rules.
Rules:
● Must start with a letter, $, or _
Examples:
3. Literals
Literals are fixed values assigned to variables. They represent constant values used in the code.
Types of literals:
4. Operators
Types of operators:
5. Separators
Separators (also called punctuators) are used to define structure and organize code.
Common separators:
● () → parentheses (method calls, grouping)
● {} → braces (blocks)
● [] → brackets (arrays)
In Java, operators are symbols that tell the compiler to perform specific operations on
one, two, or more operands (variables, values, or expressions). Operators are used to
perform tasks such as mathematical calculations, logical evaluations, value
assignments, and comparisons.
1. Arithmetic Operators
These operators are used to perform basic mathematical operations such as addition,
subtraction, multiplication, division, and modulus.
- Subtraction a - b Difference
* Multiplication a * b Product
/ Division a / b Quotient
% Modulus a % b Remainder
Eg-
int a = 20, b = 8;
These operators are used to compare two values. They return a boolean value (true or
false).
== Equal to a == b
!= Not equal to a != b
3. Logical Operators
These operators are used to combine multiple conditions (expressions) and return a boolean
result.
` `
4. Assignment Operators
= Assign value a = 10
-= Subtract and a -= 2
assign
5. Unary Operators
+ Unary plus +a +a
- Unary minus -a -a
1. if Statement in Java
The if statement is used to execute a block of code only when a given condition is true.
Syntax:
if (condition) {
// statements to execute if condition is true
}
Eg-
int age = 20;
Syntax:
if (condition) {
// statements if condition is true
} else {
// statements if condition is false
}
Eg-
int number = 5;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
Syntax:
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
} else {
// statements if condition1 is true but condition2 is false
}
} else {
// statements if condition1 is false
}
Eg-
1. for Loop
The for loop is used when the number of iterations is known in advance.
Syntax:
for (initialization; condition; update) {
// statements to be executed
}
Eg:
2. while Loop
The while loop is used when the condition is checked before the loop
executes. It is ideal for situations where the number of iterations is not
known beforehand.
Syntax:
while (condition) {
// statements to be executed
}
Eg:
int i = 1;
while (i <= 5) {
System.out.println("Value: " + i);
i++;
}
3. do-while Loop
The do-while loop is used when the loop body should execute at least
once, regardless of the condition.
syntax:
do {
// statements to be executed
} while (condition);
Eg:
int i = 1;
do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);
Memory Management
1. Method Area: Stores class metadata, such as method code and static
variables.
2. Heap: Stores objects created by the application.
3. Stack: Stores method call stack frames, including local variables and
method parameters.
4. Native Method Stack: Stores native method calls.
Garbage Collection
The JVM periodically performs garbage collection to:
Key Benefits
1. Platform independence: Java code can run on any platform with a JVM.
2. Memory management: The JVM manages memory allocation and
deallocation.
3. Security: The JVM provides a sandboxed environment for running Java
code.
The JVM's working ensures that Java code is executed efficiently, securely,
and independently of the underlying platform.
14. What are arrays? Explain different types of arrays in Java with
example?
Arrays in Java are used to store multiple values of the same data type in a
single variable. Java supports both one-dimensional (1D) and
two-dimensional (2D) arrays.
Syntax:
Example:
System.out.println(numbers[2]); // Output: 30
2. Two-Dimensional Array (2D)
Syntax:
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // Output: 6
1. Decision-Making Statements
Examples:
● if
● if-else
● if-else-if
● switch
Types:
● for loop
● while loop
● do-while loop
3. Branching Statements
Used to alter the normal flow of control (exit a loop early, skip to the next
iteration, or return from a method).
Types:
In Java, operators are symbols that tell the compiler to perform specific operations on
one, two, or more operands (variables, values, or expressions). Operators are used to
perform tasks such as mathematical calculations, logical evaluations, value
assignments, and comparisons.
1. Arithmetic Operators
These operators are used to perform basic mathematical operations such as addition,
subtraction, multiplication, division, and modulus.
- Subtraction a - b Difference
* Multiplication a * b Product
/ Division a / b Quotient
% Modulus a % b Remainder
Eg-
int a = 20, b = 8;
These operators are used to compare two values. They return a boolean value (true or
false).
Operator Description Example
== Equal to a == b
!= Not equal to a != b
3. Logical Operators
These operators are used to combine multiple conditions (expressions) and return a boolean
result.
` `
4. Assignment Operators
= Assign value a = 10
+= Add and assign a += 5
-= Subtract and a -= 2
assign
1. if Statement in Java
The if statement is used to execute a block of code only when a given condition is true.
Syntax:
if (condition) {
// statements to execute if condition is true
}
Eg-
int age = 20;
Eg-
int number = 5;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
Syntax:
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
} else {
// statements if condition1 is true but condition2 is false
}
} else {
// statements if condition1 is false
}
Eg-
Switch Statement
Used to select one of many possible blocks of code to be executed, depending on the
value of a variable.
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// default block
}
Eg:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Syntax:
// Declaration
int[] arr;
// Memory Allocation
// Declaration + Initialization
System.out.println(numbers[2]); // Output: 30
Syntax:
// Declaration
int[][] matrix;
// Memory Allocation
matrix = new int[2][3]; // 2 rows, 3 columns
// Declaration + Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // Output: 6
6. Explain Java Data Types with example for each?
In Java, data types specify the kind of data that a variable can store. They define the size,
nature, and behavior of data used in a Java program. Java is a strongly typed language,
meaning every variable must have a declared data type..
🔹 a) Integer Types
Data Type Size Range Example
🔹 b) Floating-Point Types
Data Type Size Description Example
🔹 c) Character Type
Data Type Size Description Example
🔹 d) Boolean Type
Data Type Size Description Example
1. Decision-Making Statements
Examples:
● if
● if-else
● if-else-if
● switch
Types:
● for loop
● while loop
● do-while loop
3. Branching Statements
Used to alter the normal flow of control (exit a loop early, skip to the next
iteration, or return from a method).
Types:
Unit 2
16.Explain the class and object in Java with example.&
For Example, Pen is an object . Its name is Reynolds ; color is white, known
as its state . It is used to write, so writing is its behavior .
• Methods
• Constructors
• Blocks
Example program:
class Student {
int id = 21510;
18. What are classes? How do you declare a class in Java? Explain each
term in it.(2+3+5)
Data is encapsulated in a class by placing data fields inside the body of the
class definition.
datatype fieldname ;
For example :
class Rectangle
{
int length ;
int width ;
}
Method Declaration
Methods are declared inside the body of the class but immediately after the
declaration of instance variables
class Rectangle
Eg:
class Bike1 {
Bike1() {
System.out.println("Bike is created");
}
public static void main(String args[]) {
Bike1 b = new Bike1();
}
}
2.Parameterized constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
Eg:
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
}
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
Student s1 = new Student(111, "Karan");
Student s2 = new Student(222, "Aryan");
s1.display();
s2.display();
}
}=
Inheritance
• Reusability is the another aspect of OOP paradigm. Java supports this
concept.
• This is basically done by creating new classes, reusing the properties of
existing ones.
• The mechanism of deriving a new class from an old one is called inheritance.
• The old class is known as base class, super class or parent class.
• The new one is called the subclass, derived class or child class.
• The inheritance allows subclasses to inherit all the variables and methods of
their parent classes.
• The keyword extends signifies that the properties of the super class name
are extended to the subclass name.
• The subclass will now contain its own variables and methods as well as
those of the super class.
• This kind of situation occurs when we want to add some more properties to
an existing class without actually modifying it.
Types of inheritance
Single Inheritance:
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Dog is barking");
}
}
public class Example
{ public static void main(String[] args)
{ Dog dog = new Dog(); dog.eat(); // inherited method dog.bark(); // method of
child class }
}
Multilevel Inheritance:
• In Multilevel Inheritance, a derived class will be inheriting a base class, and
as well as the derived class also acts as the base class for other classes.
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Dog is barking");
}
}
class Labrador extends Dog
{
void color()
{
System.out.println("Labrador is brown");
}
}
public class Example
{
public static void main(String[] args)
{
Labrador labrador = new Labrador();
labrador.eat(); // inherited from Animal
labrador.bark(); // inherited from Dog
labrador.color(); // method of Labrador
}
}
Hierarchical Inheritance:
• In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass.
class Shape
{
void draw()
{
System.out.println("Drawing a shape");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("Drawing a rectangle");
}
} class Triangle extends Shape
{
void draw()
{
System.out.println("Drawing a triangle");
}
}
public class Example
{
public static void main(String[] args)
{
Shape circle = new Circle();
Shape rectangle = new Rectangle();
Shape triangle = new Triangle();
circle.draw();
rectangle.draw();
triangle.draw();
}
}
interface ElectronicDevice {
void turnOn();
void turnOff(); }
System.out.println("Car starting"); }
System.out.println("Car stopping"); }
}}
// example of Multiple inheritance
car.start();
car.stop();
car.turnOn();
car.turnOff();
}
}
• In method overriding, the return type must be the same or covariant (return
type may vary in the same direction as the derived class).
Eg:
class Shape
{
void draw()
{
System.out.println("Drawing a shape");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("Drawing a circle");
}
}
public class Main { public static void main(String[] args)
{
Shape shape = new Shape();
shape.draw();
Circle circle = new Circle();
circle.draw();
}
}
Output:
Drawing a shape
Drawing a circle
Method Overloading
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• In method overloading, more than one method shares the same method
name with a different signature in the class.
• In method overloading, the return type can or can not be the same, but we
have to change the parameter because, in java, we can not achieve the
method overloading by changing only the return type of the method.
import java.io.*;
class MethodOverloadingEx {
static int add(int a, int b)
{
return a + b;
} static int add(int a, int b, int c)
{
return a + b + c;
}
public static void main(String args[])
{
System.out.print(" a+b = ");
System.out.println(add(4, 6));
System.out.print(" a+b+c = ");
System.out.println(add(4, 6, 7));
}
}
OUTPUT
a+b = 10
a+b+c = 17
30. What is exception handling? Why do exceptions occur?
31. What is exception? Explain the methods to handle it.
32. Explain the different types of exception handling methods in java.(10
mark)
13. Explain the types of exceptions in detail with example code for each.
14. Explain the methods of handling exceptions in Java with appropriate
programming example for each.(15 mark)
Java exceptions
● When executing Java code, different errors can occur:
○ coding errors made by the programmer
○ errors due to wrong input
○ or other unforeseeable things
● When an error occurs, Java will normally stop and generate an error
message.
● The technical term for this is: Java will throw an exception (throw an error). ●
When an exception occurs within a method, it creates an object.
● This object is called the exception object.
● It contains information about the exception, such as the name and
description of the exception and the state of the program when the exception
occurred.
Major reasons why an exception Occurs
● Code errors
● Invalid user input
● Device failure
● Loss of network connection
● Physical limitations (out of disk memory)
● Opening an unavailable file
● Exception Handling in Java is one of the effective means to handle the
runtime errors so that the regular flow of the application can be preserved.
● In java there are three methods to handle the exceptions
● They are
* try-catch
* finally
* throw
try and catch
● The try statement allows you to define a block of code to be tested for errors
while it is being executed.
● The catch statement allows you to define a block of code to be executed, if
an error occurs in the try block.
● The try and catch keywords come in pairs
● Syntax
try {
// Block of code to try
}
catch(Exception e)
{
};
Finally
•The finally statement lets you execute code, after try...catch, regardless of the
result
•The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
The throw keyword
● The "throw" keyword is used to throw an exception.
● The throw statement allows you to create a custom error.
● The throw statement is used together with an exception type.
● There are many exception types available in Java:
○ ArithmeticException
○ FileNotFoundException
○ ArrayIndexOutOfBoundsException
○ SecurityException, etc
When an applet begins, the following methods are called, in this sequence:
● init( )
● start( )
● paint( )
When an applet is terminated, the following sequence of method calls takes
place:
● stop( )
● destroy( )
1. init( ) : The init( ) method is the first method to be called. This is where you
should initialize variables. This method is called only once during the run time
of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart
an applet after it has been stopped. Note that init( ) is called once i.e. when
the first time an applet is loaded whereas start( ) is called each time an
applet’s HTML document is displayed onscreen. So, if a user leaves a web
page and comes back, the applet resumes execution at start( ).
3. paint( ) : Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt. The paint() has one parameter of type graphics.
This is used whenever output to the applet is required.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example.
When stop( ) is called, the applet is probably running. You should use stop( )
to suspend threads that don’t need to run when the applet is not visible. You
can restart them when start( ) is called if the user returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from memory. At
this point, you should free up any resources the applet may be using. The
stop( ) method is always called before destroy( ).
// Overriding paint() method
HTML code:
<html>
<body>
height="200">
</applet>
</body>
</html>
Unit 3
35. Explain thread with its example. Also explain the benefits of thread.
(6+4)
36. Explain threads. Explain its life cycle
38. Describe the life cycle of a thread in Java. Explain each phase in
detail(10 mark)
19. Discuss the different states in the life cycle of a thread in Java.
Explain each state in detail with suitable examples.(15 mark)
Threads in Java
• A Thread is a very light-weighted process.
• It is the smallest part of the process that allows a program to operate more
efficiently by running multiple tasks simultaneously.
• In order to perform complicated tasks in the background, we used the
Thread concept in Java.
• All the tasks are executed without affecting the main program. • In a program
or process, all the threads have their own separate path for execution, so
each thread of a process is independent.
Benefits of threads
1.Java Threads are lightweight compared to processes, it takes less time and
resource to create a thread.
2.Threads in Java provide a powerful mechanism for building responsive,
scalable, and efficient concurrent applications.
3.Threads share their parent process data and code Context switching
between threads is usually less expensive than between processes.
4.Thread intercommunication is relatively easy than process communication.
By using threads, applications can remain responsive to user input even while
performing lengthy operations in the background.
5.Threads allow multiple tasks to be executed concurrently, improving the
performance of applications by utilizing available resources more efficiently
New
• By default, a Thread will be in a new state, in this state, code has not
yet been run and the execution process is not yet initiated.
Runnable State
awaiting the processor's availability (CPU time). That is, the thread has
• Threads in this state are either running or ready to run, but they’re
Running State
• Running implies that the processor (CPU) has assigned a time slot to
the thread for execution. When a thread from the runnable state is
chosen for execution by the thread scheduler, it joins the running state.
• When the thread gets the CPU, it moves from the runnable to the
• In the running state, the processor allots time to the thread for
execution and runs its run procedure. This is the state in which the
thread directly executes its operations. Only from the runnable state
state.
Waiting/Blocked State
then, either the thread is in the blocked state or is in the waiting state.
• When the thread is alive, i.e., the thread class object persists, but it
but currently the lock is acquired by the other thread. The thread will
move from the blocked state to runnable state when it acquires the
lock.
join() method. It will move to the runnable state when other thread
• A thread lies in a timed waiting state when it calls a method with a timeout
parameter. A thread lies in this state until the timeout is completed or
Dead/Terminated State
automatically dies or enters the dead state. That is, when a thread exits
• It’s in the terminated state when it has either finished execution or was
terminated abnormally.
1. Better CPU Utilization: Idle CPU time can be used efficiently.
4. Resource Sharing: Threads share the same memory space, reducing
overhead.
thread1.start();
thread2.start();
}
39. Describe the various constructors available in the Thread class.
Provide examples.
1. Using Thread()
t.start();
t.start();
t.start();
t.start();
}
40. Explain the methods of making classes threadable
41. Explain how you can create and start a thread in Java. Provide and
explain an example to demonstrate this process.
System.out.println("Thread is running...");
}
43. Explain Synchronization in java with programming example(10mark)
20. Describe the concept of synchronization in Java threads. Describe
why synchronization is necessary and provide examples to demonstrate
its usage.
21. Illustrating java programs, explain how synchronization is important
in programming. What happens if it is skipped during
multithreading(15mark)
• Synchronization in Java is the process that allows only one thread at a
particular time to complete a given task entirely.
• The synchronization is mainly used
1.to prevent thread interference.
2.to prevent consistency problem.
• General form of synchronized statement
Synchronized(objRef) {
//statements to be synchronized
}
eg:
class Counter {
✅
Importance of Synchronization in Programming
○ When two or more threads try to modify shared data at the same
time, they can interfere with each other’s operations.
What Happens if Synchronization is Skipped?
44. Explain the delegation event model. Explain the steps of registering
source with listener.
• Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism has the code which is
known as event handler that is executed when an event occurs.
• Java uses the Delegation Event Model to handle the events.
Registering the source with a listener is a crucial step in the Java
The following are the steps for registering the source with a
listener:-
handle. For example, if you're dealing with GUI events, you might
varies depending on the event source and the type of event you're
handling.
45. What is an event and event handling in Java? Provide Example.
Explain the two types of events in java?
• The change in the state of an object or behavior by performing actions is
referred to as an Event in Java.
• Actions include button click, keypress, page scrolling, or cursor movement.
Types of Events
1. The Foreground Events:
• Foreground events typically refer to events that require immediate attention
and are directly related to the user interaction or user interface.
2. The Background Events :
• Background events occur in the background or behind the scenes, usually
without requiring direct user interaction.
• These events may include tasks like network communication, data
processing, or automated system operations.
46. Write a note on event listener interface. Explain any ten.
Listeners are created by implementing one or more of the interfaces defined
by the java.awt.event package.
✅
1. ActionListener
✅ 2. AdjustmentListener
● Used for: Scrollbar adjustments.
✅ 3. ComponentListener
● Used for: Component visibility or size changes.
● Methods:
○ componentResized()
○ componentMoved()
○ componentShown()
○ componentHidden()
✅ 4. ItemListener
● Used for: Checkbox or list item selection changes.
✅ 5. ContainerListener
● Used for: Adding or removing components in a container.
● Methods:
○ componentAdded()
○ componentRemoved()
✅ 6. FocusListener
● Used for: When a component gains or loses keyboard focus.
● Methods:
○ focusGained()
○ focusLost()
✅ 7. KeyListener
● Used for: Keyboard input.
● Methods:
○ keyPressed()
○ keyReleased()
○ keyTyped()
✅ 8. MouseListener
● Used for: Mouse clicks and button events.
● Methods:
○ mouseClicked()
○ mousePressed()
○ mouseReleased()
○ mouseEntered()
○ mouseExited()
✅ 9. MouseMotionListener
● Used for: Mouse movement and dragging.
● Methods:
○ mouseDragged()
○ mouseMoved()
✅ 10. WindowListener
● Used for: Window events like open, close, minimize.
● Methods:
○ windowOpened()
○ windowClosing()
○ windowClosed()
○ windowIconified()
○ windowDeiconified()
○ windowActivated()
○ windowDeactivated()
import java.awt.event.*;
AdapterExample() {
addWindowListener(new WindowAdapter() {
System.out.println("Window Closing");
});
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
Inner class or nested class is a class that is declared inside the class or
interface.
class Outer {
int innerData = 5;
void display() {
JFrame: JFrame is a top-level container that represents the main window of a
GUI application. It provides a title bar, and minimizes, maximizes, and closes
buttons.
JPanel: JPanel is a container that can hold other components. It is commonly
used to group related components together.
JButton: JButton is a component that represents a clickable button. It is
commonly used to trigger actions in a GUI application.
JLabel: JLabel is a component that displays text or an image. It is commonly
used to provide information or to label other components.
JTextField: JTextField is a component that allows the user to input text. It is
commonly used to get input from the user, such as a name or an address.
Eg:
import javax.swing.*;
}
22. Explain the two methods of making classes threadable in Java with
example(15 mark)
● Call the start() method to begin execution, which internally calls run().
Example:
System.out.println("thread is running...");
● Pass an instance of your class to a Thread object and start it using the
start() method.
Example:
System.out.println("thread is running...");