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

Java Notes Old Ques

The document provides a comprehensive overview of Java programming concepts, including definitions and explanations of static data, import statements, Java buzzwords, object-oriented programming, and various data types. It also covers advanced topics such as inheritance, method overriding, and the Java Virtual Machine architecture. Additionally, it discusses the use of keywords like 'this' and 'super', as well as the differences between String and StringBuffer classes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views40 pages

Java Notes Old Ques

The document provides a comprehensive overview of Java programming concepts, including definitions and explanations of static data, import statements, Java buzzwords, object-oriented programming, and various data types. It also covers advanced topics such as inheritance, method overriding, and the Java Virtual Machine architecture. Additionally, it discusses the use of keywords like 'this' and 'super', as well as the differences between String and StringBuffer classes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2 MARKS

Unit – 1
1. Define: “Static Data”.
Ans: Static data is shared among all objects of a class. It belongs to the class, not objects. Memory is
allocated only once for static variables.
Useful for common properties like counters.

Eg : class Test {
static int x = 10;
}

2. What is general form of import statement?:


import package_name.class_name; import
package_name.*;
Used to access classes from other packages.
Avoids writing fully qualified names.

3. Write a note on Java buzzwords.


Ans: Key features: Simple, Object-Oriented, Platform Independent, Secure, Robust, Multithreaded. Also
includes Distributed and High Performance.
These features make Java widely used.

4. Write the general form of a method declaration in java.


