[Go to site: main page, start]

0% found this document useful (0 votes)
7 views28 pages

Java Programming Language Features Explained

The document outlines the features of the Java programming language, emphasizing its simplicity, object-oriented nature, platform independence, security, robustness, multithreading capabilities, high performance, and support for distributed applications. It also explains the components of the Java platform, including JDK, JRE, and JVM, and provides examples of Java program structure, variable declaration rules, arithmetic operators, type casting, input/output streams, and loop statements. Additionally, it discusses the importance of constants and variables in programming, as well as the different types of operators and data types supported in Java.
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)
7 views28 pages

Java Programming Language Features Explained

The document outlines the features of the Java programming language, emphasizing its simplicity, object-oriented nature, platform independence, security, robustness, multithreading capabilities, high performance, and support for distributed applications. It also explains the components of the Java platform, including JDK, JRE, and JVM, and provides examples of Java program structure, variable declaration rules, arithmetic operators, type casting, input/output streams, and loop statements. Additionally, it discusses the importance of constants and variables in programming, as well as the different types of operators and data types supported in Java.
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

1. Explain features of Java Programming Language. 1.

JRE (Java Runtime Environment) – Used to run Java programs


Java is a very popular and powerful programming language. It is designed to be 2. JVM (Java Virtual Machine) – Executes Java bytecode
simple, secure, and platform independent. Some important features of Java are: 3. Compiler (javac) – Converts .java file into .class file
1. Simple 4. Interpreter
Java is easy to learn. It removes complex features like pointers, multiple 5. Debugger
inheritance (in classes), and memory management by the programmer. This makes 6. Java libraries and tools
Java programming safer and cleaner. JDK is required by developers because it includes tools for building applications.
2. Object-Oriented JVM (Java Virtual Machine)
Java follows the principles of object-oriented programming such as classes, JVM is a virtual machine that runs Java bytecode. It is available for each
objects, inheritance, polymorphism, abstraction, and encapsulation. This makes operating system, like Windows JVM, Linux JVM, Mac JVM, etc.
the program modular and reusable. Important functions of JVM:
3. Platform Independent (Write Once, Run Anywhere) 1. Loads Java bytecode
Java programs run on the JVM, so they do not depend on any operating system. A 2. Verifies code for security
program written on Windows can run on Linux or Mac without any change. This 3. Executes the code line by line
feature makes Java very powerful. 4. Provides memory management
4. Secure 5. Performs garbage collection
Java avoids pointers, uses bytecode verification, has automatic memory Working:
management, and provides a security manager. These features protect Java  Java file (.java) → compiled by javac → creates bytecode (.class)
programs from viruses and attacks.  JVM reads .class file and converts bytecode into machine code of that
5. Robust particular OS.
Java focuses on error handling and memory management. It provides automatic Because of JVM, Java becomes platform independent.
garbage collection, exception handling, and strong type checking to make
programs stable and reliable. 3. Explain with an example the structure of a Java Program.
6. Multithreaded A Java program follows a specific structure. It contains class definition, main
Java supports multithreading, which means multiple tasks (threads) can run at the method, statements, and brackets. Every Java program must have at least one class
same time. This improves performance in games, animations, and real-time and a main() method.
applications. Basic structure of a Java program:
7. High Performance import [Link].*;
Java uses Just-In-Time (JIT) compiler, which converts bytecode to machine code class Example
quickly. This increases the speed and performance of Java applications. {
8. Distributed public static void main(String args[])
Java supports networking easily. Classes in [Link] allow programs to {
[Link]("Hello Java");
communicate over networks and build distributed applications. }
}
2. Explain JDK & JVM in detail. Explanation of structure:
Java platform is mainly built using 3 components: JDK, JRE, and JVM. Out of 1. Import statements
these, JDK and JVM are the most important. These are used to include predefined classes from Java packages.
JDK (Java Development Kit) Example: import [Link];
JDK is a complete software package used for developing Java applications. It 2. Class Declaration
contains everything needed for writing, compiling, and running Java programs. Every program must have a class. The filename must match the class
Components of JDK:
name. Rules for declaring a variable in Java:
Example: class Example 1. A variable must start with a letter, underscore (_), or dollar symbol ($).
3. Main Method Example: age, _id, $value
The main method is the entry point of a Java program. 2. A variable cannot start with a digit.
Syntax: public static void main(String args[]) Example: 1age (invalid)
4. Statements inside main() 3. Variable names cannot contain spaces.
All program logic is written inside the main method. Example: student name (invalid)
Example: [Link]("Hello Java"); 4. Only letters, digits, underscore, and dollar symbols are allowed.
5. Curly Braces 5. Variable names should not be Java keywords.
Braces { } define the starting and ending of class and methods. Example: int, class, static (invalid)
6. Variable names are case-sensitive.
4. Write Java Program to demonstrate all the arithmetic operators. Example: Age and age are different.
Arithmetic operators are used to perform mathematical operations on variables 7. Variable names should be meaningful to improve code readability.
and values. Java supports the following arithmetic operators: Example: totalMarks is better than tm.
1. Addition (+) – Used to add two values. 8. A variable must be declared before it is used in the program.
2. Subtraction (-) – Used to subtract one value from another. 9. A variable can also be declared and initialized in the same line.
3. Multiplication (*) – Used to multiply two values. Example: int x = 10;
4. Division (/) – Used to divide one value by another. 10. Java follows strict type checking, so the type of variable decides the type
5. Modulus (%) – Gives the remainder after division. of data it will store.
6. Increment (++) – Increases value by 1. These rules help the compiler understand how much memory to reserve and how
7. Decrement (--) – Decreases value by 1. to process the data.
Arithmetic operators are very important in calculations, expressions, and formulas
used in Java programs. These operators always work on numeric data types like 6. Explain with example type casting and conversion in Java.
int, float, double, etc. Java strictly checks the data types before performing Type casting and type conversion are used when we want to convert one data type
operations to avoid errors. Arithmetic operators also follow a specific order of into another. Java supports two types of conversions:
execution known as operator precedence.
Short Java Program: 1. Implicit Conversion (Automatic Type Conversion)
class Test { This happens automatically when we assign a smaller data type to a larger data
public static void main(String args[]) { type.
int a = 10, b = 3;
[Link](a + b); Java does this conversion safely without loss of data.
[Link](a - b); Examples of automatic conversion:
[Link](a * b); byte → short → int → long → float → double
[Link](a / b); This is also called widening conversion because data is moved to a bigger
[Link](a % b);
}
container.
} Example:
int x = 10;
5. Write rules to declare a variable in Java. double y = x; // automatic conversion
A variable is a name given to a memory location where data is stored. Java is a
strongly typed language, which means every variable must be declared with a 2. Explicit Type Casting (Manual Conversion)
specific data type before use. Variable declaration tells the compiler about the This is done manually by the programmer.
type of data the variable will store. Used when converting a larger type into a smaller type.
Examples: int result = MAX - x;
double → float → long → int → short → byte [Link](result);
This is called narrowing conversion because data moves to a smaller container. }
Narrowing may cause loss of data, so Java needs explicit casting. }
Example:
double a = 10.75; 8. Explain Input and Output Stream functions in Java.
int b = (int) a; // manual type casting In Java, streams are used to perform input and output operations. A stream is
simply a sequence of data.
Short Java Program for Type Casting: Input Stream:
class CastDemo { • Used to read data from an input device (keyboard, file, network, etc.).
public static void main(String args[]) { • Data flows from source to program.
int x = 10;
double y = x; // implicit • Common classes: InputStream, FileInputStream, BufferedInputStream, Scanner.
double p = 12.9; • It reads data byte-by-byte or line-by-line.
int q = (int)p; // explicit Output Stream:
[Link](y); • Used to send data from the program to an output device (console, file, network,
[Link](q);
}
etc.).
}.
• Data flows from program to destination.
• Common classes: OutputStream, FileOutputStream, PrintStream,
BufferedOutputStream.
7. How constants and variables are important in developing a program?
Java I/O is based on the concept of:
Explain with example.
Constants and variables are fundamental building blocks of any programming • Byte Streams: Read/write raw bytes (images, audio).
language. They help a programmer store, retrieve, and manipulate data during • Character Streams: Read/write characters (text data).
program execution. Keyboard Input Example (Short):
Importance of variables: import [Link].*;
• A variable stores data that can change during runtime. class InputDemo {
• They let the program take dynamic input and process it in different ways. public static void main(String[] args) {
• Without variables, a program cannot hold user input, cannot perform Scanner sc = new Scanner([Link]);
calculations, and cannot store temporary or final results. int x = [Link]();
• Variables make programs flexible, reusable, and easy to update. [Link](x);
Importance of constants: }
• A constant is a fixed value that cannot be changed once assigned. }
• Constants help avoid accidental modification of important values such as PI, tax File Output Example (Short):
rates, conversion rates, etc. import [Link].*;
• They improve code readability and reduce errors. class OutputDemo {
• Constants make maintenance easy because if a fixed value needs an update, you public static void main(String[] args) throws Exception {
change it in only one place. FileOutputStream f = new FileOutputStream("[Link]");
Small Example: [Link](65);
class Demo { [Link]();
public static void main(String[] args) { }
final int MAX = 100; // constant }
int x = 20; // variable
9. List and explain LOOP statements in Java. ==, !=, >, <, >=, <=
Java supports three main loop statements that help repeat a block of code multiple They return true or false.
times: 3. Logical Operators
1. for loop Used to combine multiple conditions.
Used when the number of iterations is already known. && (AND), || (OR), ! (NOT)
Structure: initialization; condition; increment/decrement Useful in decision-making and boolean expressions.
The loop stops when the condition becomes false. 4. Assignment Operators
Example: Used to assign values to variables.
for(int i=1; i<=5; i++){ =, +=, -=, *=, /=, %=
[Link](i); They can also update a variable’s value in one step.
} 5. Increment/Decrement Operators
2. while loop Increase or decrease value by 1.
Used when the number of iterations is unknown but depends on a ++ and --
condition. Used for loop counters and quick updates.
The condition is checked before loop execution. 6. Bitwise Operators
Example: Used for bit-level operations.
int i = 1; &, |, ^, ~, <<, >>, >>>
while(i <= 5){ Applied mostly in system-level programming.
[Link](i); 7. Conditional (Ternary) Operator
i++; Short form of if-else.
} (condition ? value1 : value2)
3. do-while loop 8. Unary Operators
Similar to while loop, but it executes the block at least once even if the Operate on a single operand.
condition is false. +, –, ++, --, !
Example: Used for positive/negative values and boolean negation.
int i = 1; 9. Instanceof Operator
do{ Checks whether an object belongs to a class or not.
[Link](i); Example short code:
i++; class OpDemo {
}while(i <= 5);. public static void main(String[] args) {
int a = 10, b = 5;
10. Explain different types of operators supported in Java. [Link](a + b);
Operators in Java are special symbols used to perform operations on variables and }
values. They help in calculations, decision-making, comparisons, and other }
program actions.
Java supports the following main types of operators: 11. What are variables? Write rules for naming variables with example.
1. Arithmetic Operators A variable is a named memory location used to store data that may change during
Used for mathematical calculations. program execution. Variables allow a program to accept input, perform
+, –, *, /, % calculations, and store results.
These operators work on numeric types and return numeric results. Rules for naming variables:
2. Relational Operators • The name must start with a letter, underscore (_), or dollar ($).
Used to compare two values. • It cannot start with a digit.
• It should not contain spaces. class SwitchDemo {
• Java variable names are case-sensitive (age and Age are different). public static void main(String[] args) {
• It cannot use Java keywords (int, class, static, etc.). int day = 3;
• Use meaningful names to increase readability. switch(day){
• Can contain letters, digits, and underscores. case 1: [Link]("Mon"); break;
Examples: case 2: [Link]("Tue"); break;
int age = 20; case 3: [Link]("Wed"); break;
float marks_10 = 88.5f; default: [Link]("Invalid");
String userName = "Ajay"; }
Wrong examples (not allowed): }
int 1num; }
int my value;
int class; 13. List and explain different datatypes in Java.
Short example program: Datatypes in Java define what type of data a variable can store. Java is a strongly
class VarDemo { typed language, meaning every variable must have a declared datatype before use.
public static void main(String[] args) { Datatypes ensure that memory is used correctly and prevent errors by restricting
int x = 10; invalid operations.
[Link](x); Java datatypes are mainly classified into two categories:
} 1. Primitive Datatypes
} These are basic built-in types, stored directly in memory and faster in
execution.
12. Explain switch statement with syntax and example. • byte – 1 byte, stores small integers (-128 to 127).
The switch statement is used to make decisions based on multiple possible values • short – 2 bytes, stores medium integers.
of a variable. It is an alternative to long if-else chains. • int – 4 bytes, commonly used for whole numbers.
It compares the value of a variable with different case labels. When a match is • long – 8 bytes, stores large integers.
found, the corresponding block runs. • float – 4 bytes, stores decimal numbers with single precision.
Key points: • double – 8 bytes, stores decimal numbers with high precision.
• Works with int, char, String, and enum. • char – 2 bytes, stores a single character (Unicode).
• Each case must end with break to stop fall-through. • boolean – 1 bit, stores true or false.
• default case runs when no case matches. 2. Non-Primitive Datatypes
Syntax: These are complex datatypes created by users or Java itself.
switch(variable){ • String – sequence of characters.
case value1: • Arrays – collection of similar datatype values.
statements; • Class & Objects – used for OOP programming.
break; • Interface – similar to a class but contains abstract methods.
case value2: Example:
statements; int age = 20;
break;
double price = 99.5;
default: char grade = 'A';
statements; String name = "Ajay";
}
Short example:
14. Write a Java program to compute roots of a quadratic equation where input int t=a[j]; a[j]=a[j+1]; a[j+1]=t;
is taken from keyboard at runtime. }
Quadratic equation form: }
ax² + bx + c = 0 }
Roots depend on discriminant (D): for(int x : a) [Link](x+" ");
D = b² – 4ac }
• If D > 0 → two real roots }
• If D = 0 → one real root
• If D < 0 → complex roots 16. List and explain loops and decision-making statements in Java.
Short code: In Java, loops and decision-making statements control the flow of a program.
import [Link].; They help in executing statements repeatedly or choosing actions based on
class QuadRoots { conditions.
public static void main(String[] args) { Decision-Making Statements
Scanner sc = new Scanner([Link]); These statements allow the program to choose one path from multiple options
double a = [Link](); based on a condition.
double b = [Link](); 1. if statement
double c = [Link](); Executes a block only when the condition is true.
double d = bb - 4ac; 2. if-else statement
[Link]("Root1: " + ((-b + [Link](d)) / (2a))); Provides two paths: one for true condition and one for false.
[Link]("Root2: " + ((-b - [Link](d)) / (2a))); 3. else-if ladder
} Used when multiple conditions need to be checked one after another.
} 4. switch statement
Used when a variable is compared with many constant values (cases).
15. Write a Java program to sort numbers using bubble sort Algorithm. Useful for menu-driven programs.
Bubble sort is a simple comparison-based sorting algorithm. Loop Statements
It works by repeatedly comparing adjacent elements and swapping them if they Loops are used when a block needs to run repeatedly.
are in the wrong order. 1. for loop
How Bubble Sort works: Used when number of iterations is known.
1. Compare first two elements → swap if needed Example: iterating from 1 to 10.
2. Move to next pair 2. while loop
3. After each pass, the largest element moves to the end Used when number of iterations is unknown but depends on a condition.
4. Repeat passes until all elements are sorted 3. do-while loop
Time Complexity: Executes body at least once before checking the condition.
• Best: O(n) 4. Enhanced for loop
• Average/Worst: O(n²) Used for iterating over arrays or collections easily.
Short code: These constructs help in building logical programs, reducing repetition, and
class BubbleSort { improving performance.
public static void main(String[] args) {
int a[] = {5, 1, 4, 2, 8}; 17. How is array created in Java?
for(int i=0;i<[Link]-1;i++){ An array in Java is created using the new keyword.
for(int j=0;j<[Link]-i-1;j++){ Java arrays are objects stored in continuous memory.
if(a[j] > a[j+1]){ To create an array, two steps are needed:
1. Declare the array 1. Primitive Datatypes
This tells Java what type of elements the array will store. These are basic built-in datatypes provided by Java. They are stored directly in
Example: memory and work fast. There are 8 primitive datatypes.
int a[]; a) byte
2. Create the array in memory using new Size: 1 byte
Example: Range: -128 to 127
a = new int[5]; Example:
This creates an integer array of size 5. byte age = 20;
All array elements get default values (0 for int, 0.0 for double, false for boolean, b) short
null for objects). Size: 2 bytes
Full example: Example:
int a[] = new int[5]; short distance = 5000;
c) int
18. What is array? How can we initialize array in Java? Size: 4 bytes (most commonly used for numbers)
Array definition Example:
An array is a collection of similar datatype elements stored in continuous memory. int marks = 450;
It allows storing multiple values under one variable name and accessing them d) long
using index numbers (0,1,2,...). Size: 8 bytes
Arrays help reduce memory usage and improve program organization. Example:
Array initialization long population = 90000000L;
There are two types of initialization: e) float
1. Static Initialization (direct initialization) Size: 4 bytes, single precision decimal
Values are given at the time of declaration. Example:
Example: float price = 99.5f;
int a[] = {10, 20, 30, 40}; f) double
2. Dynamic Initialization (assigning after creating) Size: 8 bytes, high precision decimal
First create the array, then assign values. Example:
Example: double salary = 56000.75;
int a[] = new int[4]; g) char
a[0] = 10; Size: 2 bytes, stores a single character
a[1] = 20; Example:
a[2] = 30; char grade = 'A';
a[3] = 40; h) boolean
Both techniques are widely used depending on the program’s requirement. Stores true or false
Example:
19. Explain the data types supported by Java with example. boolean isPassed = true;
Datatypes in Java define the type of data a variable can store. Java is a strongly
typed and platform-independent language, so every variable must have a 2. Non-Primitive Datatypes
datatype before use. Datatypes help the compiler understand how much memory These are more complex datatypes created using classes.
to allocate and what operations are allowed on the data. They store references (addresses), not actual data.
Java supports two major categories of datatypes: a) String
Used to store sequence of characters.
Example: In the above example, both classes have a show() method.
String name = "Ajay"; When a Child object calls show(), the child version overrides the parent version.
b) Array Output will be:
Collection of similar datatype. Child class
Example:
int a[] = {10, 20, 30}; 2. Explain with an example interfaces in Java.
c) Class An interface in Java is a complete abstract structure that contains only abstract
Blueprint for objects (OOP). methods (before Java 8) and constants.
Example: class Student {} A class implements an interface to provide the actual method body.
d) Interface Important points:
Used for abstraction. • All methods in interface are abstract by default
Example: interface Animal {} • A class uses implements keyword
These datatypes allow Java to support OOP, modular programs, and strong • Multiple inheritance is possible using interfaces
memory management. • Variables inside interfaces are public, static, and final
• Helps in achieving abstraction and loose coupling
1. Explain concept of method overriding with suitable example. Syntax:
Method overriding is an important feature of runtime polymorphism in Java. interface InterfaceName {
It occurs when a child class provides its own version of a method that is already void method1();
defined in its parent class. }
Key points of method overriding: Example:
• Method name must be same interface Vehicle {
• Method parameters must be same void run();
• Method return type must be same }
• Happens only in inheritance class Car implements Vehicle {
• Object of child class always calls child’s method public void run() {
• Used for dynamic/late binding [Link]("Car is running");
Why overriding is used: }
• To provide specific implementation in subclass }
• To modify the behavior of parent class methods Here, Car class implements the Vehicle interface.
• To achieve runtime polymorphism The method run() must be defined in the Car class because interface methods have
Example: no body.
class Parent { Output:
void show() { Car is running
[Link]("Parent class");
} 3. Explain access specifiers supported by Java in detail.
} Access specifiers (access modifiers) define visibility of classes, methods, and
class Child extends Parent { variables in Java.
void show() { They control from where a class or member can be accessed.
[Link]("Child class"); Java provides four access specifiers:
}
} 1. public
• Accessible from anywhere in the program
• No restriction on access Why method overloading is used:
• Used for widely shared methods • To improve code readability
Example: • To perform similar tasks with different types of inputs
public int age; • To avoid creating unnecessary method names
Example:
2. private class Test {
• Accessible only within the same class void show(int a) {
• Not visible to subclasses or other classes [Link]("Integer: " + a);
• Used for data hiding (encapsulation) }
Example: void show(String s) {
private int salary; [Link]("String: " + s);
}
}
3. protected
Here both methods have the same name show(), but different parameter types.
• Accessible within the same class
Java decides which method to call based on the argument type.
• Accessible in child class (even in different package)
• Not accessible in unrelated classes
5. What is Interface? Why needed?
Example:
Interface definition:
protected void display();
An interface in Java is a completely abstract structure that contains abstract
methods and constants.
4. default (no keyword)
A class implements an interface to provide actual method definitions.
• When no modifier is written
Why interfaces are needed:
• Accessible only within the same package
1. To achieve multiple inheritance (Java classes cannot inherit from
• Not accessible outside package
multiple classes).
Example:
2. To achieve 100% abstraction (before Java 8).
int marks; // default access
3. To define common rules that multiple classes must follow.
4. To increase loose coupling in programs.
Summary Table:
5. To ensure better structure and security.
Modifier Access Level
Example:
public Everywhere
interface Animal {
private Only inside same class
void sound();
protected Same package + subclasses
}
default Same package only
class Dog implements Animal {
public void sound() {
4. Explain method overloading in Java.
[Link]("Dog barks");
Method overloading is a feature in Java where multiple methods have the same
}
name but different parameters.
}
It is an example of compile-time polymorphism, because the compiler decides
Interfaces help in building strong architecture, reusable code, and separating
which method to call based on the arguments.
method specification from implementation.
A method can be overloaded by changing:
• Number of parameters
6. What do you mean by access specifier? Explain the scope of each
• Type of parameters
access specifier.
• Order of parameters
Access specifiers (access modifiers) in Java define visibility of variables,
methods, and classes. 7. Differentiate between Method Overloading and Method Overriding
They decide from where a member can be accessed. Method overloading and method overriding are both polymorphism concepts in
Java has four access specifiers: Java, but they work in different ways.
Method Overloading
1. public • Occurs within the same class
• Highest visibility • Same method name but different parameters
• Accessible from anywhere: same class, same package, outside package • Return type can be same or different
• Used for widely shared code • Used for compile-time polymorphism
Example: • Decided by compiler
public int age; • Helps perform similar tasks with different inputs
Example: show(int a), show(String s)
2. private Method Overriding
• Lowest visibility • Occurs in two different classes (inheritance required)
• Accessible only inside the same class • Same method name, same parameters, same return type
• Not accessible in subclass or outside class • Used for runtime polymorphism
• Used for encapsulation and data hiding • Decided at runtime
Example: • Child class changes the behavior of parent class method
private int salary; Example: Parent’s display() overridden by Child’s display()
Difference Table
3. protected Overloading Overriding
• Accessible in the same class Same class Different classes (inheritance)
• Accessible within the same package
• Accessible in subclasses outside the package Different parameters Same parameters
• Not accessible in unrelated classes Compile-time polymorphism Runtime polymorphism
Example: No inheritance needed Inheritance required
protected void show(); Return type may change Return type must be same

