Java Object-Oriented Programming Guide
Java Object-Oriented Programming Guide
By:
Satish Naik
Published by
This book, “Object-Oriented Programming Using Java”, is designed primarily for BCA students,
with the aim of providing a clear and systematic understanding of fundamental programming
concepts through Java. It follows a simple, concept-first and example-later approach inspired by
the teaching style of E. Balagurusamy, ensuring that even beginners can grasp complex topics with
ease.
I sincerely hope this book serves as a useful guide for students beginning their journey in object-
oriented programming and helps them build a strong foundation in Java.
Suggestions and constructive feedback from readers, teachers, and students are most welcome and
will be appreciated for the improvement of future editions.
Satish Naik
Author
First and foremost, I bow with deep respect and devotion to my revered Guru, Shri Vishnu Sawant
Bosle of Santoshimata Temple, whose wisdom and blessings have been a constant source of
inspiration and strength. His divine guidance has enlightened my path and given me the courage to
complete this work.
I am sincerely thankful to Kekare Sir, for his continuous encouragement and motivation to pursue
my passion for teaching and writing. His belief in my abilities has played a major role in
transforming this idea into a meaningful book.
Lastly, I express my sincere appreciation to all my students, readers, and well-wishers. Your trust,
enthusiasm, and eagerness to learn have always inspired me to do better. I hope this book serves
as a useful companion in your journey of learning Object-Oriented Programming with Java.
— Satish Naik
Java Evolution: Java evolution refers to how the Java programming language has grown and improved
since its creation. It has continuously adapted to new technologies and developer needs, ensuring its
relevance in modern computing.
That same year, Java 1.0 was officially released with the famous slogan “Write Once, Run Anywhere
(WORA)”, highlighting its ability to run on any platform using the Java Virtual Machine (JVM).
Today, Java is maintained by Oracle Corporation and continues to be used in diverse areas like web
applications, mobile apps (Android), enterprise software, cloud computing, and artificial intelligence.
Key Contributors to Java (Green Project Team) : In 1991, Sun Microsystems formed the Green
Project team with about 13 members to work on a new language for
programming small devices. The most notable among them were:
James Gosling – Father of Java, designed the language.
Mike Sheridan – Project manager who coordinated the effort.
Patrick Naughton – Helped bring Java into practical use.
Bill Joy – Co-founder of Sun, strong supporter and promoter of
Java.
While many contributed, Gosling, Sheridan, and Naughton are
recognized as the main creators of Java. Other important members of
the Green Project team who contributed to the development of Java
were: Jon Payne, Cindy Long, David Lavallee, Al Frazier, Joe Palrang,
Don Jackson, Chuck Clanton, Bob Weisblatt, Sheueling Chang, Chris Warth, Ed Frank, and Craig Forrest.
Features of Java
Java became one of the most popular programming languages because of its powerful features. These
features make Java different from earlier languages like C and C++ and ensure its wide use in modern
applications such as web, mobile, and enterprise systems.
1. Simple
Java is considered simple because:
Its syntax is based on C/C++, which makes it familiar, but it avoids confusing features such as
pointers, multiple inheritance (through classes), and operator overloading.
It provides automatic memory management through Garbage Collection, which reduces
programmer effort and prevents memory leaks.
Java programs are easier to read, write, and debug compared to older languages.
3. Platform-Independent
One of Java’s strongest features is platform independence.
Programs are compiled into an intermediate form called bytecode, not machine code.
Bytecode is executed by the Java Virtual Machine (JVM) on any platform.
The same Java program can run on Windows, Linux, or Mac without any change.
This gives Java its famous slogan: “Write Once, Run Anywhere (WORA)”.
4. Secure
Java has strong built-in security:
It does not support pointers, eliminating memory corruption and unauthorized access.
The JVM verifies bytecode before execution to prevent malicious operations.
Java supports security mechanisms like the Security Manager and Sandboxing, which restrict
untrusted code.
Because of these features, Java is widely used in banking, financial, and web applications where security is
crucial.
5. Robust
Java is designed to be strong and reliable.
It emphasizes compile-time checking and runtime checking, reducing chances of errors.
Exception handling mechanisms prevent programs from crashing unexpectedly.
Automatic Garbage Collection ensures better memory management.
This makes Java applications more stable and dependable than many older languages.
6. Distributed
Java supports distributed computing, where programs can run and interact across multiple systems
connected by a network.
It includes a rich set of classes in the [Link] package for networking.
Supports technologies like RMI (Remote Method Invocation), CORBA, and web services.
These features allow Java to build powerful client-server and internet-based applications.
7. Multithreaded
Java provides built-in support for multithreading—executing multiple tasks simultaneously.
Each task is executed as a thread, which is lightweight and managed by the JVM.
Multithreading is useful in applications like games, animations, multimedia processing, and real-time
systems.
Threads allow better CPU utilization by performing multiple operations in parallel.
8. High Performance
Although Java is an interpreted language, it achieves high performance with the help of:
Just-In-Time (JIT) Compiler, which converts bytecode into native machine code at runtime for faster
execution.
Efficient memory management and optimization techniques.
Java is not as fast as low-level languages like C, but its performance is good enough for large-scale
enterprise, web, and mobile applications.
Summary of Features
Feature Description
Simple Easy to learn, no pointers, no operator overloading, automatic memory management.
Object-Oriented Follows OOP principles: Encapsulation, Inheritance, Polymorphism, Abstraction.
Platform-Independent Compiled into bytecode, runs on JVM anywhere (WORA).
Secure No pointers, bytecode verification, security manager, sandboxing.
Robust Strong error handling, garbage collection, memory safety.
Distributed Built-in networking support, RMI, CORBA, web services.
Multithreaded Supports concurrent execution of multiple threads.
High Performance JIT compiler and efficient memory management improve speed.
Dynamic Supports runtime linking and reflection for flexibility.
Portable Bytecode and fixed data types ensure consistent behavior everywhere.
Key Differences
1. Paradigm
C → Procedural (focuses on func ons and procedures).
C++ → Supports both Procedural and Object-Oriented Programming.
Java → Purely Object-Oriented (everything is an object except primitive types).
2. Platform Dependence
C & C++ → Pla orm dependent. Compiled programs run only on the system they are compiled for.
Java → Pla orm independent. Code is compiled into bytecode, which runs on the Java Virtual
Machine (JVM).
3. Memory Management
C & C++ → Programmer manually allocates and frees memory (malloc, free, delete).
Java → Automa c memory management with Garbage Collection.
4. Pointers
C & C++ → Use pointers for direct memory access.
Java → No explicit pointers (uses references instead), which improves security.
5. Multiple Inheritance
C++ → Supports mul ple inheritance (a class can inherit from mul ple classes).
Java → Does not support mul ple inheritance through classes (to avoid ambiguity problems).
Instead, it uses interfaces to achieve multiple inheritance of behavior.
C → Not object-oriented, so no concept of inheritance.
Comparison Table
Feature C C++ Java
Procedural + Pure Object-Oriented (except
Programming Paradigm Procedural
Object-Oriented primitives)
Platform Dependency Dependent Dependent Independent (via JVM)
Manual Manual
Memory Management Automatic (Garbage Collector)
(malloc/free) (new/delete)
Not supported (only
Pointers Fully supported Fully supported
references)
Not supported (via interfaces
Multiple Inheritance Not supported Supported
only)
Not supported (except + for
Operator Overloading Not supported Supported
strings)
Compiled to Compiled to Compiled to bytecode (runs on
Execution
machine code machine code JVM)
Libraries Limited STL Huge API library
Security Low Low High
System-level, OS Games, system
Application Domain Web, mobile, enterprise, cloud
dev software
Another major strength of Java on the Internet is its networking capabilities. With the [Link] package,
developers can easily create client–server applications, work with sockets, and access information over URLs.
These features earned Java the title of a network-centric language. At the same time, Java placed a strong
emphasis on security, ensuring that Internet applications could run safely. Features like the absence of
pointers, bytecode verification, and sandboxing protected users from malicious code and made Java a
trusted choice for online banking, e-commerce, and enterprise systems.
Web Browsers
A Web Browser is application software that allows users to access, retrieve, and view information on the
World Wide Web. It interprets HTML, CSS, JavaScript, and other web technologies to display web pages in a
user-friendly format.
Browsers act as the interface between the user and the Internet: when a URL is entered, the browser sends
a request to a web server using the HTTP/HTTPS protocol, retrieves the response (usually HTML documents,
images, or multimedia), and renders it for the user.
1. Hardware Requirements
The exact requirements depend on the version of Java, but a basic system configuration for Java
programming is:
Processor: Minimum Pentium IV (1 GHz or higher); modern systems use multi-core processors
(i3/i5/i7, AMD Ryzen).
RAM: Minimum 512 MB (for older JDK versions); recommended 2 GB or more for smooth
development with IDEs (like Eclipse, NetBeans, IntelliJ).
Hard Disk: Around 500 MB free space for JDK; additional space required for IDEs, libraries, and
projects.
Monitor: Standard VGA/LED monitor with at least 1024 × 768 resolution.
Keyboard & Mouse: For program input and interaction.
2. Software Requirements
To develop and execute Java programs, the following software is required:
Operating System (OS):
o Java is platform-independent and works on Windows, Linux, and macOS.
o For academic use, Windows (7/8/10/11) or Linux distributions (Ubuntu, Fedora) are
common.
Java Development Kit (JDK):
o The JDK includes the compiler (javac), interpreter (java), libraries, and tools required for
writing and running Java programs.
o Example: JDK 8, JDK 11, JDK 17 (LTS versions commonly used).
Java Runtime Environment (JRE):
o Required to run Java programs.
o JDK already contains JRE, so separate installation is optional for developers.
Integrated Development Environment (IDE): (optional but recommended)
o Tools like Eclipse, NetBeans, IntelliJ IDEA, BlueJ make coding easier with features like syntax
highlighting, debugging, and project management.
o Beginners can also use a simple text editor (Notepad/Notepad++/gedit) with the command-
line tools.
Types of Java Programs: Java programs can be broadly classified into two types based on how they are
executed:
1. Standalone Applications
Definition: Standalone applications are programs that run independently on a computer using the
JVM.
Characteristics:
o They do not require a web browser to run.
o Typically executed from the command line or an IDE.
o Can be desktop software like calculators, text editors, or business applications.
Example: Programs like HelloWorld, Student & Test, or Bank Management Systems.
2. Web Applets
Definition: Applets are Java programs that run inside a web browser or an applet viewer.
Characteristics:
o Require a web browser to execute.
o Used to provide interactive features on web pages, like animations or simple games.
o Run in a restricted security environment (sandbox) for safety.
Example: Java applets embedded in web pages to display interactive forms, animations, or
educational tools.
Output:
Sum: 30
// Class 1: Student
class Student {
private String name;
private int rollNo;
// Constructor
public Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}
// Class 2: Test
public class Test {
public static void main(String[] args) {
// Creating an object of Student class
Student s1 = new Student("Ram", 101);
[Link]();
}
}
Explanation:
class Student → Declares a class with data members and a constructor.
display() → A method to print student details.
public class Test → Contains the main method, the starting point of program execution.
Student s1 = new Student("Ram", 101) → Creates an object of the Student class and passes data.
[Link]() → Calls the method to display student information.
Output:
Name: Ram
Roll No: 101
Example:
// This program prints a welcome message
[Link]("Welcome to Java!");
1. Keywords
Keywords are reserved words in Java.
They have a predefined meaning and cannot be used as identifiers.
Java has around 50+ keywords like: class, int, if, else, while, switch, static, void, break, return,
public, private.
Example:
class Student {
int age; // 'class' and 'int' are keywords
}
2. Identifiers
Identifiers are the names given to classes, variables, methods, and objects.
They allow programmers to identify program elements.
Rules for Naming Identifiers
1. Must begin with a letter (A-Z or a-z), underscore (_), or dollar sign ($).
2. Can contain letters, digits, underscores, and dollar signs.
3. Cannot use keywords as identifiers.
4. Java is case-sensitive (Age and age are different).
Valid Identifiers
name, student1, _rollNo, $salary
Invalid Identifiers
❌123abc (cannot start with digit)
❌class (keyword)
❌stu dent (space not allowed)
❌@data (special character not allowed)
Operators: Operators are symbols that perform specific operations on variables and
a values.
Java has a rich set of operators grouped into categories.
1. Arithmetic Operators
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10, b = 3;
2. Relational Operators
public class RelationalOperators {
public static void main(String[] args) {
int x = 10, y = 20;
[Link]("x == y: " + (x == y));
[Link]("x != y: " + (x != y));
[Link]("x > y: " + (x > y));
[Link]("x < y: " + (x < y));
[Link]("x >= y: " + (x >= y));
[Link]("x <= y: " + (x <= y));
}
}
Logical Operators
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true, b = false;
[Link]("a && b: " + (a && b));
[Link]("a || b: " + (a || b));
[Link]("!a: " + (!a));
}
}
a += 3; // a = a + 3
[Link]("a += 3: " + a);
a *= 2; // a = a * 2
[Link]("a *= 2: " + a);
a -= 4; // a = a - 4
[Link]("a -= 4: " + a);
a /= 2; // a = a / 2
[Link]("a /= 2: " + a);
}
}
Example:
int x = 5;
[Link](x++); // 5 (post-increment)
[Link](++x); // 7 (pre-increment)
(b) OR (|)
Rule: 1 | 1 = 1, 1 | 0 = 1, 0 | 0 = 0
Example:
5 = 0101
3 = 0011
--------------
5 | 3 = 0111 (decimal 7)
Example:
-5 >>> 1 → large positive number (because sign bit is removed)
Bitwise Operators
public class BitwiseOperators {
public static void main(String[] args) {
int x = 5, y = 3; // Binary: 0101 and 0011
[Link]("x & y: " + (x & y)); // AND
[Link]("x | y: " + (x | y)); // OR
[Link]("x ^ y: " + (x ^ y)); // XOR
[Link]("~x: " + (~x)); // NOT
[Link]("x << 1: " + (x << 1)); // Left shift
[Link]("x >> 1: " + (x >> 1)); // Right shift
}
}
Output:
x & y: 1
x | y: 7
x ^ y: 6
~x: -6
x << 1: 10
x >> 1: 2
H. Instanceof Operator
Tests whether an object belongs to a particular class.
Example:
String s = "Hello";
[Link](s instanceof String); // true
2. instanceof Operator
class Animal {}
class Dog extends Animal {}
Example:
double d = 10.5;
int x = (int) d; // converts double to int
5. Separators (Delimiters)
Separators help organize code.
; → Statement terminator
{ } → Defines a block of code
( ) → Encloses parameters/condi ons
[ ] → Array indexing
, → Separates mul ple variables
. → Accesses class members
Example:
int arr[] = {1, 2, 3};
[Link](arr[0]);
Java Statements
A statement in Java is a complete unit of execution. Just like a sentence in English ends with a period, a Java
statement usually ends with a semicolon ( ; ). Statements tell the Java compiler what actions to perform.
Java provides several types of statements to control the execution flow of a program.
2. Declaration Statements
Used to declare variables or constants.
Example:
int a;
final double PI = 3.14159;
4. Block Statements
A block is a group of statements enclosed in curly braces { }, treated as one unit.
Example:
{
int x = 10;
int y = 20;
[Link](x + y);
}
Evaluation of Expressions in Java
Evaluation of expressions means the process of computing the final value of an expression by applying
operators on operands according to rules of precedence and associatively.
1. Order of Evaluation
1. Operator Precedence → Some operators are given higher priority (e.g., *, / before +, -).
2. Associativity → If operators have the same precedence, evalua on follows a fixed direc on (le -to-
right or right-to-left).
3. Parentheses () → Always evaluated first, overriding precedence.
3. Steps in Evaluation
Parentheses are solved first.
Then unary operators (++, --, !).
Multiplication/division/modulus are applied before addition/subtraction.
Relational and logical operators are applied later.
Finally, assignment happens.
Type Conversion: Type conversion is the process of converting a value from one data type to another.
There are two main types:
Rules in Java:
byte → short → int → long → float → double
char → int → long → float → double
Example (Java):
int x = 10;
double y = x; // int is promoted to double
[Link](y); // Output: 10.0
Here, int x is implicitly converted to double because double can store integer values without loss.
Example (Java):
double a = 9.78;
int b = (int) a; // explicit casting
[Link](b); // Output: 9
Associatively
Associatively defines the order in which operators of the same precedence are evaluated in an expression.
a) Types of Associatively
1. Left-to-Right Associatively
o Most binary operators follow left-to-right.
o Example: +, -, *, /, %
2. int x = 20 - 5 - 3;
3. // evaluated as (20 - 5) - 3 = 12
4. Right-to-Left Associativity
o Some operators like assignment (=) and unary operators.
5. int a, b, c;
6. a = b = c = 10;
7. // evaluated as a = (b = (c = 10))
Quick Table
Operator Associativity
*/%+- Left to Right
= Right to Left
++ -- Right to Left
?: (ternary) Right to Left
// Absolute value
[Link]("Absolute of num1: " + [Link](num1));
// Power
[Link]("num2 raised to 3: " + [Link](num2, 3));
// Square root
[Link]("Square root of 16: " + [Link](16));
// Rounding functions
[Link]("Ceil of num1: " + [Link](num1));
[Link]("Floor of num1: " + [Link](num1));
[Link]("Round of num1: " + [Link](num1));
// Trigonometric function
[Link]("Sine of 45 degrees: " + [Link]([Link](45)));
Output:
Absolute of num1: 8.5
num2 raised to 3: 64.0
Square root of 16: 4.0
Ceil of num1: -8.0
Floor of num1: -9.0
Round of num1: -8
Max of num1 and num2: 4.0
Min of num1 and num2: -8.5
Sine of 45 degrees: 0.7071067811865475
e^2: 7.38905609893065
Natural log of 2: 0.6931471805599453
Here, args is an array of type String that stores command-line arguments passed by the user.
Key Points:
1. All command-line arguments are treated as strings.
2. They are separated by spaces on the command line.
3. The first argument is stored in args[0], the second in args[1], and so on.
4. The number of arguments can be obtained using [Link].
Syntax:
java ProgramName arg1 arg2 arg3 ...
Where:
ProgramName → name of the compiled .class file (without extension)
arg1, arg2, arg3 → arguments passed to the program
Example Program:
// File: [Link]
class CommandLineDemo {
public static void main(String args[]) {
[Link]("Number of arguments: " + [Link]);
Output:
Number of arguments: 3
The arguments are:
args[0] = Hello
args[1] = Java
args[2] = World
Explanation:
When we run the program, the JVM passes the arguments (Hello, Java, World) to the main() method as a
String array.
The for loop is used to display each argument separately.
Even if numeric values are passed, they are read as strings. You can convert them using
[Link]() or [Link]() when needed.
Why to use command line arguments: Command line arguments make a Java program flexible, reusable,
and automatable without code changes.
Variable : A variable is a named memory location that holds a value which can change during program
execution. It acts as a container to store data temporarily while the program runs.
Syntax
data_type variable_name;
or
data_type variable_name = value;
Examples
int age;
float salary;
char grade;
Initialization of Variables
Assigning an initial value to a variable at the time of declaration is called initialization.
Example:
int total = 100;
double pi = 3.14159;
Multiple Declarations
You can declare multiple variables of the same type in one line:
int a, b, c;
float x = 2.5f, y = 4.0f;
Note : $ can be used, but not recommended for normal variable names. $ is mainly used by Java compilers
or tools (like auto-generated class names, inner classes, or proxies). Example: Outer$[Link] → created
for inner classes. It’s also sometimes used in machine-generated code or frameworks (like JSP or bytecode
tools).
Constant: A constant is a fixed value that cannot be changed during program execution. It is used to make
programs more readable, maintainable, and error-free.
Example: PI = 3.14159 → the value of π should not change anywhere in the program.
Syntax
In Java, constants are declared using the keyword final: final → makes the value unchangeable. By
convention, constant names are written in UPPERCASE.
Examples
final int MAX_STUDENTS = 60;
final double PI = 3.14159;
final char GRADE = 'A';
Example Program
class ConstantDemo {
public static void main(String args[]) {
final double PI = 3.14159;
double radius = 5.0;
double area = PI * radius * radius;
Types of Constant:
1. Literal Constants
These are fixed values written directly in the program.
Type Example Explanation
int constant 10, 250, -5 Fixed integer numbers
float/double constant 3.14, 9.81 Fixed decimal numbers
char constant 'A', 'z', '0' Single characters
String constant "Hello", "Ravi" Sequence of characters
boolean constant true, false Logical values
Example:
String name = "Ravi";
int[] marks = {85, 90, 75};
Example:
class Example {
void show() {
int num = 10; // local variable
[Link]("Num = " + num);
}
}
num is only accessible inside show(). Outside, it gives an error.
B. Instance Variables (Non-Static): Declared inside a class but outside any method. Belongs to the object
— each object has its own copy. Default values are assigned automatically.
Example:
class Student {
int rollNo; // instance variable
String name; // instance variable
void display() {
[Link](rollNo + " " + name);
}
}
Each Student object has its own rollNo and name.
C. Static Variables (Class Variables) : Declared with static keyword inside a class. Belongs to the class, not to
objects — shared among all objects. Default values are assigned automatically.
Example:
class Example {
static int count; // static variable
void increment() {
count++;
}
}
All objects of Example share the same count.
Example Program
import [Link];
class InputDemo {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
The if Statement in Java: The if statement is used to execute a block of code only when a specified
condition is true. If the condition is false, the block of code is skipped. It is the simplest form of
decision-making in Java.
Syntax
if (condition) {
// statements to execute if condition is true
}
Flow of Control
1. Condition is evaluated.
2. If true → execute the statements inside if block.
3. If false → skip the if block and continue with the rest of the program.
Example Program
class IfExample {
public static void main(String args[]) {
int marks = 75;
Syntax
if (condition) {
// statements executed if condition
is true
} else {
// statements executed if condition
is false
}
Flow of Control
1. Condition is evaluated.
2. If true → execute if block.
3. If false → execute else block.
4. Program continues after if-else.
Syntax
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
}
}
Example Program
class NestedIfExample {
public static void main(String
(String
args[]) {
int marks = 85;
Output:
Distinction
Syntax
if (condition1) {
// statements for condition1
}
else if (condition2) {
// statements for condition2
}
else if (condition3) {
// statements for condition3
}
else {
// statements if all conditions
are false
}
Flow of Control
1. The first if condition is checked.
2. If true,, its block executes and the rest
are skipped.
3. If false, the next else if is checked.
4. If all conditions are false, the else block (if present) executes.
The switch-case Statement in Java: The switch statement is used to select one action from
multiple alternatives based on the value of a variable or expression. It is an alternative to multiple if-else
statements when you have many discrete values to
check. Best for situations where a variable can have
many possible constant values.
Syntax
switch (expression) {
case value1:
// statements for value1
break;
case value2:
// statements for value2
break;
...
default:
// statements if none of the
above matches
}
Notes:
expression → must return a byte, short, int,
char, String (Java 7+), or enum.
break → prevents fall-through to the next
case.
default → optional, executes if no case
matches.
Example Program
class SwitchExample {
public static void main(String args[]) {
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
default:
[Link]("Invalid day");
}
}
}
The ?: (Ternary) Operator in Java: The ternary operator is a shortcut for if-else statements. It
evaluates a condition and returns one value if true, another if false. Called ternary because it uses three
operands: condition, value if true, value if false.
Syntax
variable = (condition) ? value_if_true : value_if_false;
condition → boolean expression (true or false)
value_if_true → returned if condition is true
value_if_false → returned if condition is false
Example Program
class TernaryExample {
public static void main(String args[]) {
int marks = 75;
Output:
Grade: Distinction
In programming terms:
While Loop
The while loop is a control structure that allows a set of statements to be executed repeatedly as long as a
given condition is true. It is also called an entry-controlled loop,, because the condition is checked
checke before
executing the loop body.
Usage:
When the number of iterations is not known in advance.
Commonly used for situations like:
o Reading data until the end of file.
o Waiting for user input until a valid response is
entered.
o Repeating an operation until a particular condition
changes.
Syntax:
while (condition) {
// Body of the loop
// Statements to be executed repeatedly
}
condition → a logical or rela onal ex expression that controls the loop.
If the condition is true,, the loop body executes.
After execution, the condition is tested again.
If the condition becomes false,, the loop terminates and control goes to the next statement
after the loop.
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Do While
The do...while loop is a control structure used to execute a block of statements at least once, and
then repeatedly execute it as long as the given condition is true. Unlike the while loop, which
checks the condition before executing the loop body, the do...while loop checks the condition after
the loop body is executed.
Usage:
Used when the loop must execute at least
once, even if the condition is false initially.
Commonly used for:
o Menu-driven programs.
o Input validation (e.g., asking user to
continue or stop).
o Repetitive tasks where the first
action must always happen.
Syntax:
do {
// Body of the loop
// Statements to be executed
} while (condition);
Note: The semicolon (;) at the end of the while statement is mandatory.
Output:
Inside loop once even if condition is false.
Here, the condition num < 5 is false, but still the body runs once because the condition is tested after
execution.
For Loop : The for loop is a control structure that allows a block of statements to be executed repeatedly
for a fixed number of times. It is called an entry-controlled loop, because the condition is checked before
each iteration.
In simple words: “When you know exactly how many times you want to repeat a task, use a for loop.”
Usage:
Used when the number of repetitions (iterations) is known in advance.
Commonly used for:
o Printing a series of numbers.
o Calculating sums or factorials.
o Iterating through arrays or lists.
o Repeating a task a specific number of times.
Syntax:
for (initialization; condition; increment/decrement) {
// Body of the loop
// Statements to be executed repeatedly
}
Explanation of parts:
Part Description
Initialization Initializes loop control variable (executes once before loop starts).
Condition Tested before each iteration; if true → loop body executes.
Increment/Decrement Updates the control variable after each iteration.
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
1. Initialization: int i = 1; sets the starting value.
2. Condition: i <= 5 is checked — if true, the loop body executes.
3. Execution: [Link]("Number: " + i); prints the current value.
4. Increment: i++ increases the value of i by 1.
5. The process repeats until the condition becomes false.
Output:
2
4
6
8
10
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Enhanced for Loop (for Arrays and Collections) : The enhanced for loop (or for-each loop) is
used to access all elements of an array or collection one by one without using an index.
Type:
Simplified entry-controlled loop introduced in Java 1.5.
Syntax:
for (dataType variable : array_or_collection) {
// statements
}
Example:
int numbers[] = {10, 20, 30, 40, 50};
for (int n : numbers) {
[Link](n);
}
Output:
10
20
30
40
50
Usage:
o To read or display elements of arrays and collections.
o Removes need for loop counters or index management.
In simple terms: “Jump statements make the program skip, exit, or repeat sections of code based
on conditions.”
1. break Statement: To terminate the nearest enclosing loop or switch case immediately.
for (int i = 1; i <= 5; i++) {
if (i == 3)
break; // loop exits when i is 3
[Link](i);
}
Output:
1
2
2. continue Statement : To skip the current iteration and continue with the next iteration of the
loop.
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue; // skips printing 3
[Link](i);
}
Output:
1
2
4
5
Labeled Loops in Java: Labeled loops are used to control the flow of nested loops more
precisely. A label is an identifier placed before a loop to name it. Using this label, we can break out of or
continue a specific loop — not just the innermost one.
In simple words: “A label allows you to jump out of or continue a particular loop in nested loop
situations.”
Syntax:
labelname:
for (initialization; condition; increment) {
// Outer loop statements
for (initialization; condition; increment) {
// Inner loop statements
if (condition)
break labelname; // or continue labelname;
}
}
Output:
1 1
1 2
1 3
2 1
Loop ended.
Explanation:
When i == 2 and j == 2, the statement break outer; causes the outer loop to terminate immediately.
Explanation: Whenever j == 2, control skips the rest of the inner loop and continues the next
iteration of the outer loop.
Key Points:
A label must be followed by a colon (:) and placed just before the loop.
Labels are used with break or continue only.
Useful in nested loops when you need to exit or skip a specific loop.
Avoid overusing labels as they can make code harder to read.
1. Explain in detail the features of Java and how they contribute to platform independence
and security.
2. Describe the complete process of writing, compiling, and executing a Java program,
including the role of the JVM.
3. Explain operators in Java. Discuss arithmetic, relational, logical, and bitwise operators with
examples.
4. Discuss decision-making and looping statements in Java with suitable examples for each.
5. Explain the Java environment setup (hardware/software requirements, JDK tools, and Java
support systems) with a neat diagram.
Classes, Arrays, Strings and Vectors: Classes, Objects and Methods: Introduction, Defining a class, Adding
Variables, Adding Methods, Creating Objects, Accessing class members, Constructors, Methods Overloading,
Static Members, and Nesting of Methods.
Inheritance: Extending a class, Overriding Methods, Final Variables and Methods, Finalizer Methods,
Abstract Methods and Classes, Visibility Control. Arrays, Strings and Vectors: Arrays, One dimensional Array,
Creating an array, Two-dimensional Arrays, Strings, Vectors and Wrapper Classes.
Object-Oriented Programming (OOP) emerged to make programming more intuitive and closer to real-
world modeling. In the 1960s, Simula, developed by Ole-Johan Dahl and Kristen Nygaard in Norway,
introduced the concept of classes and objects for simulation purposes, which is considered the first OOP
language.
In the 1970s, Smalltalk, developed at Xerox PARC, refined OOP concepts like encapsulation, inheritance,
and polymorphism, making them practical for general-purpose programming.
In the 1980s and 1990s, OOP gained widespread adoption with languages like C++ and Java, which provided
robust support for creating modular, reusable, and maintainable software. Today, OOP is a standard
paradigm in software development, especially in Java, C++, Python, and C#.
Key Milestones:
1960s: Simula → First object-oriented language.
1970s: Smalltalk → Refined OOP principles.
1980s: C++ → OOP in general-purpose programming.
1990s: Java → Pla orm-independent OOP language with widespread use.
Definition:
Object-Oriented Programming (OOP) is a programming paradigm that organizes software around
objects rather than functions or logic. In OOP, real-world entities are modeled as objects, which
contain data (attributes) and behavior (methods).
Class in Java : A class in Java is a blueprint or template used to create objects. It defines the state
(attributes) and behavior (methods) that the objects of that class will have. Essentially, a class
encapsulates data and functions into a single unit.
In simple words: “A class is like a blueprint of a house — it defines how the house should be, but
the actual house is the object created from it.”
// Methods (Behavior)
returnType methodName(parameters) {
// method body
}
}
Example of a Class:
// Class to represent a Car
class Car {
// Attributes
String color;
String model;
int year;
// Method
void displayDetails() {
[Link]("Model: " + model);
[Link]("Color: " + color);
[Link]("Year: " + year);
}
}
Explanation:
Car is the class name.
color, model, year are attributes representing the car’s state.
displayDetails() is a method that prints the car details — representing its behavior.
This class does not occupy memory until an object is created.
It is an instance of a class, created using the new keyword in Java. Objects help in encapsulating data and
functions together in one unit. Each object has its own identity, attributes, and actions. Objects interact
with one another through method calls. They form the basic building blocks of Object-Oriented
Programming (OOP).
An object is a specific instance of a class. It occupies memory and has its own copy of attributes. Objects are
used to access class members (attributes and methods).
In simple terms: “If a class is a blueprint, an object is the actual house built from it.”
class Car {
String model;
String color;
void display() {
[Link](model + " - " + color);
}
}
class Main {
public static void main(String args[]) {
// Creating an object of Car
Car myCar = new Car();
// Setting attributes
[Link] = "Honda";
[Link] = "Red";
// Calling method
[Link]();
}
}
Output:
Honda - Red
Syntax:
[Link];
class Main {
public static void main(String args[]) {
// Create object
Car myCar = new Car();
Output:
Model: Honda
Color: Red
Arrays of Objects in Java: In Java, an array of objects is used to store multiple objects of the same class
in a single array. Each element of the array is a reference to an object, and memory for objects must be
allocated individually using the new keyword.
In simple words: “An array of objects is just like an array of variables, but each element holds a
reference to an object instead of a simple value.”
Syntax:
ClassName arrayName[] = new ClassName[size];
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]();
Sample Output:
Enter number of students: 2
Key Points:
1. The name of the constructor is the same as the class name.
2. It does not have any return type, not even void.
3. Constructors are automatically called when an object is created.
4. There can be more than one constructor in a class (constructor overloading).
5. If no constructor is defined, Java provides a default constructor automatically.
Syntax:
class ClassName {
ClassName() {
// constructor body
}
}
Example:
class Student {
int rollNo;
String name;
// Constructor
Student() {
rollNo = 1;
name = "Default Student";
}
void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}
class Main {
public static void main(String args[]) {
Student s1 = new Student(); // constructor called automatically
[Link]();
}
}
Output:
Roll No: 1, Name: Default Student
Default Constructor: A default constructor is the one that does not take any parameters.
It is used to assign default values to object members. If no constructor is defined, Java automatically
provides a default one.
Example:
class Student {
int rollNo;
String name;
// Default constructor
Student() {
rollNo = 1;
name = "Unknown";
}
void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}
class Main {
public static void main(String args[]) {
Student s1 = new Student(); // default constructor called
[Link]();
}
}
Example:
class Student {
int rollNo;
String name;
// Parameterized constructor
Student(int r, String n) {
rollNo = r;
name = n;
}
void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
[Link]();
[Link]();
}
}
Copy Constructor: Java does not have an inbuilt copy constructor like C++, but we can create one
manually to copy data from one object to another.
Example:
class Student {
int rollNo;
String name;
// Parameterized constructor
Student(int r, String n) {
rollNo = r;
name = n;
}
// Copy constructor
Student(Student s) {
rollNo = [Link];
name = [Link];
}
void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}
class Main {
public static void main(String args[]) {
Student s1 = new Student(101, "Rahul");
Student s2 = new Student(s1); // copy constructor called
[Link]();
[Link]();
}
}
Summary Table
Type of Constructor Parameters Purpose Example of Use
Default Constructor No Assigns default values Student s = new
Student();
Parameterized Constructor Yes Initialize with given Student s = new
values Student(101, "Amit");
Copy Constructor Yes (object) Copy data from another Student s2 = new
object Student(s1);
Example:
class Addition {
// Method with one parameter
void add(int a) {
[Link]("Sum = " + (a + 10));
}
class Main {
public static void main(String args[]) {
Addition obj = new Addition();
[Link](5); // calls add(int)
[Link](10, 20); // calls add(int, int)
[Link](4.5, 3.2); // calls add(double, double)
}
}
Output:
Sum = 15
Sum = 30
Sum = 7.7
Output:
Area of square: 25
Area of rectangle: 50
Area of circle: 19.625
Static Members in Java : In Java, the keyword static is used to define class-level members — that is,
variables and methods that belong to the class, not to any specific object. Static members are shared by all
objects of that class and can be accessed without creating an object.
1. Static Variables (Class Variables) : A static variable is common to all objects of a class. It is created
only once in memory, regardless of how many objects exist.
Example:
class Student {
int rollNo;
String name;
static String college = "ABC College"; // static variable
Student(int r, String n) {
rollNo = r;
name = n;
}
void display() {
[Link](rollNo + " " + name + " " + college);
}
Note : Here, both students share the same college name, since it is static.
2. Static Methods : A static method belongs to the class rather than to objects. It can be called without
creating an object, using the class name.
Rules:
Static methods can access only static variables and other static methods directly.
They cannot use this or super keywords.
Example:
class MathUtility {
static int square(int x) {
return x * x;
}
3. Static Blocks : A static block is used to initialize static variables. It executes only once, when the class
is loaded into memory.
Example:
class Example {
static int count;
static {
count = 100;
[Link]("Static block executed");
}
Output:
Summary Table
Static Member Description Accessed By Usage
Static Variable Shared by all objects [Link] Common data for all objects
Static Method Belongs to class [Link]() Utility or helper methods
Static Block Runs once when class loads Automatically Initialize static data
Key Points:
1. One method can call another method directly if it is in the same class.
2. If the called method is in a different class, it must be accessed using an object.
3. The method call is usually made using its name only, without the object reference (when
inside the same class).
Syntax:
class ClassName {
void method1() {
// statements
method2(); // calling another method
}
void method2() {
// statements
}
}
Example:
class Calculation {
void input() {
int a = 5, b = 10;
display(sum(a, b)); // calling sum() and display() methods
}
Output:
Sum = 15
In simple words: “Inheritance allows a new class to use the fields and methods of an existing class
without rewriting the code.”
Advantages of Inheritance:
1. Code reusability – avoids rewriting common code.
2. Method overriding – allows runtime polymorphism.
3. Extensibility – easy to add new features without affecting existing code.
4. Hierarchical organization – models real-world
world relationships effectively.
Key Points:
1. Parent class / Superclass → The class whose features are inherited.
2. Child class / Subclass → The class that inherits the features of the parent class.
3. Java supports single, multilevel, and hierarchical inheritance
inheritance.
4. Java does not support multiple inheritance using classes (can be achieved
chieved with interfaces).
Syntax:
class Parent {
// fields and methods
}
class Main {
public static void main(String args[]) {
Dog d = new Dog();
[Link](); // inherited method
[Link](); // own method
}
}
Output:
Types of Inheritance in Java: Inheritance allows a class to acquire properties and methods of another
class. Java supports four main types of inheritance:
Type Description Example
Single A child inherits from one class Dog extends Animal
parent class
Multilevel A class inherits from a subclass, class Puppy extends Dog
forming a chain
Hierarchical Multiple subclasses inherit class Cat extends Animal,
from one parent class Dog extends Animal
Multiple (via Interfaces) One class implements multiple class A implements X, Y
interfaces
Single Inheritance: Single Inheritance means that a child (subclass) inherits properties and
behaviors (methods and variables) from only one parent (superclass). This allows the subclass to
reuse and extend the functionality of the parent without rewriting the same code. It creates a
simple and clear hierarchy, making the program easier to understand and maintain. For example, a
Car class can inherit from a Vehicle class to gain all its common features like speed and fuel type,
while adding its own specific features like number of doors or model name.
Example:
class Student {
String name;
int rollNo;
void displayStudent() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}}
void displayExam() {
[Link]("Marks: " + marks);
}
}
class Main {
public static void main(String args[]) {
Exam e = new Exam();
[Link] = "Ravi";
[Link] = 101;
[Link] = 85;
Output:
Name: Ravi, Roll No: 101
Marks: 85
Multilevel Inheritance: occurs when a class is derived from another subclass, forming a chain of
inheritance. In this type, features of the base class are passed to the derived class, and then further
to another subclass. This allows gradual enhancement and reuse of code across multiple levels. For
example, if Animal is the base class, Mammal can inherit from Animal, and Dog can inherit from
Mammal. Thus, Dog gets the properties of both Mammal and Animal.
Example:
class Student {
String name;
int rollNo;
void displayStudent() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}
void displayExam() {
[Link]("Marks: " + marks);
}
}
void displayResult() {
[Link]("Grade: " + grade);
}
}
Hierarchical Inheritance: It occurs when two or more child classes inherit from the same
parent class. This allows multiple subclasses to share the common properties and methods of a
single base class, while also defining their own specific features. It promotes code reuse and
organized structure. For example, if Animal is the parent class, then Dog, Cat, and Horse can each
inherit from Animal, sharing common traits like eat() or sleep(), but having their own unique
behaviors.
class Student {
String name;
int rollNo;
void displayStudent() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}
void displayExam() {
[Link]("Marks: " + marks);
}
}
void displaySports() {
[Link]("Game: " + game);
}
}
class Main {
public static void main(String args[]) {
Exam e = new Exam();
[Link] = "Kiran";
[Link] = 103;
[Link] = 75;
[Link]();
[Link]();
}
}
4. Multiple Inheritance (via Interfaces) : Java does not support multiple inheritance with classes (to
avoid ambiguity). Achieved using interfaces where a class can implement multiple interfaces.
interface Academic {
void displayMarks();
}
interface Activity {
void displayGame();
}
[Link]();
[Link]();
}
}
Output:
Name: Priya, Roll No: 105, Marks: 92
Name: Priya, Game: Basketball
In simple words: “The child class redefines a method of the parent class with the same name,
parameters, and return type.”
Key Points:
1. The method name, return type, and parameters must be exactly the same.
2. The access level in the child class cannot be more restrictive than the parent class.
3. Private, static, and final methods cannot be overridden.
4. Use @Override annotation (optional but recommended) for compile-time checking.
Syntax:
class Parent {
void method() {
// parent method
}
}
class Main {
public static void main(String args[]) {
Student s = new Student();
[Link](); // calls parent method
Output:
This is a student.
This student has appeared for an exam.
Final Variables in Java are constants whose values cannot be changed once they are initialized. When a
variable is declared with the final keyword, it must be assigned a value only once, either at the time of
declaration or inside the constructor. Final variables are often used to define fixed values or constants that
should remain the same throughout the program, such as final double PI = 3.14159;. This helps make code
more reliable and easier to maintain..
Syntax:
final int MAX = 100; // constant variable
Example:
class Student {
final int maxMarks = 100; // final instance variable
void display() {
[Link]("Maximum Marks = " + maxMarks);
// maxMarks = 120; // Error: cannot assign a value to final variable
}
Final Methods: In Java, a method declared with the final keyword cannot be overridden by any subclass.
This ensures that the original implementation of the method remains unchanged and cannot be modified in
derived classes. It is mainly used to preserve important or core functionality that should not be altered. For
example, declaring final void show() in a parent class prevents subclasses from providing their own version of
the show() method..
Syntax:
class Parent {
final void display() {
[Link]("Final method in Parent");
}
}
Example:
class Student {
final void info() {
[Link]("This is a final method.");
}
}
Key Points:
Final Member Purpose / Rule
Final Variable Value cannot be changed once assigned
Final Method Cannot be overridden in subclass
Final Class Cannot be inherited (no subclass can extend it)
Key Points:
1. Declared as: protected void finalize() throws Throwable
2. Called by Garbage Collector before object removal.
3. Not guaranteed to run immediately.
4. Deprecated in Java 9; use try-with-resources or Cleaner instead.
Example:
class Student {
String name;
Student(String n) {
name = n;
[Link]("Student created: " + name);
}
class Main {
public static void main(String args[]) {
Student s1 = new Student("Ravi");
s1 = null;
[Link](); // request garbage collection
[Link]("End of main");
}
}
Sample Output:
Abstract Methods and Classes in Java: An abstract class is a class that cannot be
instantiated directly and may contain abstract methods. An abstract method is a method without a
body; it only has a method signature. Abstract classes are used to provide a base class with common
behavior while leaving specific implementations to subclasses.
Key Points:
1. Declared using the keyword abstract.
2. Cannot create objects of an abstract class.
3. Abstract classes may have concrete methods (methods with body) as well as abstract methods.
4. Subclasses must override abstract methods unless the subclass is also abstract.
Syntax:
abstract class ClassName {
abstract void methodName(); // abstract method
void normalMethod() { // concrete method
// method body
}
}
Student(String n) {
name = n;
}
// Abstract method
abstract void examDetails();
// Concrete method
void displayName() {
[Link]("Student Name: " + name);
}
}
Exam(String n, int m) {
super(n);
marks = m;
}
class Main {
public static void main(String args[]) {
// Student s = new Student("Ravi"); // Error: cannot instantiate
Exam e = new Exam("Ravi", 85);
[Link]();
[Link]();
}
}
Output:
Visibility Control in Java: Visibility control in Java determines which classes or objects can access
members (variables or methods) of a class. It is achieved using access modifiers, which control access levels
for data and methods to ensure encapsulation.
// Constructor
Student(int r, String n, int m, String c) {
rollNo = r;
name = n;
marks = m;
course = c;
}
void display() {
[Link]("RollNo: " + rollNo + ", Name: " + name +
", Marks: " + marks + ", Course: " + course);
}
}
class Main {
public static void main(String args[]) {
Student s = new Student(101, "Ravi", 85, "Java");
// [Link]([Link]); // Error: private
[Link]([Link]()); // Allowed via getter
[Link]([Link]); // default
[Link]([Link]); // protected (same package)
[Link]([Link]); // public
}
}
Output:
101
Ravi
85
Java
Key Points:
1. Encapsulation: Hides data from unauthorized access.
2. Use private for sensitive variables and provide getter/setter methods.
3. protected is mainly used to allow inheritance access.
4. public members are fully accessible everywhere.
Arrays in Java: An array is a collection of elements of the same data type stored in contiguous
memory locations. It allows storing multiple values under a single variable name and accessing them
using an index.
Types of Arrays:
1. One-Dimensional Array – Stores elements in a single row (e.g., marks of students).
2. Two-Dimensional Array – Represents data in rows and columns (e.g., a matrix).
1D Array : A one-dimensional (1D) array in Java is a collection of elements of the same data type stored in
contiguous memory locations and accessed using a single index
Declaration:
int[] marks; // or int marks[];
Initialization:
marks = new int[5]; // size 5, default values 0
int[] marks = {85, 90, 75}; // directly initialize with values
2D Array : A two-dimensional (2D) array in Java is an array of arrays, used to store data in rows and columns
(like a table or matrix).
Declaration:
int[][] matrix; // or int matrix[][];
Initialization:
matrix = new int[3][3]; // 3x3 matrix, default 0
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; // directly initialize
1D Array Example
class Main {
public static void main(String args[]) {
// Declaration & Initialization
int[] marks = {85, 90, 75, 60};
Output:
Marks of students:
Student 1: 85
Student 2: 90
Student 3: 75
Student 4: 60
2D Array Example
class Main {
public static void main(String args[]) {
// Declaration & Initialization
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
Output:
Matrix:
1 2 3
4 5 6
7 8 9
Key Points:
Arrays are homogeneous (same data type).
1D array is like a list, 2D array is like a table.
Index starts from 0.
Arrays are fixed in size once created.
Strings in Java: A String is an object that represents a sequence of characters. Strings are immutable,
which means that once a String object is created, its value cannot be changed. Any modification, like
concatenation or replacement, creates a new String object rather than altering the existing one.
For example, if String s = "Hello"; and you do s = s + " World";, a new String object "Hello World" is created, and s
now refers to this new object. This immutability makes strings thread-safe and efficient for many operations.
Example:
class Main {
public static void main(String args[]) {
String name = "Ravi Kumar";
[Link]("Length: " + [Link]());
[Link]("Character at 2: " + [Link](2));
[Link]("Uppercase: " + [Link]());
[Link]("Substring: " + [Link](0,4));
[Link]("Replace: " + [Link]('a','o'));
}
}
Output:
StringBuffer Class in Java: StringBuffer is a mutable sequence of characters, meaning you can
modify the contents of the string without creating a new object. It is thread-safe and part of [Link]
package.
Creating StringBuffer:
Example:
class Main {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Ravi");
[Link](" Kumar");
[Link](4," XYZ");
[Link](0,4,"John");
[Link](8,12);
[Link]();
[Link](sb);
}
}
Output:
ramuHZY nhoJ
Key Points:
1. String → immutable, new object created on modifica on.
2. StringBuffer → mutable, modifies original object.
Vectors in Java: A Vector is a dynamic array that can automatically grow or shrink as elements are
added or removed. It is part of the [Link] package and is synchronized, which means it is thread-safe and
can be safely used in multi-threaded programs. Unlike a regular array, you don’t need to specify its size in
advance, and it provides methods like add(), remove(), get(), and size() to manipulate elements efficiently
Key Features:
1. Can store objects of any type.
2. Dynamic size unlike arrays.
3. Provides methods for adding, removing, and accessing elements.
4. Synchronized, so safe for multithreaded operations.
Common Methods
Method Description Example
add(element) Adds element at the end [Link](100);
add(index,element) Adds element at specific index [Link](1,200);
remove(index) Removes element at index [Link](0);
get(index) Returns element at index [Link](2);
size() Returns number of elements [Link]();
contains(element) Checks if element exists [Link](100);
clear() Removes all elements [Link]();
set(index, element) Replaces element at index [Link](1,300);
class Student {
String name;
int rollNo;
Student(String n, int r) {
name = n;
rollNo = r;
}
void display() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}
class Main {
public static void main(String args[]) {
Vector<Student> students = new Vector<>();
// Display students
for(Student s : students) {
[Link]();
}
// Remove a student
[Link](1); // removes Meena
[Link]("After removal:");
for(Student s : students) {
[Link]();
}
}
}
Output:
Key Points:
1. Vector is like a dynamic array with automatic resizing.
2. Supports object storage, thread-safe, and legacy collection.
3. Can be replaced by ArrayList in modern applications for better performance if
synchronization is not needed.
Wrapper Classes in Java: A wrapper class in Java provides a way to use primitive data types as objects.
Every primitive type has a corresponding wrapper class in [Link] package.
Wrapper classes are useful when objects are required, for example in Collections (Vector,
ArrayList), which cannot store primitives directly.
Output:
Integer object: 25
Double object: 12.5
Primitive int: 25
Primitive double: 12.5
String to int: 100
String to double: 45.6
1. Explain in detail the concepts of classes, objects, and methods with a complete Java
program demonstrating all.
2. Discuss inheritance in Java. Explain how to extend a class, override methods, and use the
super keyword with examples.
3. Explain the concept of abstract classes and final methods in Java. How are they used in
object-oriented programming?
4. What are arrays, strings, and vectors in Java? Compare their features and illustrate each
with a suitable example.
5. Explain method overloading and nesting of methods with a program that demonstrates
both.
Multithreaded Programming: Introduction, Creating Threads, Extending the Thread Class, Stopping and
Blocking a thread, Life Cycle of a thread, Using Thread Methods, Thread Exceptions, Thread Priority,
Synchronization, Implementing the Runnable Interface.
Multiple Inheritances: Java does not support multiple inheritances with classes to avoid
ambiguity (diamond problem). Interfaces provide a way to achieve multiple inheritance because a
class can implement multiple interfaces. Interfaces can contain abstract methods, constants, and
in modern Java, default, static, and private methods.
Defining Interfaces
Declared using the keyword interface.
Members are public and abstract by default.
Variables are public, static, and final by default.
Syntax:
interface InterfaceName {
int MAX = 100; // constant
void method1(); // abstract method
void method2(); // abstract method
}
Extending Interfaces
One interface can extend another interface using the extends keyword.
Supports multiple inheritance between interfaces.
Syntax:
interface Exam {
void displayMarks();
}
Implementing Interfaces
A class implements an interface using the implements keyword.
If a class implements multiple interfaces, separate them by comma.
The class must override all abstract methods of the interfaces.
interface Exam {
void displayMarks();
}
interface Result {
void displayResult();
}
Student(String n, int m) {
name = n;
marks = m;
}
class Main {
public static void main(String args[]) {
Student s = new Student("Ravi", 85);
[Link]();
[Link]();
}
}
Output:
Marks of Ravi = 85
Ravi has Passed
Student(String n, int m) {
name = n;
marks = m;
}
class Main {
public static void main(String args[]) {
Student s1 = new Student("Ravi", 85);
[Link]();
[Link]();
}
}
Output:
Marks of Ravi = 85
Ravi has Passed
Student(String n, int m) {
name = n;
marks = m;
}
class Main {
public static void main(String args[]) {
Student s = new Student("Ravi", 85);
Output:
Marks of Ravi = 85
Ravi has Passed
interface Vehicle {
void start();
void stop();
}
class Main {
public static void main(String args[]) {
Vehicle v1 = new Car();
Vehicle v2 = new Bike();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Example:
interface Exam {
int MAX_MARKS = 100
100; // public static final by default
}
class Main {
public static void main(String args[]) {
Student s = new Student();
[Link]();
[Link](
[Link]("Access using interface: " + Exam.MAX_MARKS);
}
}
Output:
Maximum Marks: 100
Access using interface:
: 100
Packages in Java: A package in Java is a collection of related classes, interfaces, and sub-
sub
packages. It helps in organizing code
code, avoiding naming conflicts,, and reusing classes. Example:
[Link], [Link], [Link] are standard Java packages.
Java API Packages : Java provides a large set of predefined packages called API packages. Some
commonly used API packages
packages:
Example:
import [Link];
class Main {
public static void main(String args[]) {
Vector<String> v = new Vector<>();
[Link]("Ravi");
[Link](v);
}
}
Naming Conventions
Package names are lowercase to avoid conflicts.
Follow company domain style for unique names.
o Example: [Link]
Class names inside packages follow CamelCase.
Creating Packages
Use package keyword at the top of the Java file.
Example:
Accessing a Package
Use import to use classes from a package.
Example:
import [Link];
class Main {
public static void main(String args[]) {
Student s = new Student();
[Link] = "Ravi";
[Link]("Name: " + [Link]);
}
}
Using a Package
Once imported, classes can be instantiated and used normally.
Helps in modular programming.
Key Points:
1. Packages organize code and avoid class name conflicts.
2. Java provides system packages for common tasks.
3. Custom packages are created using package keyword and accessed with import.
4. Proper naming conventions ensure clarity and uniqueness.
Hiding Classes in Java : Hiding classes means restricting access so they cannot be used
outside their package or outer class, enhancing encapsulation.
package studentinfo;
class Student { // default class
String name;
}
class Outer {
private class Inner {
void display() {
[Link]("Private inner class");
}
}
void show() {
Inner i = new Inner();
[Link]();
}
}
Benefits of multithreading:
1. Better CPU utilization
2. Faster execution for concurrent tasks
3. Simpler program structure for asynchronous operations
Creating Threads
Java provides two ways to create threads:
1. Extending the Thread class
2. Implementing the Runnable interface
Example:
class MyThread extends Thread {
public void run() {
for(int i=1; i<=5; i++) {
[Link]("Thread: " + i);
}
}
}
class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link](); // starts a new thread
}
}
Implementing the Runnable Interface: Another way to create threads in Java is by implementing
the Runnable interface.
Example
class MyRunnable implements Runnable {
public void run() {
for(int i = 1; i <= 5; i++) {
[Link]("Runnable Thread: " + i);
}
}
}
class Main {
public static void main(String args[]) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r); // pass Runnable to Thread
[Link](); // start new thread
}
}
1. Stopping a Thread:
o stop() method is deprecated.
o Use a boolean flag to stop the thread safely.
2. Blocking a Thread:
o sleep(milliseconds) → pauses thread temporarily.
o join() → waits for another thread to complete.
class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link]();
}
}
Output:
Thread prints numbers with 1-second interval.
Life Cycle of a Thread: A thread in Java goes through different states from creation to termination.
These states define the life cycle of a thread.
Thread State Description Methods / Events Causing This State
New (Created) Thread object is created but not yet started. Thread t = new Thread() (constructor)
Runnable Thread is ready to run and waiting for CPU [Link]() moves thread from New →
time. Runnable
Running Thread is currently executing its run() JVM scheduler picks a Runnable thread to
method. execute
Blocked / Thread is waiting for a resource, I/O, or wait(), waiting to acquire a lock, join(),
Waiting another thread to release a lock. sleep() (temporarily)
Timed Waiting Thread is waiting for a specified period of sleep(ms), join(ms), wait(ms)
time.
Terminated Thread has finished execution or stopped, run() completes, or stop() (deprecated)
(Dead) cannot be restarted.
class Main {
public static void main(String args[]) {
MyThread t = new MyThread(); // New state
[Link]("Thread created: " + [Link]());
try {
[Link](500); // Main thread sleeps
[Link]("Thread state: " + [Link]()); // Likely
TIMED_WAITING
[Link](); // Wait for thread to finish
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread final state: " + [Link]()); // TERMINATED
}
}
Possible Output:
Using Thread Methods: Java provides several methods to control thread behavior:
Method Description
start() Starts the thread and calls run() method.
run() Contains the code executed by the thread.
sleep(ms) Pauses thread for specified milliseconds.
join() Waits for another thread to complete.
getName() Returns thread’s name.
setName(String) Sets thread’s name.
getPriority() Returns thread’s priority (1–10).
setPriority(int) Sets thread’s priority.
isAlive() Checks if thread is alive.
yield() Temporarily pauses thread to allow other threads to execute.
Example:
class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link]("Thread-A");
[Link]();
}
}
Output:
Thread-A is running
Thread Exceptions in Java: Threads in Java can throw exceptions during execution, mainly due
to interruption or illegal operations.
Example: InterruptedException
class MyThread extends Thread {
public void run() {
try {
[Link]("Thread starts sleeping...");
[Link](3000); // thread sleeps for 3 seconds
[Link]("Thread woke up");
} catch (InterruptedException e) {
[Link]("Thread was interrupted: " + e);
}
}
}
class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link]();
try {
[Link](1000); // main thread sleeps 1 second
[Link](); // interrupt t1 while it is sleeping
} catch (InterruptedException e) {
[Link](e);
}
}
}
Output:
Thread starts sleeping...
Thread was interrupted: [Link]
Explanation:
Thread t1 is sleeping for 3 seconds.
Main thread interrupts it after 1 second, causing InterruptedException.
Methods
Method Description
setPriority(int p) Sets thread priority (1–10).
getPriority() Returns the current thread’s priority.
Example
class MyThread extends Thread {
public void run() {
[Link](getName() + " priority: " + getPriority());
}
}
class Main {
public static void main
main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
[Link]("Thread
"Thread-A");
[Link]("Thread
"Thread-B");
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.MAX_PRIORITY); // 10
[Link]();
[Link]();
}
Possible Output:
Thread-A priority: 1
Thread-B priority: 10
Managing Exceptions in Java: Exceptions are unusual or error conditions that occur during
program execution. Managing exceptions ensures the program does not terminate abruptly. Java
provides a robust exception handling mechanism using try, catch, throw, throws, and finally.
Exception Types
1. Checked Exceptions:
o Checked at compile-time.
o Example: IOException, SQLException.
2. Unchecked Exceptions:
o Checked at runtime.
o Example: ArithmeticException, NullPointerException.
3. Error:
o Serious problems not meant to be handled by the program.
o Example: OutOfMemoryError.
Basic Syntax
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// Handle exception of type ExceptionType2
} finally {
// Code that will always execute (optional)
}
Output:
Cannot divide by zero: [Link]: / by zero
Execution completed
Syntax
class MyException extends Exception {
MyException(String message) {
super(message); // pass message
to Exception class
}
}
Output:
Caught: This is a custom exception
Applet Programming in Java: An applet is a small Java program designed to run inside a web browser
or an applet viewer. Unlike regular Java applications, applets cannot run independently—they depend on a
host environment. Applets are mainly used to create interactive web applications, such as games,
animations, or visual components, providing dynamic content for web pages.
HTML Example:
<html>
<body>
<h2>My First Applet</h2>
<applet code="[Link]" width="300" height="100">
</applet>
</body>
</html>
Attribute Description
code Name of the compiled applet class
width Width of applet display area
height Height of applet display area
align Alignment of the applet in page
codebase Directory containing class file
alt Alternate text if applet not supported
Passing Parameters to Applets: When an applet runs inside an HTML page, we can send data
(parameters) from the HTML file to the Java applet.
Those values are written in the HTML file and read by the applet at runtime.
Use <param> tag inside <applet> to pass values.
HTML Example:
<applet code="[Link]" width="300" height="100">
<param name="username" value="Satish">
</applet>
import [Link];
import [Link].*;
import [Link].*;
Method Description
drawLine(x1, y1, x2, y2) Draws a line between two points
drawRect(x, y, w, h) Draws a rectangle
fillRect(x, y, w, h) Draws filled rectangle
drawOval(x, y, w, h) Draws oval inside the rectangle bounds
fillOval(x, y, w, h) Draws filled oval
drawArc(x, y, w, h, startAngle, arcAngle) Draws an arc of ellipse
drawPolygon(int[] x, int[] y, n) Draws polygon with n points
drawString(String s, x, y) Displays string at (x,y)
setColor(Color c) Sets color for drawing
setFont(Font f) Sets font for text
drawPolygon(int[] x, int[] y, n)
Description: Draws a polygon connecting n points defined by arrays x[] and y[].
Example:
public void paint(Graphics g) {
int x[] = {500, 550, 600};
int y[] = {50, 150, 50};
[Link]([Link]);
[Link](x, y, 3); // triangle
}
setColor(Color c)
Description: Sets the color for subsequent drawing operations.
Example:
public void paint(Graphics g) {
[Link]([Link]);
[Link](50, 70, 100, 50);
}
setFont(Font f)
Description: Sets the font style and size for text drawn using drawString().
Example:
public void paint(Graphics g) {
[Link](new Font("Arial", F [Link], 16));
[Link]("Java Graphics", 50, 100);
}
import [Link];
import [Link];
import [Link];
Explanation:
Explanation:
data[i] determines the height of each bar.
200 - data[i] sets the top-left corner of the
bar for correct vertical positioning.
Looping makes it easy to draw multiple bars dynamically.
add(lbl);
add(tf);
add(btn);
[Link](this);
}
// Draw x-axis
[Link]([Link]);
[Link](40, 300, x, 300);
}
}
Explanation
o User Input:User enters numbers in the TextField, separated by commas (e.g., 50, 100, 80, 120).
o ActionListener: Button click triggers parsing of input into an integer array.
o Repaint: repaint() calls paint() to draw bars dynamically.
o Bar Graph:
Bars are drawn using fillRect().
Numbers displayed above each bar with drawString().
try {
[Link](
[Link](50); // delay for smooth animation
} catch (InterruptedException e) {}
}
}
Explanation
1. Thread for Animation:
o Implements Runnable and uses a thread to continuously update ball position.
2. Movement Variables:
o dx and dy control speed and direction.
3. Boundary Check:
o Ball reverses direction when it hits edges of applet (dx = -dx, dy = -dy).
4. Repaint Loop:
o repaint() redraws the ball at the new position every 50 ms for smooth animation.
1. What is bytecode?
2. Mention any two features of Java.
3. What are command line arguments?
4. Define variable and give an example.
5. What is the difference between if and switch statements?
6. Define class and object.
7. What is inheritance?
8. What is an interface?
9. Define thread and mention any one method of creating it.
10. What is the use of the finally block?
11. What is an applet?
12. Name any two methods of the Graphics class.
1. Explain in detail the features of Java and discuss how Java differs from C and C++.
2. Discuss classes, objects, and constructors in detail with suitable examples.
3. Explain packages in Java — creation, usage, and accessing user-defined packages with examples.
4. Explain the complete applet life cycle with a neat diagram and suitable program.
5. Write a detailed Java program to demonstrate exception handling using try, catch, throw,
throws, and finally.
1. Explain in detail the OOP principles and their advantages in Java programming.
2. Discuss method overriding and dynamic method dispatch with examples.
3. Explain exception handling hierarchy in Java and write a program demonstrating multiple catch
blocks.
4. Explain multithreading in Java. Write a program to create two threads executing simultaneously.
5. Write short notes on:
(a) Final variables and methods (b) Abstract methods and interfaces (c) Visibility control in
inheritance.
1. What is Java?
2. Define a class.
3. What is an object?
4. Name any two features of Java.
5. What is the use of the import statement?
6. What is the default value of an integer variable?
7. Write the syntax of a for loop in Java.
8. What is a constructor?
9. Define inheritance.
10. What is an interface?
11. What is the purpose of the final keyword?
12. What is meant by thread in Java?
Method overriding in Java occurs when a subclass provides its own implementation of a method that is already defined by its superclass. It requires the method in the subclass to have the same name, return type, and parameters as the method in the superclass. This feature of Java enables polymorphism by allowing the runtime decision of method execution based on the actual object's class. This is essential for dynamic method calls, allowing subclasses to modify or enhance behavior defined in the parent class, thereby extending its functionality while maintaining a common interface.
In Java, the 'final' keyword is used to define constants, ensure methods cannot be overridden, and prevent subclassing. When used with variables, 'final' means the variable can be assigned only once, establishing a constant; with methods, it prevents overriding in subclasses, preserving original functionality; and with classes, it prohibits subclassing, meaning the class cannot have child classes. This mechanism helps secure code integrity and design intents against unintended extensions or manipulations.
Abstract classes in Java provide a means of facilitating code extension and maintenance by allowing classes to share a common interface and implement shared code. They serve as a base class that cannot be instantiated directly but can define both abstract (method signatures without implementation) and concrete methods that subclasses can utilize and extend. This helps enforce a common interface across different subclasses while allowing individual implementations, making code easier to manage and extend. Subclasses must provide concrete implementations of abstract methods, fostering consistent and predictable behavior.
Multiple inheritance in Java is achieved through interfaces because Java does not support multiple inheritance with classes directly, to avoid ambiguity. A class can implement multiple interfaces, which allows it to inherit abstract methods from more than one interface. For instance, a class can implement both the 'Academic' and 'Activity' interfaces: `class StudentDemo implements Academic, Activity`. This enables the class 'StudentDemo' to define behaviors of both interfaces without having direct class hierarchy issues. Each method in the interfaces is explicitly defined in the implementing class, ensuring clarity and preventing method conflicts.
Java's visibility control ensures encapsulation by allowing developers to restrict access to class members (fields and methods) through access modifiers. The modifiers 'private,' 'default' (no modifier), 'protected,' and 'public' define the level of accessibility. 'Private' restricts access to within the same class, 'default' allows it within the same package, 'protected' expands access to subclasses even outside the package, and 'public' provides access from any other class. By controlling access, encapsulation is maintained, which hides the internal state and functionality of an object and exposes a clean interface.
Constructors in Java are special methods used to initialize objects. They have the same name as the class and do not have a return type, unlike regular methods. Constructors are automatically called when an object is created, enabling the setup of initial state and allocation of resources. They can be overloaded to provide multiple ways to instantiate objects depending on input parameters. Unlike regular methods, constructors cannot be called explicitly via method calls and are central to object creation and initialization.
Multilevel inheritance in Java allows one class to inherit from another subclass, forming a chain of inheritance. This means that a base class passes its features to a derived class, which can then pass its own features onto a further subclass. The advantage of multilevel inheritance is that it allows for gradual enhancement and reuse of code across multiple levels. For example, if "Animal" is a base class, "Mammal" can inherit from "Animal," and "Dog" can then inherit from "Mammal." As a result, the "Dog" class has access to properties and methods from both "Mammal" and "Animal." This promotes code reusability and a clear hierarchical structure.
The thread life cycle in Java consists of several stages: 'New,' where the thread is created but not yet started; 'Runnable,' where it is ready to run and awaiting CPU allocation; 'Blocked,' where it cannot proceed until a particular resource is available; 'Waiting,' where it awaits another thread to perform a specific action or notification; 'Timed Waiting,' similar to 'Waiting,' but occurs for a specified period; and 'Terminated,' where the thread completes its execution. Understanding the thread life cycle is key for managing and controlling thread execution within applications.
Java manages error handling through its robust exception handling mechanism, which allows the definition and handling of exceptions separately from the main code logic. Key components include the 'try' block to enclose code that might throw an exception; 'catch' blocks to handle specific exceptions; 'finally' block to execute code after 'try' or 'catch' regardless of outcome; and 'throw' keyword to explicitly throw exceptions. The 'throws' keyword can denote methods that might throw exceptions, promoting clear but flexible error-handling paths. This structure encapsulates error management distinctly, promoting cleaner code and effective debugging.
Abstract classes in Java can have both abstract methods (without body) and concrete methods (with body), and they are used to provide a base class with some common functionality that can be extended by subclasses. Interfaces, on the other hand, can only contain abstract methods until Java 8, after which they can include default and static methods. Interfaces are intended to define a contract for the implementing classes without providing any method implementation. Abstract classes allow for shared code and can have instance variables, while interfaces ensure that classes adhere to a method signature contract, promoting flexibility and multiple inheritance. Abstract classes are instantiated by subclassing, whereas interfaces are implemented by classes.