returnType methodName(parameters) {

// body

Defines behavior of an object.


Can return value or be void.

5. Write a note on static method.


Ans: A method that belongs to the class and can be called without object. Can access
only static data directly.
Used for utility or common operations.

class Test {
static void show() {

[Link]("Hello");

} }

6. List out the different types of operators in Java.


Ans: Arithmetic, Relational, Logical, Assignment, Bitwise, Unary, Ternary.
Used to perform operations on variables and values.
Each type has specific purpose.

7. What is Object-Oriented Programming?


Ans: A programming concept based on objects and classes. Supports reuse
using inheritance.
Improves modularity and maintainability.

8. What is the purpose of the main method in a Java program?


Ans: Entry point of Java program. Execution starts here.
JVM calls this method automatically.
Must be public, static, and void.

public static void main(String[] args) { }

9. Identify the primary difference between String and String Buffer classes in Java.
Ans: String: Immutable
StringBuffer: Mutable
String is slower for modification. StringBuffer
is faster for frequent changes.

String s = "Hi";

StringBuffer sb = new StringBuffer("Hi");

10. Why java is known as platform independent?


Ans: Because it uses bytecode that runs on JVM on any system. “Write
once, run anywhere” concept.
No need to recompile for different OS.
11. Write down the rules for naming classes
Ans: Start with uppercase letter.
Should not use keywords or spaces. Use
meaningful names.
Example: MyClass

Unit – 2
12. Define: “Array”.
Ans: Collection of same type elements stored in contiguous memory. Size is
fixed once declared.
Accessed using index values. int

a[] = {1,2,3};

13. Mention the advantages of constructor.


Ans: Initializes objects automatically.
Reduces need for separate initialization method. Improves
code readability.

14. Show the declaration of Abstract classes.


Ans: abstract class Test {

abstract void show();

Cannot be instantiated. Used


to achieve abstraction.

15. State the use of dynamic method dispatch.


Ans: Method call resolved at runtime.
Supports runtime polymorphism.
Based on object type, not reference type.

A obj = new B();


[Link]();

16. What do you mean by inheritance?


Ans: Acquiring properties of one class into another. Promotes
code reuse.
Uses keyword extends.
class B extends A { }

17. State the rules for naming classes in Java.


Ans: Same as Unit-1 rules.
Use CamelCase naming.
Example: StudentData

18. What is method overriding?


Ans: Redefining parent method in child class. Achieves
runtime polymorphism.
Method signature must be same.

class A { void show(){} }


class B extends A { void show(){} }

19. Mention the general form of package statement.


Ans: package package_name;
Used to group related classes.
Helps avoid name conflicts.

20. Define a user-defined class in Java.


Ans: Class created by programmer.
Contains variables and methods.
Used to define objects.

class Student { }

21. Identify the different types of inheritance in Java.


Ans: Single, Multilevel, Hierarchical.
Multiple inheritance via interfaces only.
Improves code structure.

Unit – 3
22. Give the example for Runnable interface.
Ans: class MyThread implements Runnable {

public void run() {

[Link]("Thread running");
}

Used to create threads.


Preferred over extending Thread class.

23. What do you mean by synchronization?


Ans: Controls access of multiple threads to shared resources. Prevents data
inconsistency.
Uses synchronized keyword.

24. What are the usages of final keyword?


Ans: Variable: constant
Method: cannot override
Class: cannot extend
Improves security and stability.

25. Show the purpose of Abstract Window Tool Kit.


Ans: Used to create GUI components like buttons, windows. Platform
dependent.
Part of Java GUI library.

26. Comment on garbage collection.


Ans: Automatic memory management to delete unused objects. Handled by
JVM.
Reduces memory leaks.

27. What is the purpose of the finally block in exception handling?


Ans: Executes always after try-catch.
Used for cleanup operations.
Runs even if exception occurs.

28. Identify the difference between throw and throws in Java.


Ans: throw: used to throw exception
throws: declares exception
throw used inside method. throws
used in method signature.
29. How to stop a thread?
Ans: Using flag or interrupt method.
Avoid using stop() (deprecated).
Ensures safe thread termination.

[Link]();

30. What is the use of catch block


Ans: Handles exceptions.
Prevents program crash.
Can have multiple catch blocks.

Unit – 4
31. Define: “Swing”.
Ans: Java GUI toolkit for building applications. Platform
independent.
Provides rich components.

32. What is the use of J Label control?


Ans: Displays text or images.
Used in GUI forms.
Does not allow user input.

33. What is JscrollPane control?


Ans: Adds scrollbars to components. Used
for large content display.
Improves usability.

34. What is the purpose of the AWT class hierarchy in Java?


Ans: Defines structure of GUI classes.
Shows parent-child relationships. Helps in
understanding components.

35. Define a top-level container in Swing.


Ans: Main window container like JFrame.
Holds other components.
Required for GUI apps.
36. What is the function of the JLabelcomponent
in Swing? Ans:
[Link] text or icon.
[Link]-editable
component.
[Link] for labels
informs.

37. What is AWT?


Ans: [Link] Window Toolkit
for GUI.
[Link] dependent.
[Link] basic components.

Unit – 5
38. Comment on Enumeration.
Ans:
[Link] to iterate collection
elements.
[Link] with legacy classes like
Vector.
[Link] methods like hasMoreElements().

39. Define the term “Adapter Classes”.


Ans: Provide default implementation of
interfaces. Used in event handling.
Reduces coding effort.

40. What is an adapter class in Java?


Ans: Predefined classes like
WindowAdapter. Override only required
methods.
Used with listeners.

41. What is the role of the


Comparator interface? Ans:
[Link] to sort objects.
[Link] custom sorting
logic.
3. Implements compare()
method.

5 MARKS
[Link] will you declare a variable in java?
To declare a variable in Java, you must specify the data type followed by the variable name,
and terminate the statement with a semicolon (;).
Basic Declaration Syntax
The standard format for creating a variable is:
Syntax: dataType variableName;
Methods of Declaration
 Declaration without value: Introduces the variable but assigns no value yet.
Eg: int score;
 Declaration with Initialization: Assigns an initial value immediately using the
assignment operator (=).
Eg: int score = 4;
 Multiple Declarations: You can declare multiple variables of the same type in one
line by separating them with commas.
Eg: int x = 5, y = 10, z = 15;
Rules for naming variables are:
 Names can contain letters, digits, underscores, and dollar signs
 Names must begin with a letter
 Names can also begin with $ and _
 Names are case-sensitive ("myVar" and "myvar" are different variables)
 Reserved words cannot be used as names
Types of Variables in Java
The location where you declare a variable determines its scope:
 Local Variables: Declared inside methods or blocks; must be initialized before use.
 Instance Variables: Declared inside a class but outside methods; belong to a specific
object.
 Static (Class) Variables: Declared with the static keyword; shared across all
instances of the class.
 Constants: Declared using the final keyword to ensure the value cannot be changed
after assignment.
[Link] example. Summarize the JVM architecture with diagram
Java Virtual Machine is a engine that provides Runtime environment to derive the Java code
or application. It converts Java bytecode into machine language JVM is a part of Java
Runtime environment (JRE)
Class Loader
Class loader is a system used for loading class files. It performs three major functions loading
linking initialization
Method area
Method area stores per class structure such as the runtime constants field and method data for
methods
Heap
It is used to allocate the objects JVM creates a class object for each class files
Stack
stack is used for storing temporary variables it holds local variables and partial results
PC register (Program Counter)
PC register contains the address of the Java Virtual Machine instruction
Native methods stack
Native methods stack it contains all the native method used in the application
Execution engine
It is type of software used to text hardware software complete system the text execution
engine never carries any information about the tested product
Native method Interface
Native method allows Java code which is running in a JVM to call by libraries and native
applications
Native method libraries
It is a correction of native library (C or C + +) which are needed by the execution engine
[Link] the type conversion and casting with example.
Assigning the value of one primitive data type to another Type
[Link] casting
2. Narrowing casting
Widening casting
• Widening casting converting a smaller data type to larger data type
• It takes place when two data type are compatible
• Target type is larger than the source type
byte -> short -> char -> int -> long -> float -> double
Eg:
class Geeks {
public static void main(String[] args)
{
int i = 10;
long l = i;
double d = i;
[Link]("Integer: " + i);
[Link]("Long: " + l);
[Link]("Double: " + d);
}
}
Narrowing casting
• converting a larger type to a smaller type size
double -> float -> lon g -> int -> char -> short -> byte
Eg:
class Geeks {
public static void main(String[] args)
{
double i = 100.245;
short j = (short)i;
int k = (int)i;
[Link]("Original Value before Casting"+ i);
[Link]("After Type Casting to short " + j);
[Link]("After Type Casting to int " + k);
}
}
[Link] the string and string buffer classes.
1. String Class
The String class represents a sequence of characters. It is immutable, meaning once a
String object is created, its value cannot be changed.
 Immutable (cannot modify the original object)
 Stored in String Constant Pool
 Thread-safe by default
 Any modification creates a new object
2. StringBuffer Class
StringBuffer is used to create mutable strings. It allows modification of the same
object without creating new ones.
 Mutable (can change content)
 Thread-safe (synchronized methods)
 Efficient for repeated modifications
 Stored in heap memory
class Demo {
public static void main(String[] args) {

// ===== String Example =====


String s = "Hello";
[Link]("Original String: " + s);
[Link]("Length: " + [Link]());
[Link]("Character at index 1: " + [Link](1));
[Link]("Uppercase: " + [Link]());

String s2 = [Link](" World");


[Link]("After concat: " + s2);

[Link]("Substring (1,4): " + [Link](1,4));


[Link]("Equals 'Hello': " + [Link]("Hello"));

===== StringBuffer Example ===== //

StringBuffer sb = new StringBuffer("Hello");

[Link]("\nOriginal StringBuffer: " + sb);

[Link](" World");
[Link]("After append: " + sb);

[Link](0, 5, "Hi");
[Link]("After replace: " + sb);

[Link](0, 2);
[Link]("After delete: " + sb);

[Link]();
[Link]("After reverse: " + sb);

[Link]("Capacity: " + [Link]());


}
}

5. Explain the different data types available in Java.


1. Primitive Data Types
These are the basic, built-in building blocks of Java and represent simple values directly in
memory. There are eight primitive type
 Integers (Whole Numbers)
o byte: 8-bit signed integer. Range: -128 to 127.
o short: 16-bit signed integer. Range: -32,768 to 32,767.
o int: 32-bit signed integer. Standard choice for whole numbers.
o long: 64-bit signed integer. Used for very large values; must end with an 'L'
(e.g., 100L).
 Floating-Point (Decimals)
o float: 32-bit single-precision. Good for saving memory in large arrays; must
end with an 'f'.
o double: 64-bit double-precision. Default choice for decimal numbers in Java.
2. Non-Primitive (Reference) Data Types
These types refer to objects and store the memory address of the data rather than the actual
value. They can be null and are often user-defined.
 Strings: A sequence of characters.
 Arrays: Collections of elements of the same type (e.g., int[] or String[]).
 Classes: User-defined templates used to create objects.
Eg:
class DataTypesDemo {
public static void main(String[] args) {

// Primitive Data Types


byte b = 10;
short s = 1000;
int i = 50000;
long l = 100000L;

float f = 10.5f;
double d = 20.99;

char c = 'A';
boolean flag = true;

// Non-Primitive Data Types


String str = "Hello Java";

int arr[] = {1, 2, 3, 4};

// Output
[Link]("byte value: " + b);
[Link]("short value: " + s);
[Link]("int value: " + i);
[Link]("long value: " + l);

[Link]("float value: " + f);


[Link]("double value: " + d);

[Link]("char value: " + c);


[Link]("boolean value: " + flag);

[Link]("String value: " + str);

[Link]("Array values: ");


for(int x : arr) {
[Link](x + " ");
}
}
}
[Link] the use of import statements in package.
In Java, the import statement is used to make classes and interfaces from other
packages available in the current program
 Syntax of Import Statement
import package_name.class_name;
import package_name.*;

Types of Import Statement


(A) Specific Class Import
Used to import only one class.
import [Link];

class Test {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
}
}
(B)Wildcard Import
Used to import all classes from a package.
import [Link].*;

class Test {
public static void main(String[] args) {
ArrayList list = new ArrayList();
}
}
7. Describe the usage of this and super keyword.
This keyword is reserved keyword in java. It is used to refer current class instance as well as
static members. And also passed as an argument in method call & constructor call
Eg :
Class person
{
String name;
person (string name)
{
[Link]=name;
}
void display ()
{
[Link](name);
}
}
Public static void main(string args [])
{
person p=new person (“kamal”);
[Link]();
}
}
Super keyword
Super keyword is reserved keyword in Java. It is referred superclass instance as well
as static members. And also used to invoke superclass method or constructor
Class parent
{
int a= 10;
Static int b =20;
}
class child extends parent
{
void show ()
{
[Link](super.a);
[Link](super.b);
}
Public static void main(string args [])
{
child c=new child();
[Link]();
}
}

8. Distinguish between the method overloading and method overriding.(any 5)


Feature Method Overloading Method Overriding
Defining multiple methods
Redefining an
with the same name but
Definition inherited method in a
different parameters in the
subclass.
same class.
Polymorphism Runtime
Compile-time polymorphism
Type polymorphism
Number of Two classes
One class
Classes Involved (Inheritance required)
Parameter List Must be different Must be the same
Can be different but not used Must be the same or
Return Type
for differentiation covariant
Static Methods Can be overloaded Cannot be overridden
Cannot have a more
Access Modifier Can be different
restrictive modifier
Minor overhead due
Performance
No runtime overhead to dynamic method
Impact
dispatch
9. Explain the concept of method overloading in Java with an example.
Method Overloading (Compile time polymorphism)
• Method overloading in java means having multiple methods with the same name
in the same class, but with different in the parameters Lists.
• Java determines which overloaded method to call at compile time based on the
arguments passed.

class addition

void sum (int a, int b) {

[Link] (a+b);

void sum (int a, int b, int c)


{
[Link] (a+b+c);

public static void main (string args[])

addition

addition a = new addition ();

a. sum (12,10);

a. sum (10,12,1);

}
10. Examine the concept of packages in Java.
Packages
A package is a collection of related classes and interfaces stored in a directory
structure.
Types of Packages
(1) Built-in Packages
Provided by Java.
 [Link] (default package)
 [Link]
 [Link]
(2) User-defined Packages
Created by programmer.
Creating a Package
package mypack;

class Test {
void display() {
[Link]("Welcome to Package");
}
}
Using a Package (Importing)
import [Link];

class Demo {
public static void main(String[] args) {
Test t = new Test();
[Link]();
}
}
11. Explain dynamic dispatch method
Is a process where the method call is executed during the runtime
The overridden Method is called through reference variable of super class this process
is also known as Rum-time polymorphism.

clan Animal
{
void makesound (){
[Link] ("Animal make different sounds");
}
}
Class Day extends Animal{
void makesound ()
{
[Link] ("Dog barks");
}
}
class cat extends Animal
void makesound {
[Link] ("cat meows");
public class Dispatch Eg
{
Public static void main(String args[]) {
Animal a = new Dog ();
a. makesound();
Animal a = new cat();
[Link]();
}
12. Elaborate the types of built-in exceptions in java.
Types of Built-in Exceptions in Java
1. Checked Exceptions (Compile-time Exceptions)
These exceptions are checked at compile time. The programmer must handle them using try-
catch or declare them using throws.
Examples:
 IOException
 FileNotFoundException
 SQLException
 InterruptedException
Example Program:
import [Link].*;

class Test {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("File not found");
}
}
}

2. Unchecked Exceptions (Runtime Exceptions)


These exceptions occur at runtime and are not checked at compile time. Handling them is
optional.
Examples:
 ArithmeticException
 NullPointerException
 ArrayIndexOutOfBoundsException
 NumberFormatException
Example Program:
class Test {
public static void main(String[] args) {
int a = 10 / 0; // ArithmeticException
}
}
13. Summarize the try and catch statement with example program.
try and catch Statement in Java
In Java, the try and catch blocks are used for exception handling. They help to handle
runtime errors and prevent the program from crashing.
Definition
 try block: Contains code that may cause an exception
 catch block: Handles the exception that occurs in the try block

Syntax
try {
// risky code
} catch (ExceptionType e) {
// handling code
}

Example Program
class Test {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b; // Exception occurs
[Link](c);
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}

[Link]("Program continues...");
}
}
[Link] will you create own exception classes in Java? Give example.
create our own user-defined exceptions to handle application-specific errors. This is done by
extending the Exception class (for checked exceptions) or RuntimeException (for
unchecked).