4. default (no keyword) 8. What is inheritance? Write a program in Java to implement single
• When no modifier is written inheritance.
• Accessible only within the same package Inheritance definition:
• Not accessible outside package Inheritance is a core OOP concept where one class (child class) acquires
• Good for package-level control properties and methods of another class (parent class).
Example: It helps in code reusability, organization, and minimizing duplication.
int marks; // default access Types of inheritance in Java:
• Single
Summary Table • Multilevel
Modifier Scope • Hierarchical
public Everywhere (Java does NOT support multiple inheritance through classes)
private Same class only Single inheritance example (short code):
protected Same package + subclasses
default Same package only
class Parent { • Child uses extends keyword
void show() { • Child gets access to parent’s methods and properties
[Link]("Parent class"); • Child can also define its own additional methods
} Advantages of Single Inheritance:
} • Easy to understand
class Child extends Parent { • Reduces code repetition
void display() { • Promotes reusability
[Link]("Child class"); • Helps achieve hierarchical structure
} Example (short code):
} class Animal {
class Test { void eat() {
public static void main(String[] args) { [Link]("Animal eats");
Child c = new Child(); }
[Link](); }
[Link](); class Dog extends Animal {
} void bark() {
} [Link]("Dog barks");
This program shows that Child class inherits show() method from Parent class. }
}
9. Write a program in Java to accept temperature in Celsius through class Test {
keyboard and convert it into Fahrenheit. public static void main(String[] args) {
Formula: Dog d = new Dog();
F = (C × 9/5) + 32 [Link]();
Short code: [Link]();
import [Link].*; }
class TempConvert { }
public static void main(String[] args) { Here, Dog inherits from Animal → This is single inheritance.
Scanner sc = new Scanner([Link]);
double c = [Link](); 11. Write a program in Java illustrating method overloading.
double f = (c * 9/5) + 32; Method overloading means same method name but different parameters.
[Link]("Fahrenheit: " + f); This is used when we want to perform similar actions using different types of
} inputs.
} Short code:
class OverloadDemo {
10. Explain Single Inheritance in Java with example. void show(int a) {
Single inheritance is a type of inheritance where one child class inherits from [Link]("Integer: " + a);
only one parent class. }
It allows the child class to use methods and variables of the parent class without void show(String s) {
rewriting them. [Link]("String: " + s);
}
This helps in code reusability, clean structure, and less duplication.
In single inheritance: public static void main(String[] args) {
• One parent class → One child class OverloadDemo o = new OverloadDemo();
[Link](10);  Easy extension of existing classes
[Link]("Ajay"); Java uses the keyword extends for inheritance.
}
General form:
}
class Child extends Parent {
This shows two show() methods with different parameter types.
// child class code
}
12. Write a program in Java for multiple inheritance using interface.
When a class inherits another:
Java does not support multiple inheritance using classes.
 Child class gets access to fields and methods of parent class
