0% found this document useful (0 votes)
19 views32 pages

Java Unit 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views32 pages

Java Unit 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

OOPs in java

Unit 1:

Long answer type:-

1) 1. Explain about Object-Oriented Programming (OOP)? .Explain its four main


principles?
Answer:-

 OOP is a way of programming where real-world entities are represented as objects.

 Each object has attributes (data) and behaviors (methods).

 Java is an OOP language because it uses classes and objects.

Example:

 Object: Box

o Attributes: length, width, height

o Behaviors: calculateVolume(), calculateSurfaceArea()

Key Features of OOP

Feature Meaning Example

Object Real-world entity Box

Class Blueprint for objects class Box { ... }

Encapsulation Data hiding using methods Private length + getter/setter

Inheritance Reuse code from another class class ColoredBox extends Box {}

Overloaded/Overridden
Polymorphism Same method behaves differently
methods

Hide internal details, show


Abstraction Abstract class/interface Shape
functionality

3. Four Main Principles of OOP

(a) Encapsulation

 Meaning: Keep data safe inside a class, access it via methods.

 Advantage: Protects data from unwanted changes.


Example Code:

class Box {

private double length;

private double width;

private double height;

public void setDimensions(double l, double w, double h) {

length = l;

width = w;

height = h;

public double calculateVolume() {

return length * width * height;

(b) Inheritance

 Meaning: A child class inherits properties and methods from a parent class.

 Advantage: Reuse code, avoid repetition.

Example Code:

class Box {

void displayDimensions() {

System.out.println("This is a box");

class ColoredBox extends Box {


void displayColor() {

System.out.println("This box is red");

(c) Polymorphism

 Meaning: Same method can act differently in different situations.

 Example Code:

class Box {

void display() {

System.out.println("Displaying box");

class ColoredBox extends Box {

void display() { // Overriding

System.out.println("Displaying colored box");

(d) Abstraction

 Meaning: Show only necessary details to the user, hide complex details.

 Example Code:

abstract class Shape {

abstract void calculateVolume();

class Box extends Shape {


double length, width, height;

void calculateVolume() {

System.out.println("Volume = " + (length * width * height));

4. OOP Concept Flowchart (Easy Version)

Object-Oriented Programming

-----------------------------------------

Encapsulation Inheritance Polymorphism Abstraction

| | | |

Data hiding Code reuse Many forms Hide details

Getter/Setter Parent→Child Overload/Override Show necessary

5. Conclusion

 OOP allows real-world objects to be modeled in programs.

 Its four main principles — Encapsulation, Inheritance, Polymorphism, Abstraction —


make programs organized, reusable, and easy to maintain.

2) Explain in detail various looping statements supported by Java ?


Answer:-

Looping statements allow a set of instructions to be executed repeatedly until a condition is


satisfied.

->Java supports 3 main types of loops:


1. for loop
2. while loop
3. do-while loop
 Loops help to reduce code repetition and make programs efficient.

2. Types of Loops in Java


(a) For Loop
 Definition: A loop that executes a block of code a fixed number of times.

 Syntax:
for(initialization; condition; update) {
// statements
}

 Example: Print numbers from 1 to 5


for(int i = 1; i <= 5; i++) {
System.out.println(i);
}

 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++)

(b) While Loop


 Definition: A loop that executes a block of code as long as the condition is true.

 Syntax:
while(condition) {
// statements
}

 Example: Print numbers from 1 to 5


int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}

 Explanation:
o Checks the condition first, then executes the block.
o If the condition is false initially, the loop may not execute at all.

(c) Do-While Loop


 Definition: Executes the block of code at least once, then checks the condition.

 Syntax:
do {
// statements
} while(condition);

 Example: Print numbers from 1 to 5


int i = 1;
do {

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:
***
***
***

4. Loop Control Statements


 Java provides special statements to control loops:

1. break → Exits the loop immediately


for(int i=1;i<=5;i++){

if(i==3) break; // stops loop when i=3

System.out.println(i);

}
Output: 1 2

2. continue → Skips the current iteration and continues with next

for(int i=1;i<=5;i++){

if(i==3) continue; // skips i=3

System.out.println(i);

}
Output: 1 2 4 5

3. return → Exits from the method containing the loop

5. Flowchart of Looping Statements


Start
|
----------------
| | |
For While Do-While
| | |
Execute block based on condition
| | |
----------------
|
End

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.

 Java supports two main types of data types:

1. Primitive data types

2. Non-primitive (Reference) data types

2. Primitive Data Types

 Definition: Built-in data types that store single values and are fast and simple.

 Java has 8 primitive data types:

Data Type Size Description Example

byte 1 byte Small integer (-128 to 127) byte b = 10;

short 2 bytes Small integer (-32,768 to 32,767) short s = 1000;

Int 4 bytes Integer (-2^31 to 2^31-1) int i = 5000;

long 8 bytes Large integer (-2^63 to 2^63-1) long l = 100000L;

float 4 bytes Decimal number float f = 10.5f;

double 8 bytes Large decimal number double d = 20.99;

char 2 bytes Single character char c = 'A';

boolean 1 bit True/False value boolean flag = true;

Example:

int age = 20;

float height = 5.7f;

char grade = 'A';

boolean isPassed = true;


3. Non-Primitive (Reference) Data Types

 Definition: Objects and arrays that refer to a memory location.

 Examples:

1. String → Stores text

2. String name = "Deepthi";

3. Array → Stores multiple values of the same type

4. int marks[] = {80, 90, 85};

5. Classes/Objects → User-defined data types

6. class Student {

7. String name;

8. int rollNo;

9. }

10. Student s1 = new Student();

11. s1.name = "Deepthi";

12. s1.rollNo = 101;

4. Type Conversion in Java

1. Implicit type casting (Widening) – smaller type → bigger type automatically

2. int i = 100;

3. double d = i; // int to double

4. Explicit type casting (Narrowing) – bigger type → smaller type manually

5. double d = 20.99;

6. int i = (int)d; // double to int

5. Summary Table

Category Data Type Example

int, float, double, byte, short, long, char,


Primitive int age = 20;
boolean
Category Data Type Example

Non- String name =


String, Array, Class, Interface
Primitive "Deepthi";

6. Conclusion

 Java provides various data types to store different kinds of information.

 Primitive types are fast and simple, while non-primitive types allow more complex
structures.

 Understanding data types is essential for memory management and program


correctness.

4.Explain in detail about the operation of Java Virtual Machine ?

Answer:-

. Introduction

 JVM is a virtual computer that executes Java programs.

 It allows Write Once, Run Anywhere (WORA) because the same bytecode runs on
any platform.

Flow of Java Program:

Java Code (.java) → Compiler → Bytecode (.class) → JVM → Program Runs

2. Components of JVM

Component Purpose

Class Loader Loads .class files into JVM memory

Runtime Data Area Stores memory for objects, variables, method calls

Execution Engine Executes bytecode (Interpreter + JIT Compiler)

Garbage Collector Frees memory used by unused objects

Native Interface Connects Java with non-Java code


3. How JVM Works (Step by Step)

1. Write Java code in .java file.

2. Compile code to bytecode (.class) using javac.

3. Class Loader loads bytecode into JVM memory.

4. Execution Engine runs bytecode:

o Interpreter reads bytecode line by line.

o JIT compiler converts bytecode into machine code for speed.

5. Garbage Collector removes unused objects automatically.

6. Program runs successfully on any platform.

4. Simple JVM Diagram

Java Code (.java)

Compiler

Bytecode (.class)

----------------

| Class Loader |

----------------

----------------

| Runtime Data|

| Area |

----------------

--------------------

| Execution Engine |
| Interpreter/JIT |

--------------------

Garbage Collector

Program Runs

5. Advantages

 Platform independent

 Automatic memory management

 Secure execution

 Supports multithreading

6. Conclusion

 JVM makes Java platform-independent, secure, and efficient.

 It is the core part of Java execution.

5.Develop a Java program to display the following output: b) 1 b) * 2 3 4 5 6 7 8 9 10 ***


***** ******* ***** *** *

Q5. Java Program to Display the Given Pattern

1. Aim

 To develop a Java program to display the following pattern:

23

456

7 8 9 10
*

***

*****

*******

*****

***

2. Algorithm

1. Initialize a counter num = 1 for the number pattern.

2. Use nested loops to print the number triangle:

o Outer loop for rows (1 to 4)

o Inner loop prints numbers incrementally.

3. Use nested loops to print the asterisk pyramid:

o Outer loop for top pyramid (rows = 1 to 4)

o Inner loop for spaces

o Inner loop for asterisks

4. Use nested loops to print the bottom inverted pyramid:

o Outer loop for rows (rows = 3 to 1)

o Inner loop for spaces

o Inner loop for asterisks

3. Java Program

class PatternProgram {

public static void main(String[] args) {

int num = 1;

// Number triangle
for (int i = 1; i <= 4; i++) { // rows

for (int j = 1; j <= i; j++) { // numbers in a row

System.out.print(num + " ");

num++;

System.out.println();

// Top half of star pyramid

for (int i = 1; i <= 4; i++) {

for (int j = 4; j > i; j--) { // spaces

System.out.print(" ");

for (int k = 1; k <= (2*i-1); k++) { // stars

System.out.print("*");

System.out.println();

// Bottom half of inverted star pyramid

for (int i = 3; i >= 1; i--) {

for (int j = 4; j > i; j--) { // spaces

System.out.print(" ");

for (int k = 1; k <= (2*i-1); k++) { // stars

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:

o Spaces decrease as row number increases

o Stars increase as 2*row-1

3. Bottom inverted pyramid:

o Spaces increase as row number decreases

o Stars decrease as 2*row-1

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.

2. Executed by the Java Virtual Machine (JVM).

3. Stored in a .class file.

 Example:

class Hello {

public static void main(String[] args) {

System.out.println("Hello Java");

 After compiling with javac Hello.java, a Hello.class file is generated, which contains
bytecode.

Advantages of Bytecode:

1. Platform Independence – Same bytecode runs on any OS with JVM.

2. Security – JVM verifies bytecode before execution.

3. Optimized Execution – Can be interpreted or compiled by JIT compiler.

2. States of Java Program Execution

A Java program execution can be divided into three main states:

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

The Execution Engine of JVM executes the bytecode. Includes:

3.Execution • Interpreter: Executes line by line

• JIT Compiler: Converts bytecode to machine code for faster execution

• Runtime Data Areas: Stores variables, objects, stack, etc.

3. Simple Flow Diagram of Java Program Execution

Java Source Code (.java)

[Java Compiler: javac]

Bytecode (.class)

[Class Loader]

Runtime Data Area

[Execution Engine]

/ \

Interpreter JIT Compiler

Program Execution

4. Summary

 Bytecode is the platform-independent code executed by JVM.

 Java program execution has three main states: Compilation → Loading/Linking →


Execution.
 JVM ensures security, platform independence, and efficient execution.

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;
}

5. Differences Between Control Statements

Decision-
Feature Looping Jump Statements
making

Purpose Choose path Repeat block Alter execution flow

Examples if, if-else, switch for, while, do- break, continue,


Decision-
Feature Looping Jump Statements
making

while return

Executes
Executes based Changes normal
Execution multiple
on condition flow
times

Conditional Skipping or exiting


Use Repetition
logic loops/methods

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.

8. What is an Operator? Explain type of operators in Java with example programs?


Answer:-
Introduction
 In Java, an operator is a symbol that tells the compiler to perform specific
mathematical, logical, or relational operations on one or more operands.
 Example: +, -, *, /, ==, &&, etc.
 Operators are essential for performing calculations, comparisons, and decision-
making in programs.

2. Types of Operators in Java


Java operators are classified into several types:

Type Description Example

Arithmetic Used to perform mathematical


+, -, *, /, %
Operators calculations

Relational
Used to compare values ==, !=, >, <, >=, <=
Operators

Used to perform logical


Logical Operators &&, `
operations

Assignment Used to assign values =, +=, -=, *=, /=


Type Description Example

Operators

Unary Operators Operate on single operand +, -, ++, --, !

Conditional operator that works condition ? value1


Ternary Operator
on three operands : value2

Bitwise
Perform operations at bit level &, `
Operators

3. Examples of Each Operator


(a) Arithmetic Operators
int a = 10, b = 3;
System.out.println("a+b=" + (a+b));
System.out.println("a-b=" + (a-b));
System.out.println("a*b=" + (a*b));
System.out.println("a/b=" + (a/b));
System.out.println("a%b=" + (a%b));
(b) Relational Operators
int x = 10, y = 20;
System.out.println(x > y); // false
System.out.println(x == y); // false
System.out.println(x != y); // true
(c) Logical Operators
boolean p = true, q = false;
System.out.println(p && q); // false
System.out.println(p || q); // true
System.out.println(!p); // false
(d) Assignment Operators
int num = 10;
num += 5; // num = num + 5
System.out.println(num); // 15
(e) Unary Operators
int n = 5;
n++; // Increment by 1
System.out.println(n); // 6
n--; // Decrement by 1
System.out.println(n); // 5
(f) Ternary Operator
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max); // 20
(g) Bitwise Operators
int m = 5, n = 3;
System.out.println(m & n); // 1
System.out.println(m | n); // 7
System.out.println(m ^ n); // 6

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

Loop Type Syntax

for loop for(initialization; condition; update){ statements; }

while loop while(condition){ statements; }

do-while loop do { statements; } while(condition);

4. Program to Print Even Numbers (2 to Limit)

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();

System.out.println("Using for loop:");


for(int i=2; i<=limit; i+=2) {
System.out.print(i + " ");
}

System.out.println("\nUsing while loop:");


int j = 2;
while(j <= limit) {
System.out.print(j + " ");
j += 2;
}

System.out.println("\nUsing do-while loop:");


int k = 2;
do {
System.out.print(k + " ");
k += 2;
} while(k <= limit);
}
}

4. Sample Output (Limit = 10)


Using for loop: 2 4 6 8 10
Using while loop: 2 4 6 8 10
Using do-while loop: 2 4 6 8 10

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.

--- Bank Menu ---


1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter your choice: 3
Current balance: ₹1500

--- Bank Menu ---


1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter your choice: 2
Enter amount to withdraw: ₹700
₹700 withdrawn successfully.

--- Bank Menu ---


1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter your choice: 4
Exiting... Thank you!

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:-

To find and display the roots of a quadratic equation ax2+bx+c=0ax^2 + bx + c =


0ax2+bx+c=0 using class, object, and method concepts.
Algorithm:
1. Start
2. Create a class Quadratic with:
o Variables a, b, c to store coefficients
o Method calculateRoots() to compute and display roots
3. In main() method:
o Create an object of Quadratic class
o Accept coefficients a, b, c from the user
o If a == 0, display error message (not a quadratic equation)
o Else, call calculateRoots() method
4. In calculateRoots() method:
o Compute discriminant D=b2−4acD = b^2 - 4acD=b2−4ac
o If D>0D > 0D>0, display two real and distinct roots
o If D==0D == 0D==0, display one real and equal root
o If D<0D < 0D<0, display two complex roots
5. End

2. Program
import java.util.Scanner;

// Class to represent a quadratic equation


class Quadratic {
double a, b, c; // Coefficients
// Method to calculate and display roots
void calculateRoots() {
double discriminant = b * b - 4 * a * c;

if (discriminant > 0) { // Two real and distinct roots


double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Roots are real and distinct: " + root1 + " , " + root2);
} else if (discriminant == 0) { // Two real and equal roots
double root = -b / (2 * a);
System.out.println("Roots are real and equal: " + root);
} else { // Complex roots
double realPart = -b / (2 * a);
double imagPart = Math.sqrt(-discriminant) / (2 * a);
System.out.println("Roots are complex: " + realPart + " + " + imagPart + "i , " +
realPart + " - " + imagPart + "i");
}
}
}

// 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:-

1. What is the purpose of the System.out.println() statement in Java?


 Answer: It is used to print output to the console and move the cursor to a new line.
2. What are the principles of Object-Oriented Programming?
 Answer:
1. Encapsulation – Wrapping data and methods together
2. Inheritance – Acquiring properties from another class
3. Polymorphism – Ability to take many forms
4. Abstraction – Hiding implementation details

3. What are the escape sequences in Java? Give three examples.


 Answer: Escape sequences are special characters used in strings.
Examples: \n (new line), \t (tab), \\ (backslash)

4. Define and provide an example of type casting in Java.


 Answer: Type casting is converting one data type to another.
o Example (implicit): int x = 10; double y = x;
o Example (explicit): double d = 9.78; int i = (int)d;

5. Differentiate between instance variable, local variable, and static variable with
an example.

Variable
Description Example
Type

Instance Belongs to object, unique for each object int age;

Declared inside a method, exists only in


Local int x = 5;
method

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.

7. What is the output of the following code?


public class TernaryExample {
public static void main(String[] args) {
int result = (12 > 9) ? 20 : 25;
System.out.println("The result is: " + result);
}
}
 Answer: The result is: 20

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");

9. Why is Java said to be a secure programming language?


 Answer: Java is secure because it does not allow direct memory access, uses
bytecode verification, and provides built-in security features like the sandbox
environment.

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();
}
}

11. List out the various types of operators in Java.


 Answer: Arithmetic, Relational, Logical, Assignment, Unary, Ternary, Bitwise

12. List any four object-oriented features of Java.


 Answer: Encapsulation, Inheritance, Polymorphism, Abstraction

13. Summarize the jump statements in Java?


 Answer: Jump statements alter the normal flow of execution:
1. break – exit loop/switch
2. continue – skip current iteration
3. return – exit method

14. Define Byte Code.


 Answer: Byte code is the intermediate code generated by Java compiler which can
be executed by Java Virtual Machine (JVM).

15. What is the use of “break” statement in Java?


 Answer: break is used to exit from a loop or switch statement immediately.

You might also like