Steps to Create Custom Exception


1. Create a class that extends Exception
2. Define a constructor to pass error message
3. Use throw keyword to throw the exception
4. Handle it using try-catch
Syntax
class MyException extends Exception {
MyException(String message) {
super(message);
}
}
Example Program
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}

class Test {
public static void main(String[] args) {
int age = 15;

try {
if (age < 18) {
throw new MyException("Not eligible to vote");
}
[Link]("Eligible to vote");
} catch (MyException e) {
[Link]([Link]());
}
}
}
15. Explain garbage collection
Java garbage collection is the process of releasing unused memory occupied by unused
objects. This process is done by the JVM automatically because it is essential for memory
management.
finalize() method
The finalize() method is called by garbage collection thread before collecting object. Its
the last chance for any object to perform cleanup utility.
public class Test
{
public static void main(String[] args)
{
Test t = new Test();
t=null;
[Link]();
}
public void finalize()
{
[Link]("Garbage Collected");
}
}
16. Distinguish between the J Check Box and J Radio Button.
★ JCheckBox:
★ JCheckBox is a GUI component in Java Swing used to select one or more options from a
set of choices.
★ Each checkbox works independently, so selecting one does not affect the others.
★ It does not require any grouping.
★ It is used when the user is allowed to choose multiple values.
★ The state of JCheckBox is either selected (checked) or not selected (unchecked).
★ Example: Selecting hobbies like Reading, Music, Sports, etc.

