Java Notes Old Ques
Java Notes Old Ques
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;
}
// body
class Test {
static void show() {
[Link]("Hello");
} }
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";
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};
class Student { }
Unit – 3
22. Give the example for Runnable interface.
Ans: class MyThread implements Runnable {
[Link]("Thread running");
}
[Link]();
Unit – 4
31. Define: “Swing”.
Ans: Java GUI toolkit for building applications. Platform
independent.
Provides rich components.
Unit – 5
38. Comment on Enumeration.
Ans:
[Link] to iterate collection
elements.
[Link] with legacy classes like
Vector.
[Link] methods like hasMoreElements().
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) {
[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);
float f = 10.5f;
double d = 20.99;
char c = 'A';
boolean flag = true;
// Output
[Link]("byte value: " + b);
[Link]("short value: " + s);
[Link]("int value: " + i);
[Link]("long value: " + l);
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]();
}
}
class addition
[Link] (a+b);
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");
}
}
}
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).
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");
★ 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 + " ");
}
}
}
= 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::
&& Returns true if both statements are true x < 5 && x < 10
! 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.
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");
}
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.
interface A {
void show();
}
interface A {
void show();
}
interface B {
void display();
}
interface B extends A {
void display();
}
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");
}
Example Program
class Test {
public static void main(String[] args) {
synchronized(B) {
[Link]("Thread 1 locked B");
}
}
});
[Link]();
[Link]();
}
}
Button b;
Demo() {
b = new Button("Click Me");
[Link](100,100,80,30);
[Link](this);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
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.
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.
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].*;
[Link](fact);
}
}