Java Unit 1
Java Unit 1
Unit 1:
Example:
Object: Box
Inheritance Reuse code from another class class ColoredBox extends Box {}
Overloaded/Overridden
Polymorphism Same method behaves differently
methods
(a) Encapsulation
class Box {
length = l;
width = w;
height = h;
(b) Inheritance
Meaning: A child class inherits properties and methods from a parent class.
Example Code:
class Box {
void displayDimensions() {
System.out.println("This is a box");
(c) Polymorphism
Example Code:
class Box {
void display() {
System.out.println("Displaying box");
(d) Abstraction
Meaning: Show only necessary details to the user, hide complex details.
Example Code:
void calculateVolume() {
Object-Oriented Programming
-----------------------------------------
| | | |
5. Conclusion
Syntax:
for(initialization; condition; update) {
// statements
}
Explanation:
1. initialization → executed once at the start (i = 1)
2. condition → checked before each iteration (i <= 5)
3. update → executed after each iteration (i++)
Syntax:
while(condition) {
// statements
}
Explanation:
o Checks the condition first, then executes the block.
o If the condition is false initially, the loop may not execute at all.
Syntax:
do {
// statements
} while(condition);
System.out.println(i);
i++;
} while(i <= 5);
Explanation:
o Executes the statements first, then checks the condition.
o Ensures the loop runs at least once even if the condition is false.
3. Nested Loops
A loop inside another loop is called a nested loop.
Example: Print a 3×3 star pattern
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
***
***
***
System.out.println(i);
}
Output: 1 2
for(int i=1;i<=5;i++){
System.out.println(i);
}
Output: 1 2 4 5
6. Conclusion
Java provides for, while, and do-while loops to repeat instructions
efficiently.
Nested loops and control statements like break and continue give
more flexibility in programming.
Loops are essential for reducing code repetition and handling tasks
like printing patterns, iterating arrays, or processing data.
3.Explain different data types in Java with suitable example?
Answer:-
1. Introduction
In Java, a data type defines the type of data a variable can hold.
Definition: Built-in data types that store single values and are fast and simple.
Example:
Examples:
6. class Student {
7. String name;
8. int rollNo;
9. }
2. int i = 100;
5. double d = 20.99;
5. Summary Table
6. Conclusion
Primitive types are fast and simple, while non-primitive types allow more complex
structures.
Answer:-
. Introduction
It allows Write Once, Run Anywhere (WORA) because the same bytecode runs on
any platform.
2. Components of JVM
Component Purpose
Runtime Data Area Stores memory for objects, variables, method calls
Compiler
Bytecode (.class)
----------------
| Class Loader |
----------------
----------------
| Runtime Data|
| Area |
----------------
--------------------
| Execution Engine |
| Interpreter/JIT |
--------------------
Garbage Collector
Program Runs
5. Advantages
Platform independent
Secure execution
Supports multithreading
6. Conclusion
1. Aim
23
456
7 8 9 10
*
***
*****
*******
*****
***
2. Algorithm
3. Java Program
class PatternProgram {
int num = 1;
// Number triangle
for (int i = 1; i <= 4; i++) { // rows
num++;
System.out.println();
System.out.print(" ");
System.out.print("*");
System.out.println();
System.out.print(" ");
System.out.print("*");
System.out.println();
}
4. Output
23
456
7 8 9 10
***
*****
*******
*****
***
5. Explanation
1. Number triangle: Counter num increments in each inner loop to print numbers in
rows.
2. Top pyramid:
6.What is Byte Code? Interpret the different states of Java Program execution?
Answer:-
1. What is Bytecode?
Definition: Bytecode is the intermediate code generated by the Java compiler after
compiling a .java file.
Properties:
1. It is platform-independent.
Example:
class Hello {
System.out.println("Hello Java");
After compiling with javac Hello.java, a Hello.class file is generated, which contains
bytecode.
Advantages of Bytecode:
State Description
1. Compilation The Java source code (.java) is compiled by javac into bytecode (.class).
The Class Loader loads the bytecode into JVM memory and prepares it
2. Loading/Linking
for execution.
State Description
Bytecode (.class)
[Class Loader]
[Execution Engine]
/ \
Program Execution
4. Summary
7. Distinguish in detail about various control statements are used in Java with suitable
example program?
Answer:-
1. Introduction
Control statements in Java are used to control the flow of program execution. They
help decide:
Which statements to execute
How many times to execute a statement
When to skip or exit a block of code
Java provides three main types of control statements:
1. Decision-making statements
2. Looping statements
3. Jump statements
2. Decision-Making Statements
Decision-making statements allow the program to choose a path based on a
condition.
if statement: Executes code if a condition is true.
int num = 5;
if(num > 0)
System.out.println("Positive number");
if-else statement: Provides two alternative paths.
if(num % 2 == 0)
System.out.println("Even number");
else
System.out.println("Odd number");
switch statement: Chooses among multiple options.
int day = 2;
switch(day) {
case 1: System.out.println("Sunday"); break;
case 2: System.out.println("Monday"); break;
default: System.out.println("Other day");
}
3. Looping Statements
Looping statements are used to repeat a block of code multiple times.
for loop: Repeats a block a fixed number of times.
for(int i=1; i<=5; i++)
System.out.println(i);
while loop: Repeats while a condition is true.
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}
do-while loop: Executes at least once, then checks the condition.
int i = 1;
do {
System.out.println(i);
i++;
} while(i <= 5);
4. Jump Statements
Jump statements alter the normal flow of execution.
break: Exits a loop or switch immediately.
for(int i=1;i<=5;i++){
if(i==3) break;
System.out.println(i);
}
Output: 1 2
continue: Skips the current iteration and moves to the next iteration.
for(int i=1;i<=5;i++){
if(i==3) continue;
System.out.println(i);
}
Output: 1 2 4 5
return: Exits the current method.
int sum(int a,int b) {
return a + b;
}
Decision-
Feature Looping Jump Statements
making
while return
Executes
Executes based Changes normal
Execution multiple
on condition flow
times
6. Conclusion
Decision-making statements select the path based on conditions.
Looping statements repeat tasks efficiently.
Jump statements modify the normal flow of execution.
Using these statements properly makes programs organized, readable, and easy to
maintain.
Relational
Used to compare values ==, !=, >, <, >=, <=
Operators
Operators
Bitwise
Perform operations at bit level &, `
Operators
4. Conclusion
Operators in Java allow us to perform calculations, comparisons, and logical
operations easily.
Choosing the right operator type is essential for writing efficient and readable
programs.
Java provides a wide range of operators to handle arithmetic, relational, logical,
assignment, unary, ternary, and bitwise operations.
9. Explain different types of iterative statements in Java with their syntax. Write
programs to print all even numbers from 2 up to a given limit using each loop?
Answer:-
Introduction
Iterative statements or loops are used to execute a block of code repeatedly until a
condition becomes false.
Java supports three types of loops:
1. for loop
2. while loop
3. do-while loop
2. Syntax of Loops
import java.util.Scanner;
class EvenNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the limit: ");
int limit = sc.nextInt();
5. Conclusion
Loops help in repeating tasks efficiently.
For loop: Use when the number of iterations is known.
While loop: Use when the condition is checked before execution.
Do-while loop: Executes at least once before checking the condition.
10. Write a menu-driven Java program using a switch statement to manage a simple
bank account. The account should start with a balance of ₹1000. The program should
display this menu: • Deposit • Withdraw • Check Balance • Exit?
To create a menu-driven Java program to manage a simple bank account with options
to Deposit, Withdraw, Check Balance, and Exit.
Algorithm:
1. Start
2. Initialize balance = 1000
3. Repeat the following until user chooses Exit:
a. Display the menu:
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
b. Accept user choice
c. Use switch statement to perform operation:
o Case 1 (Deposit):
i. Input deposit amount
ii. If amount > 0, add to balance
iii. Display success message
o Case 2 (Withdraw):
i. Input withdrawal amount
ii. If amount > 0 and ≤ balance, subtract from balance
iii. Display success or error message
o Case 3 (Check Balance):
i. Display current balance
o Case 4 (Exit):
i. Display exit message
o Default: Display invalid choice message
4. End
2. Program
import java.util.Scanner;
class BankAccount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double balance = 1000; // Initial balance
int choice;
do {
// Display menu
System.out.println("\n--- Bank Menu ---");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.print("Enter amount to deposit: ₹");
double deposit = sc.nextDouble();
if(deposit > 0) {
balance += deposit;
System.out.println("₹" + deposit + " deposited successfully.");
} else {
System.out.println("Invalid amount!");
}
break;
case 2:
System.out.print("Enter amount to withdraw: ₹");
double withdraw = sc.nextDouble();
if(withdraw > 0 && withdraw <= balance) {
balance -= withdraw;
System.out.println("₹" + withdraw + " withdrawn successfully.");
} else {
System.out.println("Invalid or insufficient balance!");
}
break;
case 3:
System.out.println("Current balance: ₹" + balance);
break;
case 4:
System.out.println("Exiting... Thank you!");
break;
default:
System.out.println("Invalid choice! Please try again.");
}
} while(choice != 4); // Repeat until user chooses Exit
}
}
3. Sample Output
--- Bank Menu ---
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter your choice: 1
Enter amount to deposit: ₹500
₹500 deposited successfully.
4. Explanation
Initial balance: ₹1000
Menu: Displayed in each iteration using a do-while loop
Switch statement: Handles the user-selected option
Validation: Ensures deposits are positive and withdrawals do not exceed balance
Loop: Continues until the user selects Exit
5. Conclusion
This menu-driven program demonstrates how to manage a simple bank account.
Using switch statements makes it easy to handle multiple options.
Do-while loop ensures the menu keeps repeating until the user exits.
11.Write a java program that display the roots of a quadratic equation using class,
object and method concepts?
Answer:-
2. Program
import java.util.Scanner;
// Main class
public class QuadraticRoots {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Quadratic q = new Quadratic(); // Create object of Quadratic class
// Input coefficients
System.out.print("Enter coefficient a: ");
q.a = sc.nextDouble();
System.out.print("Enter coefficient b: ");
q.b = sc.nextDouble();
System.out.print("Enter coefficient c: ");
q.c = sc.nextDouble();
// Check if a is zero
if (q.a == 0) {
System.out.println("Coefficient 'a' cannot be zero in a quadratic equation.");
} else {
// Calculate and display roots
q.calculateRoots();
}
sc.close(); // Close scanner
}
}
3. Sample Output
Case 1: Two real and distinct roots
Enter coefficient a: 1
Enter coefficient b: -5
Enter coefficient c: 6
Roots are real and distinct: 3.0 , 2.0
Case 2: Real and equal roots
Enter coefficient a: 1
Enter coefficient b: -2
Enter coefficient c: 1
Roots are real and equal: 1.0
Case 3: Complex roots
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
Roots are complex: -1.0 + 2.0i , -1.0 - 2.0i
Case 4: a = 0 (not a quadratic equation)
Enter coefficient a: 0
Enter coefficient b: 2
Enter coefficient c: 3
Coefficient 'a' cannot be zero in a quadratic equation.
4. Explanation
Class: Quadratic stores coefficients and has a method to calculate roots.
Object: q is created in main() to access the method.
Method: calculateRoots() computes discriminant and prints the roots based on its
value.
Math.sqrt() is used to calculate the square root.
The program handles real-distinct, real-equal, and complex roots, and validates that
a ≠ 0.
One Mark:-
5. Differentiate between instance variable, local variable, and static variable with
an example.
Variable
Description Example
Type
static int
Static Belongs to class, shared by all objects
count;
6. What is encapsulation?
Answer: Encapsulation is the wrapping of data (variables) and methods together in
a class and hiding the data from outside access using access modifiers.
8. How would you use the if-else statement to check if a number is even or odd?
Answer:
if(n % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
10. Write a simple Java program to display the sum of two numbers entered by the
user.
import java.util.Scanner;
class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;
System.out.println("Sum: " + sum);
sc.close();
}
}