★ JRadioButton:
★ JRadioButton is used when the user must select only one option from a group.
★ It is always used with a ButtonGroup to ensure mutual exclusion.
★ When one radio button is selected, the others in the same group are automatically
deselected.
★ It is used for single-choice selection.
★ Example: Selecting Gender (Male or Female), Payment method, etc.
Example:
JCheckBox c1 = new JCheckBox("Music");
JCheckBox c2 = new JCheckBox("Sports");

JRadioButton r1 = new JRadioButton("Male");


JRadioButton r2 = new JRadioButton("Female");

ButtonGroup bg = new ButtonGroup();


[Link](r1);
[Link](r2);
17. What are the difference between JButton and JToggleButton? Explain.
JButton:
★ JButton is a GUI component in Java Swing used to perform an action when it is clicked.
★ It is a momentary button, meaning it works only when pressed.
★ It does not maintain any state after clicking.
Class Description
Component An abstract base class that defines any object that can be displayed.
Container An abstract class that defines any component that can contain other
components.
Window The AWT class that defines a window without a title bar or border.
Frame The AWT class that defines a window with a title bar and border.
JFrame The Swing class that defines a window with a title bar and border.
JComponent A base class for Swing components such as JPanel, JButton, JLabel, and
JTextField.
JPanel The Swing class that defines a panel, which is used to hold other components.
JLabel The Swing class that defines a label.
JTextField The Swing class that defines a text field.
JButton The Swing class that defines a button.
★ Each click triggers an event (ActionEvent).
★ It is used for actions like Submit, Save, Login, etc.
★ Example: “Submit” button in a form
JToggleButton:
★ JToggleButton is a GUI component that can switch between two states: ON and OFF.
★ It maintains its state even after clicking.
★ First click → selected (ON), next click → deselected (OFF).
★ It is used when we need a switch-like behavior.
★ It can also be used in groups (like radio buttons) using ButtonGroup.
★ Example: Light ON/OFF button
Example