But Java supports multiple inheritance using interfaces, meaning a class can
 Child can add its own methods
implement more than one interface.
 Child can override parent methods if needed
Why interfaces allow multiple inheritance:
Example:
• No method body inside interface → no confusion
class Vehicle {
• Only declarations → child class defines actual implementation
void start() {
Short code (simple and small):
[Link]("Vehicle starts");
interface A {
}
void show();
}
}
class Car extends Vehicle {
interface B {
void drive() {
void display();
[Link]("Car is driving");
}
}
class Test implements A, B {
}
public void show() {
class Test {
[Link]("Show from A");
public static void main(String[] args) {
}
Car c = new Car();
public void display() {
[Link](); // inherited method
[Link]("Display from B");
[Link](); // own method
}
public static void main(String[] args) { }
Test t = new Test(); }
[Link](); This is single inheritance → Car inherits from Vehicle.
[Link]();
}
} 14. Program: Room (length, breadth → area) and Bedroom (height
Here, class Test implements two interfaces → A and B, → volume)
which is multiple inheritance in Java. Program using inheritance:
class Room {
int length, breadth;
13. Explain the concept of inheritance in Java with suitable example. void setData(int l, int b) {
Inheritance is a feature in Java where one class (child/subclass) acquires the length = l;
properties and methods of another class (parent/superclass). breadth = b;
It allows: }
 Reusability of code
int area() {
 Less duplication return length * breadth;
 Better structure and organization }
} [Link]("Show from A");
class Bedroom extends Room { }
int height; public void display() {
void setHeight(int h) { [Link]("Display from B");
height = h; }
}
}
int volume() { class Test {
return length * breadth * height; public static void main(String[] args) {
} Demo d = new Demo();
} [Link]();
class Test { [Link]();
public static void main(String[] args) { }
Bedroom b = new Bedroom(); }
[Link](10, 12); // length, breadth Here, Demo inherits features from both A and B → Multiple inheritance using
[Link](8); // height interfaces.
[Link]("Area = " + [Link]());
[Link]("Volume = " + [Link]());
.
}
} 16. Differentiate final and abstract class in Java.
This demonstrates inheritance: final class
Room → parent, Bedroom → child.  A final class cannot be inherited.
 It is used when we want to restrict inheritance for security or stability.