JButton b = new JButton("Submit");


JToggleButton t = new JToggleButton("ON/OFF");

[Link] the hierarchy of Swing components with an example.


19. Elaborate the purpose of Java utility package.
Purpose of Java Utility Package ([Link])

★ The [Link] package is one of the most important core packages in Java.
★ It provides a large number of utility classes and data structures that help in simplifying
programming tasks.
★ These classes are reusable and reduce the need to write complex code from scratch.
★ Input Handling:
It provides the Scanner class, which is used to take input from the user in a simple way.
Example: reading integers, strings, and other data types from keyboard.
★ Date and Time Operations:
It provides classes like Date and Calendar to work with date and time values.
These are used in applications like scheduling, logging, and time tracking.
★ Random Number Generation:
The Random class is used to generate random numbers.
It is useful in games, simulations, and testing applications.
20. What are inner classes in Java? Explain their different types
 An inner class in Java is a class defined inside another class. It is used to logically
group classes that are closely related and to improve encapsulation and readability.
Types of Inner Classes
(1) Member Inner Class
 Inside class
(2) Static Nested Class
 Static inner class
(3) Local Inner Class
 Inside method
(4) Anonymous Inner Class
 No name, one-time use
Eg:
class Outer {
int x = 10;
// Inner class
class Inner {
void display() {
[Link]("Value of x: " + x);
}
}
}
class Test {
public static void main(String[] args) {
Outer obj = new Outer();
[Link] in = [Link] Inner();
[Link]();
}
}
10 MARKS
[Link] out the basic data types used in java. Explain with suitable example.
1. Primitive Data Types
These are the basic, built-in building blocks of Java and represent simple values directly in
memory. There are eight primitive type
 Integers (Whole Numbers)
o byte: 8-bit signed integer. Range: -128 to 127.
o short: 16-bit signed integer. Range: -32,768 to 32,767.
o int: 32-bit signed integer. Standard choice for whole numbers.
o long: 64-bit signed integer. Used for very large values; must end with an 'L'
(e.g., 100L).
 Floating-Point (Decimals)
o float: 32-bit single-precision. Good for saving memory in large arrays; must
end with an 'f'.
o double: 64-bit double-precision. Default choice for decimal numbers in Java.
2. Non-Primitive (Reference) Data Types
These types refer to objects and store the memory address of the data rather than the actual
value. They can be null and are often user-defined.
 Strings: A sequence of characters.
 Arrays: Collections of elements of the same type (e.g., int[] or String[]).
 Classes: User-defined templates used to create objects.
Eg:
class DataTypesDemo {
public static void main(String[] args) {
// Primitive Data Types
byte b = 10;
short s = 1000;
int i = 50000;
long l = 100000L;
float f = 10.5f;
double d = 20.99;
char c = 'A';
boolean flag = true;
// Non-Primitive Data Types
String str = "Hello Java";
int arr[] = {1, 2, 3, 4}
[Link]("byte value: " + b);
[Link]("short value: " + s);
[Link]("int value: " + i);
[Link]("long value: " + l);
[Link]("float value: " + f);
[Link]("double value: " + d);
[Link]("char value: " + c);
[Link]("boolean value: " + flag);
[Link]("String value: " + str);
[Link]("Array values: ");
for(int x : arr) {
[Link](x + " ");
}
}
}

2. Describe various types of operators with suitable example


Java operators are symbols that are used to perform operations on variables and manipulate
the values of the operands
Types of Operators:
1. Arithmetic Operators
2. Assignment Operators
3. Logical Operators
4. Shift Operators
5. Bitwise Operators
6. Ternary Operators
7. Relational Operators
8. Unary Operators
Arithmetic Operator: Arithmetic operators are used to performing addition, subtraction,
multiplication, division, and modulus. It acts as a mathematical operations
Operator Description Example

+ Adds together two values x+y

- Subtracts one value from another x-y

* Multiplies two values x*y

/ Divides one value by another x/y

% Returns the division remainder x%y


Assignment Operators
Assignment operators are used to assign values to variables

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3
*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

Comparison Operators
Comparison operators are used to compare two values (or variables).
Operator Example

== x == y

!= x != y

> x>y

< x<y

>= x >= y

<= x <= y
Logical Operators
 Logical operators are used to determine the logic between variables or values, by
combining multiple conditions::

Operator Description Example

&& Returns true if both statements are true x < 5 && x < 10

|| Returns true if one of the statements is true x < 5 || x < 4

! Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Eg:
class OperatorsDemo {
public static void main(String[] args) {
int a = 10, b = 5;
[Link]("Add: " + (a + b));
[Link]("Sub: " + (a - b));
[Link]("a > b: " + (a > b));
[Link]("(a > 5 && b < 10): " + (a > 5 && b < 10));
int x = 10;
x += 5;
[Link]("x: " + x);
int y = 5;
[Link]("++y: " + (++y));
[Link]("a & b: " + (a & b));
int max = (a > b) ? a : b;
[Link]("Max: " + max);
}
}
[Link] the different types of if statements available in Java
 if statements are used for decision making. They allow the program to execute certain
blocks of code based on conditions.
Type of Different if statements
[Link] statement
Executes a block only if condition is true.
Eg:
int a = 10;
if (a > 5) {
[Link]("a is greater than 5");
}
[Link]-else Statement
Chooses between two options.
Eg:
int a = 3;
if (a > 5) {
[Link]("Greater");
} else {
[Link]("Smaller");
}
3. if-else-if Ladder
Checks multiple conditions.
Eg:
int marks = 75;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 60) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
Example Program
class IfDemo {
public static void main(String[] args) {
int a = 10, b = 20, marks = 75;
// Simple if
if (a > 5)
[Link]("Simple if");
// if-else
if (a > b)
[Link]("a is greater");
else
[Link]("b is greater");
// if-else-if
if (marks >= 90)
[Link]("Grade A");
else if (marks >= 60)
[Link]("Grade B");
else
[Link]("Grade C");
}
}
}
[Link] the role of static data and static methods in Java. Discuss their benefits
and limitations.
1. Static Data (Static Variables)
Definition
A static variable is shared among all objects of a class. Only one copy exists in memory.

Role of Static Data


 Used for common properties (e.g., college name)
 Saves memory by storing single copy
 Accessible using class name
Example
class Student {
int id;
static String college = "ABC College";

Student(int id) {
[Link] = id;
}
void display() {
[Link](id + " " + college);
}
}
2. Static Methods
Definition
A static method belongs to the class and can be called without creating an object.
Role of Static Methods
 Used for utility functions
 Can access only static variables directly
 Called using class name