15. How is multiple inheritance achieved in Java? Explain with  All methods inside final class are implicitly final (cannot be overridden).
example.  Useful when creating utility classes or classes that must not be changed.
Java does NOT support multiple inheritance through classes to avoid Example:
ambiguity (Diamond problem). final class A { }
But Java supports multiple inheritance using interfaces. Here class A cannot be extended.
A class can implement more than one interface, thus achieving multiple
inheritance. abstract class
Syntax:  An abstract class cannot be instantiated, but it can be inherited.
class ClassName implements Interface1, Interface2 {  It may contain abstract methods (methods without body).
// must define all methods of both interfaces  Used to provide a base blueprint for other classes.
}  Helps achieve partial abstraction.
Example: Example:
interface A { abstract class A {
void show(); abstract void show();
}
}
interface B {
void display(); Difference Table
} final class abstract class
class Demo implements A, B { Cannot be inherited Must be inherited
public void show() {
final class abstract class  It is a compile-time polymorphism feature.
 Parameters may differ by:
Cannot contain abstract methods Can contain abstract & normal methods
o Number of arguments
Provides complete implementation Provides partial implementation o Type of arguments
Used for restriction Used for abstraction o Order of arguments
Why Used?
 Gives readability, clean code, and flexibility.
17. Explain the OOP features of Java programming language.  Same logical action with different input types.
Java completely supports Object-Oriented Programming (OOP). Major OOP Example (short code)
features in Java: class Demo {
1. Class & Object void add(int a, int b) { [Link](a+b); }
 Class is a blueprint; object is its real-world instance. void add(double a, double b) { [Link](a+b); }
}
 Example: class Car → object myCar.
Here, both methods are add() but with different parameter types.
2. Encapsulation
 Binding data (variables) and code (methods) together.
 Achieved using private variables + public methods. 19. What are the access specifiers supported by Java? Explain
 Helps in data hiding and security. friendly access specifier in detail.
3. Inheritance Java provides four access specifiers to control the visibility of classes, variables,
 One class acquires properties of another. and methods.
 Promotes code reusability. 1. public
 Example: class Dog extends Animal.  Accessible from anywhere in the program.
4. Polymorphism  No restriction.
 One task performed in different ways.  Example: public class A { }
 Two types: 2. private
o Method Overloading (compile-time)  Accessible only within the same class.
o Method Overriding (runtime)  Provides maximum security.
5. Abstraction  Example: private int x;
 Hiding internal details and showing only functionality. 3. protected
 Achieved via:  Accessible:
o abstract classes o Within the same class
o interfaces o Within the same package
6. Dynamic Binding o In subclasses (through inheritance)
 Method call resolved at runtime. 4. default / friendly (no modifier)
7. Message Passing This is called friendly access or package-level access.
 Objects communicate via method calls.
Friendly Access Specifier (default) in detail
18. Explain the concept of method overloading with example. When no access modifier is written, Java automatically assigns default or
Concept friendly access.
 Method Overloading means multiple methods with same name but Characteristics of Friendly Access
different parameters.  Accessible within the same package only.
 Not accessible from a class present in a different package.
 Useful in package-level grouping where related classes can access each void show() { [Link]("Parent"); }
other freely. }
 It provides moderate security between packages. class B extends A {
Why friendly access is needed? void display() { [Link]("Child"); }
 Helps divide large programs into packages. }
 Ensures only classes inside the same package can access each other. Here:
 Prevents unwanted access from classes of other packages.  Class B inherits method show() from A.
Example  Object of B can access both methods.
class A { // default access
void show() {
[Link]("Default Access");
1. Write Java Program to demonstrate how package is created
} and accessed.
}
This class and method can be accessed only by another class in the same What is a Package?
A package in Java is a way to group related classes, interfaces, and sub-packages.
package.
It helps in:
 Avoiding name conflicts
20. List types of inheritances in Java. Explain any one with  Organizing large projects
example.  Providing access protection
Types of Inheritance in Java  Code reusability
Java supports the following inheritance types: Types of Packages
1. Single Inheritance 1. User-defined package
2. Multilevel Inheritance 2. Built-in packages ([Link], [Link], [Link], etc.)
3. Hierarchical Inheritance Steps to Create and Access a Package
4. Multiple Inheritance (through interfaces) Step 1: Create a folder (ex: mypack)
5. Hybrid Inheritance (through interfaces) Step 2: Create class inside folder and use package keyword
(Note: Java does NOT support multiple inheritance through classes. It Step 3: Compile using javac
is done using interfaces.) Step 4: Access using import keyword
Short Program
Explaining Single Inheritance (with example) File: mypack/[Link]
package mypack;
Concept
 In Single Inheritance, one class extends exactly one parent class. public class Message {
 Child class inherits: public void show() {
[Link]("Hello from package!");
o Variables
}
o Methods }
o Behaviors File: [Link]
 Promotes code reusability and method sharing. import [Link];
Diagram
class Test {
Parent → Child public static void main(String[] args) {
A→B Message m = new Message();
Example (short code) [Link]();
class A { }
}

3. Explain multithreading. How we can assign priority to


2. Explain Applet & its life cycle in detail with suitable
thread?
example. What is Multithreading?
What is an Applet? Multithreading is the process where multiple threads execute independently
An applet is a small Java program that: within a single program.
 Runs inside a web browser or Applet Viewer Features of Multithreading
 Is event-driven  Increases CPU utilization
 Cannot access system resources directly for security reasons  Improves performance
 Uses AWT for GUI  Threads run concurrently
Applets were used for interactive graphics in early Java.  Lightweight compared to processes
 Supports asynchronous execution
Applet Life Cycle Methods Ways to Create Threads
Applet life cycle is controlled by browser or applet viewer. 1. Extending Thread class
1. init() 2. Implementing Runnable interface
o Called once.
o Used to initialize variables, UI components. Thread Priority in Java
2. start() Each thread has a priority from 1 to 10:
o Called every time the applet becomes active.
 Thread.MIN_PRIORITY = 1
o Good for animations or starting threads.
 Thread.NORM_PRIORITY = 5
3. paint(Graphics g)  Thread.MAX_PRIORITY = 10
o Used to draw shapes, text, images on applet screen.
Priority helps the scheduler decide which thread gets more CPU time.
4. stop()
o Called when user moves away from the applet page.
How to Assign Priority
Use the method:
o Used to stop animations or threads.
[Link](value);
5. destroy()
Short Example
o Called before unloading applet from memory. class A extends Thread {
o Used to release resources. public void run() {
[Link]("Running thread");
}
Life Cycle Diagram }
init() → start() → paint() → stop() → destroy()
class Test {
public static void main(String[] args) {
Short Applet Example A t1 = new A();
import [Link].*;
[Link](Thread.MAX_PRIORITY);
import [Link].*;
[Link]();
}
public class Demo extends Applet {
}.
public void paint(Graphics g) {
[Link]("Hello Applet", 50, 50);
}
}
4. Explain use of import statement in Java. 1. Reusability
The import statement in Java is used to include classes and packages in a Ready-made classes reduce coding effort.
program so that we can use them directly without writing the full path. 2. Saves development time
Developers can directly use existing functions.
Why import is needed?
3. Standardization
Java contains thousands of predefined classes inside various packages like:
Provides uniform and consistent method behaviour.
 [Link]
4. Easy to understand and use
 [Link]
Packages are organized logically.
 [Link]
5. Improves program structure
 [Link]
Divides large projects into modules.
Instead of writing full package name every time, we use import.
6. Strong community support
Example without import:
[Link] sc = new [Link]([Link]); API is well documented and supported worldwide.
Example with import:
import [Link]; 6. What do you mean by package? How can we create our own
Scanner sc = new Scanner([Link]);
Types of Import package?
1. Single Class Import Meaning of Package
import [Link]; A package in Java is a collection of related classes, interfaces, and sub-packages.
2. Package Import (Wildcard) It is similar to a folder in a computer which helps to organize files.
import [Link].*;
Purpose of Packages
This imports all classes of the package but not sub-packages.  Group related classes
3. Static Import  Avoid name conflicts
Used to import static members.  Provide controlled access
import static [Link].*;
 Improve code maintenance
Benefits of import  Reusability
 Makes code shorter
 Improves readability Types of Packages
 Avoids writing long package names 1. Built-in packages
([Link], [Link], [Link], [Link] etc.)
2. User-defined packages
5. What are Java API packages? Give its advantages. Created by the programmer.
Java API Packages
Java provides a large collection of pre-built classes grouped into packages. How to Create Our Own Package?
These packages are known as Java API (Application Programming Interface). Step 1: Create a folder
Some common API packages:
Example: mypack
 [Link] – basic classes (String, Math, System)
Step 2: Create a Java file inside the folder
 [Link] – data structures (ArrayList, HashMap, Scanner)
Write the package statement at the top.
 [Link] – input/output classes
Example:
 [Link] – graphics, GUI
File: mypack/[Link]
 [Link] – networking package mypack;
 [Link] – database connectivity
Advantages of Java API Packages public class Hello {
public void show() {
[Link]("Hello Package"); Used to throw an exception manually.
}
} 5. throws
Step 3: Compile the program Used in method declaration to indicate exception possibility.
javac mypack/[Link] Simple Example
Step 4: Use the package in another program try {
import [Link]; int x = 10 / 0;
} catch (Exception e) {
class Test { [Link]("Error: " + e);
public static void main(String[] args) { }
Hello h = new Hello();
[Link]();
} 8. What is thread? Describe the life cycle of thread.
} What is a Thread?
7. What is exception? How can exceptions be handled in Java? A thread is a lightweight subprocess that executes independently.
An exception is an unexpected or abnormal condition that occurs during the It is the smallest unit of execution in Java.
execution of a program. Why Threads are used?
Examples:  To perform multiple tasks simultaneously
 Division by zero  To increase performance
 File not found  For animations, games, file downloading, etc.
 Invalid input Ways to Create Thread
 Array index out of range 1. Extending Thread class
Exceptions stop normal flow of the program, so Java provides a mechanism to 2. Implementing Runnable interface
handle them.
Types of Exceptions Thread Life Cycle
1. Checked Exceptions A thread passes through the following states:
Checked at compile time (IOException, SQLException). 1. New (Created State)
2. Unchecked Exceptions Thread object is created but not started.
Occur at runtime (ArithmeticException, NullPointerException). 2. Runnable State
3. Errors After calling start() method, thread is ready to run.
Serious problems (OutOfMemoryError). 3. Running State
When the scheduler selects the thread, it starts running.
Exception Handling in Java 4. Blocked/Waiting State
Java handles exceptions using try, catch, finally, throw, throws. Thread waits for resources or waits for another thread.
1. try block 5. Terminated (Dead State)
Code that may cause exception is written inside try. Thread finishes execution.
2. catch block Diagram
Used to catch and handle the exception. New → Runnable → Running → Waiting → Running → Terminated
3. finally block
Executed whether exception occurs or not. Good for closing files, database 9. Write a program in Java to handle division by zero
connection. exception.
4. throw
Short Program
class Demo { 3. Static Synchronization
public static void main(String[] args) { Used for static methods.
try {
int a = 10; Short Example
int b = 0; class Test {
int c = a / b; synchronized void display() {
} catch (ArithmeticException e) { [Link]("Synchronized Method");
[Link]("Division by zero not allowed"); }
} }
} Why Synchronization is Needed?
}  To protect shared data
 To avoid race conditions
10. Explain the concept of multithreading. How thread can be  To make multi-threaded programs reliable
synchronized?
If you want the next Java answers, send the next questions.
Concept of Multithreading Samajh gaya Ajay.
Multithreading allows a program to execute multiple tasks at the same time.
Ab se bilkul seedha–simple exam-type answer,
Each task runs in a separate thread.
jitna question me pucha hai sirf utna hi,
Benefits of Multithreading extra why, uses, importance kuch nahi,
 Efficient CPU utilization bold allowed,
 Faster program execution theory long,
 Useful for real-time tasks simple English,
 Complex tasks can run in parallel code chhota.
 Background processing is possible Chal ab me teeno answers wapas sahi format me de raha hoon.
Examples where multithreading is used
 Web servers
 Games
11. Write an applet in Java to display the message "Hello
 Download managers World".
 Video players An applet is a small Java program that runs inside a browser. To display a
 Chat applications message, we override the paint() method and use drawString().
Program:
import [Link].*;
Thread Synchronization import [Link].*;
When multiple threads access a shared resource (like a variable or method),
problems can occur such as: public class HelloApplet extends Applet {
 Inconsistent output public void paint(Graphics g) {
[Link]("Hello World", 50, 50);
 Data corruption }
 Race conditions }
To prevent this, Java provides synchronization.
Synchronization in Java
1. Synchronized Method
A whole method is locked for one thread at a time.
2. Synchronized Block
Only a part of the code is locked.
12. Write an applet that receives three numeric values as public static void main(String[] args) {
A t = new A();
input from the user and then displays the largest of the three [Link]();
}
on the screen. }
This applet reads three numbers using getParameter() and compares them to find This program creates one thread and starts it.
the largest.
Program:
import [Link].*;
14. What is an exception? List any two types of exceptions.
import [Link].*; What is an Exception?
An exception is an unexpected or abnormal condition that occurs during the
public class MaxNumber extends Applet { execution of a program.
int a,b,c;
When an exception occurs, it disrupts the normal flow of the program.
public void init() { In Java, exceptions are objects that describe errors or unusual events.
a = [Link](getParameter("n1")); Java provides a mechanism called exception handling to catch and manage
b = [Link](getParameter("n2")); these errors, so the program can continue running or terminate gracefully.
c = [Link](getParameter("n3"));
}
Types of Exceptions
public void paint(Graphics g) { 1. Checked Exception
int max = (a>b) ? (a>c?a:c) : (b>c?b:c);
 Exceptions that are checked by the compiler at compile-time.
[Link]("Largest: " + max, 50, 50);
}  The programmer must handle these exceptions using try-catch or throws.
}  Example: IOException, FileNotFoundException.
HTML (short): 2. Unchecked Exception
<applet code="[Link]" width=300 height=200>  Exceptions that occur at runtime and are not checked by the compiler.
<param name="n1" value="10">  These usually happen due to programming mistakes.
<param name="n2" value="20">
<param name="n3" value="15">  Example: ArithmeticException, NullPointerException.
</applet> Note: Java also has Errors (like OutOfMemoryError) which are serious problems
and cannot be handled by programs.
13. What do you mean by Thread? Explain the concept of
Ajay bhai, agar chaho mai next question 15, 16… bhi isi full theory + exam-
multithreading with example. style + simple English ready kar du.
A thread is a small independent unit of execution inside a program. Chahiye?
It runs separately and performs a specific task.
Multithreading means running multiple threads at the same time in a single 1. What is event? Explain with an example event-handling in Java.
program. An event is an action performed by the user on a GUI component.
It allows different parts of a program to run concurrently. Examples of events: button click, key press, mouse movement, window closing
Example (short): etc.
class A extends Thread {
public void run() { Event handling is the mechanism used in Java to perform some action when an
[Link]("Thread running"); event occurs.
} Java uses Event Source, Event Listener, and Event Object for handling events.
} In Java, event handling is done using AWT or Swing packages.
class Test { A listener interface is implemented to handle a particular type of event.
Example: Button Click Event  Arranges components from left to right like a paragraph.
import [Link].*;  Used in Applet, Panel.
import [Link].*; Example:
setLayout(new FlowLayout());
class Demo extends Frame implements ActionListener {
Button b; 2. BorderLayout
 Divides container into 5 regions: North, South, East, West, Center.
Demo() { Example:
b = new Button("Click"); setLayout(new BorderLayout());
add(b); 3. GridLayout
[Link](this);
 Divides container into equal rows and columns.
setSize(200,200);
setLayout(new FlowLayout()); Example:
setVisible(true); setLayout(new GridLayout(2,3));
} 4. CardLayout
 Stores multiple components but shows only one at a time.
public void actionPerformed(ActionEvent e) { Example:
[Link]("Button Pressed"); setLayout(new CardLayout());
}
} 5. GridBagLayout
In this program, clicking the button generates an event that is handled by  Flexible layout that arranges components in grid with different sizes.
actionPerformed(). Each layout manager automatically arranges components without manually setting
positions.
2. Write a program in Java to draw and fill a triangle using
graphics class. 4. Write note on Popup Menus & Menu Bars
To draw a filled triangle, we use the paint() method and fillPolygon() of Graphics
Popup Menus
class.
A popup menu is a small menu that appears on user action such as a right-click
Short Program: on a component.
import [Link].*;
import [Link].*; It allows users to select one of the options provided in the menu.
Features of Popup Menus:
public class Triangle extends Applet {  Context-sensitive: Appears according to component or situation.
public void paint(Graphics g) {  Lightweight and easy to use.
int x[] = {50, 150, 100};
int y[] = {150, 150, 50};  Can contain menu items, checkboxes, or submenus.
[Link](x, y, 3); Example Use: Right-click on a text area to show options like Cut, Copy, Paste.
}
}
Menu Bars
This draws a filled triangle using three coordinate points.
A menu bar is a horizontal bar typically placed at the top of a window.
It contains menus which can further contain menu items.
3. Explain types of layout managers with suitable example. Features of Menu Bars:
Java provides layout managers to arrange GUI components automatically in a  Provides organized access to application commands.
container.  Can include File, Edit, View menus.
Types of Layout Managers  Menu items can have action listeners to perform tasks.
1. FlowLayout Difference between Popup Menu & Menu Bar:
Popup Menu Menu Bar Methods to handle events (commonly used):
 actionPerformed(ActionEvent e) → Handles action events (e.g., button
Appears on user action (e.g., right-click) Always visible at the top of window
click).
Context-sensitive Application-wide menu options  keyPressed(KeyEvent e), keyReleased(KeyEvent e),
Lightweight Standard part of GUI keyTyped(KeyEvent e) → Handle keyboard events.
 mouseClicked(MouseEvent e), mouseEntered(MouseEvent e),
mouseExited(MouseEvent e) → Handle mouse events.
5. Explain Panel & give its syntax  windowClosing(WindowEvent e) → Handle window events like closing
Panel in Java a frame.
A Panel is a container in AWT used to hold and group components like buttons, Java provides two approaches for event handling:
labels, text fields, etc. 1. Using Interfaces – Implement listener interface and override its methods.
It allows the organization of components inside a window or frame. 2. Using Adapter Classes – Use adapter classes if we don’t want to
Features of Panel: implement all methods of an interface.
 Can use layout managers for arranging components.
 Helps in modular GUI design. 7. What is a container? Explain frame container and its
 Panels can be nested inside other panels or frames.
Syntax to create a Panel: methods.
Panel p = new Panel(); Container
Adding components: A container in Java is a special type of component that can hold and organize
[Link](component); other GUI components such as buttons, labels, text fields, and panels.
Example Use: Creating a panel with buttons grouped together inside a frame. Containers are used to group components and control their layout inside a
window or applet.
6. What is an event? What methods are available to handle Types of Containers:
events in Java? 1. Top-level containers: Frame, Applet, Dialog
2. Intermediate containers: Panel, ScrollPane
What is an Event?
An event is an action performed by the user on a GUI component or by the
system.
Frame Container
A Frame is a top-level window in Java that provides a space to place
It triggers a response in the program.
components.
Examples of events:
It has a title bar, borders, and close/minimize buttons.
 Button click
 Mouse click or move
Frames are created using the Frame class in AWT.
 Key press
Key Methods of Frame:
 Window closing
1. setSize(width, height) – Sets the size of the frame.
2. setTitle("title") – Sets the title of the frame.
3. setVisible(true/false) – Makes the frame visible or invisible.
Event Handling in Java 4. setLayout(LayoutManager) – Sets the layout manager for arranging
Java provides a mechanism to handle events using event listeners. components.
Event handling allows the program to respond to user actions.
5. add(Component) – Adds a component to the frame.
Components of Event Handling:
6. remove(Component) – Removes a component from the frame.
1. Event Source – The object on which the event occurs (like a button).
7. dispose() – Closes the frame and releases resources.
2. Event Object – Contains information about the event.
Usage: Frame is widely used to create standalone GUI applications in Java.
3. Event Listener – Interface that contains methods to respond to events.
Syntax:
setLayout(new FlowLayout());
8. Discuss menu bars and menus in Java with suitable
example. GridLayout Manager
Menu Bar GridLayout arranges components in a grid of rows and columns.
A menu bar is a horizontal bar that appears at the top of a window. All cells in the grid are of equal size.
It holds menus which can contain menu items, checkboxes, and submenus. Features of GridLayout:
Menu bars help organize commands and options in GUI applications.  Number of rows and columns is fixed.
Menu  Each component occupies one cell.
A menu is a drop-down list of options inside a menu bar.  Components expand to fill the entire cell.
Each menu can contain menu items which the user can select to perform an  Useful for calculators, forms, and table-like layouts.
action. Syntax:
Key Classes in Java: setLayout(new GridLayout(rows, columns));
 MenuBar – Represents the menu bar.
 Menu – Represents a menu in the menu bar. 11. Explain any two methods of Font class
 MenuItem – Represents an item inside a menu. The Font class in Java is used to set the font style, size, and name for text
 CheckboxMenuItem – Represents a menu item with checkbox. displayed in GUI components.
Two common methods:
Example (theory explanation) 1. getFontName()
1. Create a menu bar using MenuBar mb = new MenuBar();  Returns the name of the font as a String.
2. Add a menu to the bar Menu file = new Menu("File");  Example: "Arial", "Times New Roman".
[Link](file); 2. deriveFont(int style, float size)
3. Add menu items to the menu [Link](new MenuItem("Open"));  Creates a new Font object based on existing font with given style
[Link](new MenuItem("Exit")); (PLAIN, BOLD, ITALIC) and size.
4. Attach the menu bar to a frame [Link](mb);  Useful to change font style dynamically.
This creates a File menu with options Open and Exit inside a frame.
12. Write short notes on (i) TextField (ii) Button
Ajay bhai, ye dono answers full-length, paper-ready, exam-style hai.
Agar chaho mai next set of questions 9, 10… bhi isi style ready kar doon. (i) TextField
 A TextField is a GUI component used to accept input from the user.
Ajay bhai, bilkul paper-ready, full-length, simple English answers niche de raha
hoon. Code sirf wahi jab poocha ho.  It can hold a single line of text.
 Common methods:
o getText() – Reads text from TextField.
10. Explain Flow Manager and Grid Manager in Java o setText(String s) – Sets text in TextField.
FlowLayout Manager  Example Use: Entering username or password in a form.
FlowLayout arranges components from left to right in a container, just like
words in a paragraph. (ii) Button
When the row is full, components move to the next line automatically.  A Button is a clickable component that triggers an action when pressed.
Features of FlowLayout:  It is used to perform tasks like Submit, Reset, Exit.
 Components are arranged horizontally by default.  Common methods:
 Alignment can be left, center, or right.
 Useful for small windows or panels with few components.
o addActionListener() – Attaches an event listener to handle 15. Define Event Handling. List the different situations in
clicks.
which 'Action Event' is generated
o setLabel() – Sets the text displayed on the button.
 Buttons are essential in almost all GUI programs for user interaction. Event Handling
Event Handling is a mechanism in Java to respond to user actions on GUI
components like buttons, checkboxes, text fields, etc.
13. Write a program in Java to draw and fill a rectangle using It allows a program to perform specific tasks when an event occurs.
Graphics Class Key Components:
To draw and fill a rectangle in Java, we use the Graphics class methods 1. Event Source – Object on which the event occurs.
drawRect() and fillRect() inside the paint() method of Applet or Frame. 2. Event Object – Provides details about the event.
Short Program: 3. Event Listener – Interface with methods to handle events.
import [Link].*;
import [Link].*;
Action Event
public class RectangleDemo extends Applet { An Action Event occurs when the user performs an action on a component.
public void paint(Graphics g) { It is generated for components that support user actions like clicking or pressing
[Link](50, 50, 150, 100); // Draw rectangle outline Enter.
[Link](250, 50, 150, 100); // Draw filled rectangle
}
Situations in which Action Event is generated:
} 1. Clicking a Button.
 drawRect(x, y, width, height) draws the rectangle outline. 2. Selecting a Menu Item.
 fillRect(x, y, width, height) fills the rectangle with color. 3. Pressing Enter in a TextField.
4. Selecting a CheckboxMenuItem.
Method used to handle Action Event:
14. Write AWT application to display an image  actionPerformed(ActionEvent e) in the ActionListener interface.
To display an image in Java, we use AWT classes Image and Graphics.
Images can be loaded using getImage() method and drawn using drawImage().
16. What is popup menu? Write how to create it
Short Program:
import [Link].*; Popup Menu
import [Link].*; A popup menu is a small menu that appears when the user performs a specific
action, usually a right-click on a component.
public class ImageDemo extends Applet {
Image img; It is context-sensitive, meaning it shows options based on the component or
situation.
public void init() { Steps to Create a Popup Menu in Java:
img = getImage(getDocumentBase(), "[Link]"); 1. Create a PopupMenu object:
} PopupMenu pm = new PopupMenu("Options");
public void paint(Graphics g) {
2. Add menu items to the popup menu:
[Link](new MenuItem("Cut"));
[Link](img, 50, 50, this);
[Link](new MenuItem("Copy"));
}
[Link](new MenuItem("Paste"));
}
 getImage() loads the image from file or URL.
3. Add the popup menu to a component (like Frame or Panel):
[Link](pm);
 drawImage() displays it on the applet.
4. Handle events using ActionListener to perform actions when a menu item
is selected.
Usage: Commonly used in text editors for actions like Cut, Copy, Paste.
 If the row is full, components move to the next line automatically.
17. What is AWT? Write a program in Java for drawing and  Components can be aligned as LEFT, CENTER, or RIGHT.
 It is default layout for Panel in Java.
filling a polygon Syntax:
AWT (Abstract Window Toolkit) setLayout(new FlowLayout());
AWT is a Java package used to create Graphical User Interface (GUI) Example Use: Arranging buttons, labels, and text fields in a small panel or frame.
applications. .
It contains classes for windows, buttons, labels, text fields, panels, menus,
graphics, and events. 19. Write a Java program to draw line, rectangle, fill
Polygon Drawing and Filling in Java
rectangle, circle and oval
 Use Graphics class inside paint() method.
 drawPolygon() draws the outline of a polygon. To draw basic shapes in Java, we use the Graphics class inside the paint()
 fillPolygon() fills the polygon with color. method of an Applet or Frame.
Short Program: Methods commonly used:
import [Link].*;  drawLine(x1, y1, x2, y2) – Draws a line
import [Link].*;  drawRect(x, y, width, height) – Draws rectangle outline
 fillRect(x, y, width, height) – Fills rectangle with color
public class PolygonDemo extends Applet {
public void paint(Graphics g) {  drawOval(x, y, width, height) – Draws oval outline
int x[] = {50, 150, 200, 100};  fillOval(x, y, width, height) – Fills oval with color
int y[] = {50, 50, 150, 150}; Short Program:
[Link](x, y, 4); // Draw outline import [Link].*;
[Link](x, y, 4); // Fill polygon import [Link].*;
}
} public class ShapesDemo extends Applet {
 x[] and y[] store coordinates of vertices. public void paint(Graphics g) {
 The third parameter is the number of points. [Link](50, 50, 150, 50); // Line
[Link](50, 70, 100, 50); // Rectangle
[Link](200, 70, 100, 50); // Filled Rectangle
18. What are different types of Layout managers? Explain any [Link](50, 150, 80, 80); // Circle
[Link](200, 150, 100, 50); // Oval
one in detail }
Types of Layout Managers }
1. FlowLayout – Arranges components horizontally like a paragraph.
2. BorderLayout – Divides container into North, South, East, West, and 20. Explain any two layout managers with suitable example
Center. 1. FlowLayout
3. GridLayout – Arranges components in rows and columns of equal size.  Arranges components horizontally like text in a paragraph.
4. CardLayout – Shows one component at a time, like cards.  Automatically moves components to the next line if the row is full.
5. GridBagLayout – Flexible layout with rows and columns of different  Can be aligned LEFT, CENTER, or RIGHT.
sizes. Syntax:
6. BoxLayout – Arranges components vertically or horizontally in a box. setLayout(new FlowLayout());
Example: Placing buttons and labels in a panel.
FlowLayout in Detail
 FlowLayout arranges components from left to right in a container. 2. GridLayout
 Arranges components in rows and columns of equal size. 22. Explain layout manager in detail. Give its advantages
 Each cell contains one component and components expand to fill the cell.
Layout Manager
 Useful for forms, calculators, and table-like layouts.
A layout manager in Java is an object that automatically arranges GUI
Syntax:
setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns components in a container according to a specific pattern or layout.
Example: Creating a calculator interface with buttons in grid layout. It removes the need to manually set positions of components and provides
flexibility when the window is resized.
Advantages of Layout Manager
21. Write a program to accomplish the following tasks: (i) 1. Automatic arrangement – Components are placed without manually
Drawing polygons (ii) Drawing a line graph calculating positions.
Drawing Polygons 2. Responsive design – Components adjust automatically when the window
 Use drawPolygon() or fillPolygon() methods of Graphics class. is resized.
 Store the x and y coordinates of vertices in arrays. 3. Simplifies GUI development – Easy to manage large number of
Drawing a Line Graph components.
 Use multiple drawLine() calls to connect points representing data. 4. Supports multiple layouts – Developers can use different layout
 X and Y arrays store coordinates of data points. managers for different panels.
Short Program Example: 5. Portable – Works well across different screen sizes and resolutions.
import [Link].*;
import [Link].*; 23. Explain graphics object. Design an application to draw a
public class GraphDemo extends Applet { filled circle using Java
public void paint(Graphics g) {
// Drawing Polygon Graphics Object
int x1[] = {50, 150, 100}; In Java, a Graphics object represents a drawing surface.
int y1[] = {50, 50, 150}; It is used to draw shapes, text, and images on components like Applets, Frames,
[Link](x1, y1, 3); or Panels.
Methods of Graphics class include:
// Drawing Line Graph
int x2[] = {50, 100, 150, 200};  drawLine() – Draw a line
int y2[] = {150, 120, 130, 100};  drawRect() – Draw rectangle outline
for(int i=0; i<[Link]-1; i++) {  fillRect() – Fill rectangle
[Link](x2[i], y2[i], x2[i+1], y2[i+1]);
 drawOval() – Draw oval outline
}
}  fillOval() – Fill oval or circle
}  drawPolygon() – Draw polygon
 The polygon is drawn using drawPolygon().  fillPolygon() – Fill polygon
 The line graph connects points using drawLine() in a loop.  drawString() – Draw text

Ajay bhai, ye teeno answers full-length, paper-ready, long passages, simple Short Program to Draw Filled Circle
English hain. import [Link].*;
Agla set 22, 23… bhej du kya? import [Link].*;
Ajay bhai, bilkul exam-ready, long theory, simple English, paper-ready public class CircleDemo extends Applet {
passage, aur code sirf wahi jahan poocha gaya. public void paint(Graphics g) {
[Link](100, 100, 100, 100); // Draw filled circle
}
} 5. [Link] – Advanced GUI package with classes like JButton, JLabel,
 fillOval(x, y, width, height) draws a filled oval. JPanel.
 If width = height, it becomes a circle. 6. [Link] – For networking operations like Socket, URL.
7. [Link] – For database operations like Connection, ResultSet,
24. Explain different types of Layout Managers Statement.
Java provides several layout managers to arrange components in containers: These packages save time because developers don’t need to write basic classes
1. FlowLayout themselves.
 Arranges components horizontally like a paragraph.
 Moves components to the next line when the row is full. 26. What is the use of extends and implements keyword?
 Example: setLayout(new FlowLayout());
extends Keyword
2. BorderLayout  Used in inheritance.
 Divides container into North, South, East, West, Center.
 When a class extends another class, it inherits fields and methods of the
 Each region can contain one component.
parent class.
 Example: setLayout(new BorderLayout());  Example:
3. GridLayout class Parent { }
 Arranges components in rows and columns of equal size. class Child extends Parent { }
 Example: setLayout(new GridLayout(2,3)); Here, Child inherits all features of Parent.
4. CardLayout implements Keyword
 Shows one component at a time, like cards.  Used when a class implements an interface.
 Example: setLayout(new CardLayout());  A class must define all abstract methods of the interface.
5. GridBagLayout  Example:
 Flexible layout with different row and column sizes. interface A { void display(); }
 Example: Used for complex forms with uneven component sizes. class B implements A {
public void display() { [Link]("Hello"); }
6. BoxLayout }
 Arranges components vertically or horizontally.
 extends → for class-to-class inheritance
 Example: Used for toolbars or stacked buttons.
 implements → for class-to-interface implementation

25. What are the built-in packages supported by Java? 27. List the various controls in Java. Explain any five in brief
Built-in Packages in Java Controls in Java
A package in Java is a collection of related classes and interfaces. Controls are GUI components that allow user interaction.
Java provides many predefined packages to make development easier. Common Controls:
Commonly used built-in packages:  Button, TextField, TextArea, Label, Checkbox, Choice, List, Scrollbar,
1. [Link] – Automatically imported. Contains fundamental classes like RadioButton, Canvas
String, Math, Object, System.
2. [Link] – Contains utility classes like ArrayList, Date, Scanner,
Collections.
Explanation of Five Controls
1. Button
3. [Link] – For input/output operations, like File, BufferedReader,
 A clickable component that performs actions when pressed.
PrintWriter.
 Method: addActionListener() to handle clicks.
4. [Link] – For creating GUI components like Frame, Button, Label,
2. TextField
Panel.
 Accepts single-line input from the user.
 Methods: getText(), setText(). public static void main(String[] args) {
new ContainerDemo();
3. TextArea }
 Accepts multi-line input from the user. }
 Methods: append(), setText().  This program creates a frame, adds a panel, and places buttons inside
4. Label the panel.
 Displays text that the user cannot edit.  Panels help in grouping and organizing components inside a frame.
 Methods: setText(), setAlignment().
5. Checkbox
 Provides on/off selection.
29. Write short note on event driven programming
 Methods: getState(), setState(boolean b). Event Driven Programming
Other controls include Choice (drop-down menu), List (list of items), Scrollbar,  Event-driven programming is a programming paradigm in which the
Canvas (drawing area), and RadioButton. flow of the program is determined by events.
 Events are actions performed by the user or system, such as mouse
clicks, keyboard presses, or window actions.
 Programs wait for events and respond using event handlers.
28. Write a Java program for class container which includes Key Points:
features of frame and panel 1. Each GUI component can generate events.
Explanation 2. Event handlers like ActionListener, MouseListener, KeyListener are
In Java, a container is a component that can hold other GUI components. used to respond.
A Frame is a top-level window and a Panel is an intermediate container to 3. Provides interactive and responsive applications.
organize components. 4. Widely used in GUI applications, games, and web interfaces.
A program can include both Frame and Panel to design a GUI application. Example: Clicking a button to submit a form generates an ActionEvent, which is
Short Program Example: handled by actionPerformed() method.
import [Link].*;  Event-driven programming makes applications user-friendly and
import [Link].*; dynamic.
public class ContainerDemo extends Frame {
Panel p;

ContainerDemo() {
setTitle("Frame with Panel");
setSize(400, 300);

p = new Panel();
[Link]([Link]);
add(p); // Add panel to frame

Button b1 = new Button("OK");


Button b2 = new Button("Cancel");
[Link](b1);
[Link](b2);

setLayout(new FlowLayout());
setVisible(true);
}

You might also like