Example
class Test {
static void show() {
[Link]("Static method");
}

public static void main(String[] args) {


[Link]();
}
}
Example program
class Student {
int id;
static String college = "ABC College";
Student(int i) {
id = i;
}
static void changeCollege() {
college = "XYZ College";
}
void display() {
[Link](id + " " + college);
}
public static void main(String[] args) {
Student s1 = new Student(1);
Student s2 = new Student(2);
[Link]();
[Link]();
}
}
[Link] the different types of inheritance with example.
Inheritance is an concept where one class (child/subclass) acquires the properties and
methods of another class (parent/superclass).
Types of Inheritance in Java
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
One child class inherits from one parent class.
Example:
class A {
void show() {
[Link]("Class A");
}
}

class B extends A {
void display() {
[Link]("Class B");
}
}

class Test {
public static void main(String[] args) {
B obj = new B();
[Link]();
[Link]();
}
}
2. Multilevel Inheritance
A class inherits from another class, which is also inherited by another class.
Example:
class A {
void show() {
[Link]("Class A");
}
}

class B extends A {
void display() {
[Link]("Class B");
}
}

class C extends B {
void print() {
[Link]("Class C");
}
}
3. Hierarchical Inheritance
Multiple child classes inherit from a single parent class.
Example:
class A {
void show() {
[Link]("Parent class");
}
}
class B extends A {
void display() {
[Link]("Class B");
}
}

class C extends B {
void print() {
[Link]("Class C");
}
}
6. What is constructor? What are different types of constructor with example?
 A constructor in java ia s special method that is used to initialize objects.
 The constructor is called when an object of a class is created
Default Constructor
• Takes no parameters
• Initializes variables with default values

Parameterized Constructor
 A constructor that have parameters called parameterized constructor
 It can have any number of parameters
7. Discuss the various forms of implementing interfaces with example.
 An interface in Java is a collection of abstract methods that a class must implement. It
is mainly used to achieve abstraction and multiple inheritance.

1. Single Interface Implementation

 A class implements only one interface.

interface A {
void show();
}

class Test implements A {


public void show() {
[Link]("Single Interface");
}

public static void main(String[] args) {


Test t = new Test();
[Link]();
}
}

[Link] Interface Implementation

 A class implements more than one interface.

interface A {
void show();
}

interface B {
void display();
}

class Test implements A, B {


public void show() {
[Link]("Interface A");
}

public void display() {


[Link]("Interface B");
}

public static void main(String[] args) {


Test t = new Test();
[Link]();
[Link]();
}
[Link] Inheritance
One interface extends another [Link]:
interface A {
void show();
}

interface B extends A {
void display();
}

class Test implements B {


public void show() {
[Link]("From A");
}

public void display() {


[Link]("From B");
}
}
[Link] thread & life cycle of thread
The life cycle of a thread in Java refers to the various states of a thread goes through. For
example, a thread is born, started, runs, and then dies. Thread class defines the life cycle
and various states of a thread.

States of a Thread Life Cycle in Java

 New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it completes
its task or otherwise terminates.
 Eg program
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
}

public static void main(String[] args) {


MyThread t = new MyThread();
[Link](); // start thread
}
}
[Link] the concept of deadlock in multithreaded programming.
A deadlock is a situation in multithreading where two or more threads are blocked
forever, waiting for each other to release resources. As a result, the program stops
progressing.

2. How Deadlock Occurs


Deadlock happens when:
 Thread 1 holds Resource A and waits for Resource B
 Thread 2 holds Resource B and waits for Resource A
Both threads wait indefinitely → no execution continues
3. Conditions for Deadlock (Necessary Conditions)
1. Mutual Exclusion – Resources cannot be shared
2. Hold and Wait – Thread holds one resource and waits for another
3. No Preemption – Resource cannot be taken forcibly
4. Circular Wait – Circular dependency between threads

Example Program
class Test {
public static void main(String[] args) {

final String A = "Lock1";


final String B = "Lock2";

Thread t1 = new Thread(() -> {


synchronized(A) {
[Link]("Thread 1 locked A");

synchronized(B) {
[Link]("Thread 1 locked B");
}
}
});

Thread t2 = new Thread(() -> {


synchronized(B) {
[Link]("Thread 2 locked B");
synchronized(A) {
[Link]("Thread 2 locked A");
}
}
});

[Link]();
[Link]();
}
}

[Link] the basic concept of Event Delegation Model (EDM).


Event Delegation Model is a design model in which an event source (component) generates
an event and delegates it to a listener (handler) for processing.
(1) Event Source
 The component that generates the event
 Example: Button, TextField
(2) Event Object
 Represents the event that occurred
 Example: ActionEvent, MouseEvent
(3) Event Listener
 Interface that receives and handles the event
 Example: ActionListener, MouseListener
Eg:
import [Link].*;
import [Link].*;

class Demo extends Frame implements ActionListener {

Button b;

Demo() {
b = new Button("Click Me");
[Link](100,100,80,30);

[Link](this);

add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


[Link]("Button Clicked");
}

public static void main(String[] args) {


new Demo();
}
}
11. Discuss about handling mouse and keyboard events
In Java, mouse and keyboard events are handled using the Event Delegation Model
(EDM). These events are part of AWT/Swing event handling, where listeners are
used to detect and respond to user actions.
1. Mouse Events in Java
Mouse events are generated when a user interacts with the mouse (click, move, press,
release, etc.).
Mouse Event Classes and Interfaces
 MouseListener → for click events
 MouseMotionListener → for movement events
 MouseEvent → event object
Common Mouse Methods
 mouseClicked()
 mousePressed()
 mouseReleased()
 mouseEntered()
 mouseExited()
Keyboard Events in Java
Keyboard events are generated when a key is pressed, released, or typed.
Keyboard Event Classes and Interfaces
 KeyListener → interface for keyboard events
 KeyEvent → event object
Common Key Methods
 keyPressed()
 keyReleased()
 keyTyped()
Eg program
import [Link].*;
import [Link].*;
class EventDemo extends Frame implements MouseListener, KeyListener {
EventDemo() {
addMouseListener(this);
addKeyListener(this);
setSize(300, 300);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed");
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new EventDemo();
}
}
12. Explain the role of containers in Swing
A container in Swing is a component that is used to store and organize other GUI
components.
Types of Containers
(1) Top-Level Containers
These are main windows of a Swing application:
 JFrame → main window
 JDialog → dialog box
 JApplet → applet container
Example:
import [Link].*;
class Demo {
public static void main(String[] args) {
JFrame f = new JFrame("Swing Container");

JButton b = new JButton("Click Me");

[Link](b); // adding component to container


[Link](300, 200);
[Link](true);
}
}
(2) Intermediate Containers
Used inside top-level containers to organize components:
 JPanel
 JScrollPane
 JTabbedPane
Example Program :
import [Link].*;
class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("Container Example");
JLabel label = new JLabel("Hello Swing");
JButton button = new JButton("Click");
[Link](label);
[Link](button);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
13. Examine the methods used for collection and iterator interface
Iterator interface
The Iterator interface of the Java collections framework allows us to access elements of a
collection. It has a subinterface ListIterator.
Methods of Iterator
The Iterator interface provides 4 methods that can be used to perform various operations on
elements of collections.
 hasNext() - returns true if there exists an element in the collection
 next() - returns the next element of the collection
 remove() - removes the last element returned by the next()
 forEachRemaining() - performs the specified action for each remaining element of the
collection
Collection Interface

 The Collection interface is the root interface of the Java collections framework.
 There is no direct implementation of this interface. However, it is implemented
through its subinterfaces like List, Set, and Queue.
Methods of Collection

The Collection interface includes various methods that can be used to perform
different operations on objects. These methods are available in all its subinterfaces.

 add() - inserts the specified element to the collection


 size() - returns the size of the collection
 remove() - removes the specified element from the collection
 iterator() - returns an iterator to access elements of the collection
 addAll() - adds all the elements of a specified collection to the collection
 removeAll() - removes all the elements of the specified collection from the collection
 clear() - removes all the elements of the collection

Example Program :
import [Link].*;
class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Java");
[Link]("Python");
[Link]("C++");
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
14. Discuss the use and advantages of adapter classes in Java’s event-handling
mechanism.
 An adapter class is a predefined class in Java that implements a listener interface and
provides empty method bodies, so that programmers can override only the required
methods.

Need for Adapter Classes


MouseListener → 5 methods
KeyListener → 3 methods
Advantages of Adapter Classes
(1) Reduces Code Complexity
No need to implement all methods of an interface.
(2) Saves Time
Only required methods are overridden.
(3) Improves Readability
Code becomes cleaner and easier to understand.
(4) Simplifies Event Handling
Useful for interfaces with many methods.
(5) Increases Productivity
Developers can focus only on required functionality.
Eg Program :
import [Link].*;
import [Link].*;
class Demo extends Frame {
Demo() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new Demo();
}
}
1. Write a java program to find the sum of the digits of a given integer.
import [Link];
class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
int sum = 0;
while (num != 0) {
sum = sum + (num % 10); // get last digit
num = num / 10; // remove last digit
}

[Link]("Sum of digits = " + sum);


}
}
2. Write a java program to count the number of vowels in the given string.
public class VowelCount {
public static void main(String[] args) {
String s = new Scanner([Link]).nextLine().toLowerCase();
int c = 0;

for(char ch : [Link]())
if("aeiou".indexOf(ch) != -1) c++;

[Link](c);
}
}
3. Write a java program to illustrate implementing interfaces.
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
4. Write a java program to find the value of n! where n is a given integer
import [Link].*;

public class Factorial {


public static void main(String[] args) {
int n = new Scanner([Link]).nextInt();
int fact = 1;

for(int i = 1; i <= n; i++)


fact *= i;

[Link](fact);
}
}

You might also like