Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Answers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

1. Explain the important features of java language.

Ans: Java is a versa le, object-oriented programming language with several key features that
make it widely used in so ware development:

Object-Oriented: Java is based on the object-oriented programming (OOP) paradigm, which


means it focuses on objects and classes. This allows for be er code reusability, modularity, and
easier maintenance.

Pla orm-Independent: Java's "Write Once, Run Anywhere" (WORA) philosophy is achieved
through the Java Virtual Machine (JVM). Once compiled, Java code can run on any device or
opera ng system that has a JVM, making it highly portable.

Simple: Java is designed to be easy to learn and use. Its syntax is clean and consistent, and it
avoids many of the complexi es of languages like C++ (e.g., pointers).

Secure: Java provides robust security features, such as bytecode verifica on and a security
manager, which ensures that programs can’t access resources without proper authoriza on.

Mul threading: Java supports mul threading, allowing concurrent execu on of two or more
threads. This is beneficial for developing high-performance applica ons, such as games or large-
scale web services.

Robust and Reliable: Java emphasizes error checking at compile- me and run me, with strong
memory management and excep on handling mechanisms. This ensures that Java applica ons
are less prone to crashes.

High Performance: While Java is slower than some compiled languages (like C++), it
compensates with the use of Just-In-Time (JIT) compilers, which improve performance by
compiling bytecode into na ve machine code during execu on.

Extensible and Dynamic: Java is designed to be dynamic and adaptable, suppor ng the addi on
of new methods and variables, and enabling the loading of classes at run me.

2. Explain all the operators in java.


Ans: 1. Arithme c Operators

 These operators are used to perform basic mathema cal opera ons.

Operator Descrip on Example (assuming a = 10, b = 5)

+ Addi on a + b = 15

- Subtrac on a-b=5

* Mul plica on a * b = 50

/ Division (quo ent) a/b=2

% Modulus (remainder) a%b=0


2. Rela onal (Comparison) Operators

 These operators are used to compare two values and return a boolean result (true or false).

Operator Descrip on Example (assuming a = 10, b = 5)

== Equal to a == b is false

!= Not equal to a != b is true

> Greater than a > b is true

< Less than a < b is false

>= Greater than or equal to a >= b is true

<= Less than or equal to a <= b is false

3. Logical Operators

 These operators are used to combine two or more condi ons (boolean expressions).

Operator Descrip on Example (assuming x = true, y = false)

&& Logical AND x && y is false

` `

! Logical NOT !x is false

4. Assignment Operators

 Assignment operators are used to assign values to variables.

Operator Descrip on Example (assuming a = 10)

= Assign a = 10

+= Add and assign a += 5 (same as a = a + 5)

-= Subtract and assign a -= 5 (same as a = a - 5)

*= Mul ply and assign a *= 5 (same as a = a * 5)

/= Divide and assign a /= 5 (same as a = a / 5)

%= Modulus and assign a %= 5 (same as a = a % 5)


5. Unary Operators

 These operators only require one operand.

Operator Descrip on Example (assuming a = 10, b = 5)

+ Unary plus +a = 10

- Unary minus -b = -5

++ Increment (prefix/pos ix) ++a or a++ (a becomes 11)

-- Decrement (prefix/pos ix) --a or a-- (a becomes 9)

! Logical NOT !true = false

6. Bitwise Operators

 These operators work on bits and perform bit-level opera ons.

Operator Descrip on Example (assuming a = 5, b = 3)

& Bitwise AND a & b = 1 (0101 & 0011 = 0001)

` ` Bitwise OR

^ Bitwise XOR a ^ b = 6 (0101 ^ 0011 = 0110)

~ Bitwise complement ~a = -6 (bitwise NOT of 5)

<< Le shi a << 2 = 20

>> Right shi a >> 2 = 1

>>> Unsigned right shi a >>> 2 = 1

7. Ternary Operator (Condi onal Operator)

 The ternary operator is a shorthand for if-else statements.

Operator Descrip on Example

?: Condi onal result = (a > b) ? a : b

In this example, if a is greater than b, a is assigned to result; otherwise, b is assigned.


3. Explain all the condi onal statements in java .Write a program to find the largest of
three numbers

Ans:

 if Statement: Executes a block of code if the condi on is true.

java

Copy code

if (condi on) {

// code to be executed if condi on is true

 if-else Statement: Executes one block of code if the condi on is true, and another if it is
false.

java

Copy code

if (condi on) {

// code to be executed if condi on is true

} else {

// code to be executed if condi on is false

 if-else-if Ladder: Used to test mul ple condi ons sequen ally.

java

Copy code

if (condi on1) {

// code for condi on1

} else if (condi on2) {

// code for condi on2

} else {

// code if all condi ons are false

 Switch Statement: A be er alterna ve to a series of if-else statements when dealing with


mul ple condi ons based on a single variable.

java
Copy code

switch(expression) {

case value1:

// code block for value1

break;

case value2:

// code block for value2

break;

default:

// default code block

Program to Find the Largest of Three Numbers

java

Copy code

import java.u l.Scanner;

public class LargestOfThree {

public sta c void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter three numbers: ");

int num1 = sc.nextInt();

int num2 = sc.nextInt();

int num3 = sc.nextInt();

int largest;

if (num1 >= num2 && num1 >= num3) {

largest = num1;

} else if (num2 >= num1 && num2 >= num3) {

largest = num2;

} else {

largest = num3;

System.out.println("The largest number is: " + largest);


}

4. What is an array. Explain the different types of arrays with example


Ans: An array is a data structure in Java that stores mul ple values of the same data type in a
con guous block of memory. It is used to store a fixed-size sequence of elements. Arrays are
useful when you want to group mul ple variables of the same type together, such as a list of
numbers or names.

1. Single-Dimensional Array: A linear array that holds a list of elements of the same type.

2. Mul -Dimensional Array: An array of arrays, like a table or matrix where data is stored in
mul ple rows and columns.

Single-Dimensional Array

A single-dimensional array can be thought of as a list. The elements are stored in con guous
memory loca ons, and each element can be accessed by its index.

Syntax:

java

Copy code

dataType[] arrayName = new dataType[size];

Example:

java

Copy code

public class SingleDimArray {

public sta c void main(String[] args) {

// Declare and ini alize a single-dimensional array

int[] numbers = {10, 20, 30, 40, 50};

// Accessing array elements using indices

for (int i = 0; i < numbers.length; i++) {

System.out.println("Element at index " + i + ": " + numbers[i]);

Mul -Dimensional Array


A mul -dimensional array (such as a two-dimensional array) can be thought of as a table with
rows and columns.

Syntax:

java

Copy code

dataType[][] arrayName = new dataType[rows][columns];

Example:

java

Copy code

public class Mul DimArray {

public sta c void main(String[] args) {

// Declare and ini alize a 2D array (3x3 matrix)

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

// Accessing elements of the 2D array using nested loops

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println(); // New line a er each row

5. Explain the while, do while and for loop


Ans: Loops in Java allow you to execute a block of code repeatedly un l a certain condi on is
met. The three main types of loops in Java are:

1. While Loop

2. Do-While Loop
3. For Loop

1. While Loop

The while loop checks the condi on first, and if the condi on is true, it executes the code block. It
con nues looping as long as the condi on remains true.

Syntax:

java

Copy code

while (condi on) {

// code to be executed

 The loop will not execute even once if the condi on is false ini ally.

 Commonly used when the number of itera ons is not known beforehand.

Example:

java

Copy code

public class WhileExample {

public sta c void main(String[] args) {

int i = 1;

while (i <= 5) {

System.out.println("Count: " + i);

i++;

2. Do-While Loop

The do-while loop is similar to the while loop, but it executes the code block at least once before
checking the condi on. A er execu ng, it checks the condi on and repeats the loop if the condi on
is true.

Syntax:

java

Copy code

do {
// code to be executed

} while (condi on);

 The code block is executed at least once, even if the condi on is false ini ally.

Example:

java

Copy code

public class DoWhileExample {

public sta c void main(String[] args) {

int i = 1;

do {

System.out.println("Count: " + i);

i++;

} while (i <= 5);

3. For Loop

The for loop is best suited when you know the number of itera ons in advance. It includes
ini aliza on, condi on, and increment/decrement parts in a single line.

Syntax:

java

Copy code

for (ini aliza on; condi on; update) {

// code to be executed

 Ini aliza on: The variable is ini alized (runs only once).

 Condi on: The loop runs as long as the condi on is true.

 Update: The variable is updated a er each itera on.

Example:

java

Copy code

public class ForExample {


public sta c void main(String[] args) {

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

System.out.println("Count: " + i);

6. Write a Java Program to Add and Subtract Two Matrices

Ans: public class MatrixOpera ons {

public sta c void main(String[] args) {

int rows = Integer.parseInt(args[0]);

int cols = Integer.parseInt(args[1]);

int[][] matrix1 = { {1, 2}, {3, 4} };

int[][] matrix2 = { {5, 6}, {7, 8} };

int[][] sum = new int[rows][cols];

int[][] difference = new int[rows][cols];

// Adding two matrices

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

sum[i][j] = matrix1[i][j] + matrix2[i][j];

difference[i][j] = matrix1[i][j] - matrix2[i][j];

7. List and define the features of object oriented programming language


Ans: All object-oriented programming languages provide mechanisms that help you implement the
object-oriented model. They are encapsula on, inheritance, and polymorphism.

1. Encapsula on

Encapsula on is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. One way to think about encapsula on is as a
protec ve wrapper that prevents the code and data from being arbitrarily accessed by other code
defined outside the wrapper. Access to the code and data inside the wrapper is ghtly controlled
through a well-defined interface.

Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the
complexity of the implementa on inside the class. Each method or variable in a class may be marked
private or public.

The public interface of a class represents everything that external users of the class need to know, or
may know.

The private methods and data can only be accessed by code that is a member of the class. Therefore,
any other code that is not a member of the class cannot access a private method or variable.

2. Inheritance

Inheritance is the process by, which one object acquires the proper es of another object: This is
important because it supports the concept of hierarchical classifica on.

For example, a Golden Retriever is part of the classifica on dog, which in turn is part of the mammal
class, which is under the larger class animal.

Without the use of hierarchies, each object would need to define all of its characteris cs explicitly. By
use of inheritance, an object need only define those quali es that make it unique within its class.

It can inherit its general a ributes from its parent. Thus, it is the inheritance mechanism that makes
it possible for one object to be a specific instance of a more general case.

3. Polymorphism

Polymorphism (from Greek, meaning "many forms") is a feature that allows one interface to be used
for a general class of ac ons. More generally, the concept of polymorphism is o en expressed by the
phrase "one interface, mul ple methods."

This means that it is possible to design a generic interface to a group of related ac vi es. This helps
reduce complexity by allowing the same interface to be used to specify a general class of ac on.

8. Write a program to find the area of a triangle and explain the basic structure of a java
program
Ans: Java Program to Find the Area of a Triangle:

import java.u l.Scanner; // Import Scanner class for user input

public class TriangleArea {

public sta c void main(String[] args) {

// Create a Scanner object for input

Scanner sc = new Scanner(System.in);

// Prompt user for the base of the triangle

System.out.print("Enter the base of the triangle: ");


double base = sc.nextDouble();

// Prompt user for the height of the triangle

System.out.print("Enter the height of the triangle: ");

double height = sc.nextDouble();

// Calculate the area of the triangle

double area = 0.5 * base * height;

// Display the result

System.out.println("The area of the triangle is: " + area);

Basic Structure of a Java Program:

Every Java program follows a basic structure, and understanding this structure is essen al to
developing Java applica ons. Here's a breakdown of the main components of the program:

1. Package Declara on:

package mypackage;

 This is op onal and specifies the package to which the class belongs. A package is a
namespace that organizes classes and interfaces.

2. Import Statements:

import java.u l.Scanner;

 Import statements allow you to include classes and packages into your program. For
instance, the Scanner class is imported to take user input.

3. Class Declara on:

public class TriangleArea {

 Every Java program must contain at least one class. The class name should match the file
name (in this case, TriangleArea.java).

 public: The class is accessible to other classes.

 class: Keyword used to declare a class.

4. Main Method:

public sta c void main(String[] args) {

 This is the star ng point of the program.

o public: The method is accessible from anywhere.

o sta c: It belongs to the class and not to a specific instance.


o void: It doesn’t return any value.

o String[] args: Command-line arguments can be passed through this array.

5. Statements Inside the Main Method:

 Variable Declara on: Variables such as base, height, and area are declared and used within
the method.

 Input Handling: Using the Scanner class, user input is collected.

 Computa on: The logic for calcula ng the area of the triangle is placed inside the main
method.

 Output: The result is printed using System.out.println().

6. Closing Braces:

 Every class and method has to be properly closed with a brace } to indicate the end.

9. Explain the different data types in java.


Ans: In Java, data types specify the type of value that a variable can store. Java provides two
categories of data types:

1. Primi ve Data Types

2. Non-Primi ve (Reference) Data Types

Primi ve Data Types

1. byte:

o Size: 1 byte

o Default Value: 0

o Use: It stores small integers, ranging from -128 to 127. Useful for saving memory in
large arrays.

Example: byte smallNumber = 100;

2. short:

o Size: 2 bytes

o Default Value: 0

o Use: It stores larger integers than byte, ranging from -32,768 to 32,767.

Example: short mediumNumber = 10000;

3. int:
o Size: 4 bytes

o Default Value: 0

o Use: It is the most commonly used integer type, capable of storing values from -
2,147,483,648 to 2,147,483,647.

Example: int largeNumber = 50000;

4. long:

o Size: 8 bytes

o Default Value: 0L

o Use: For very large integers, ranging from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807.

Example: long veryLargeNumber = 15000000000L;

5. float:

o Size: 4 bytes

o Default Value: 0.0f

o Use: For single-precision floa ng-point numbers. It is suitable for saving memory in
large arrays of floa ng-point numbers.

Example: float decimalNumber = 5.75f;

6. double:

o Size: 8 bytes

o Default Value: 0.0d

o Use: For double-precision floa ng-point numbers. It is the default choice for decimal
values.

Example: double largeDecimalNumber = 19.99;

7. char:

o Size: 2 bytes

o Default Value: '\u0000' (null character)

o Use: To store a single 16-bit Unicode character.

Example:char le er = 'A';

8. boolean:

o Size: Not precisely defined (usually 1 bit)

o Default Value: false

o Use: To store true or false values, typically used for condi onal statements.
Example: boolean isJavaFun = true;

2. Non-Primi ve (Reference) Data Types

Non-primi ve data types are more complex and include:

 Strings: Used to store sequences of characters.

Example: String gree ng = "Hello, World!";

 Arrays: A collec on of similar types of elements stored in a single variable.

Example: int[] numbers = {1, 2, 3, 4, 5};

 Classes and Interfaces: Used to create objects and define methods and proper es.

10. Explain All the Condi onal Statements in Java with Example

Condi onal statements in Java are used to perform different ac ons based on different condi ons.
Here are the main types of condi onal statements:

1. if Statement

The if statement executes a block of code if the specified condi on is true.

Example:

java

Copy code

int number = 10;

if (number > 0) {

System.out.println("The number is posi ve.");

In this example, the message will be printed because the condi on (number > 0) is true.

2. if-else Statement

The if-else statement provides an alterna ve block of code that executes when the condi on is false.

Example:

java

Copy code

int number = -5;

if (number > 0) {
System.out.println("The number is posi ve.");

} else {

System.out.println("The number is not posi ve.");

Here, since the condi on is false, "The number is not posi ve." will be printed.

3. if-else-if Ladder

This structure allows you to check mul ple condi ons sequen ally.

Example:

java

Copy code

int number = 0;

if (number > 0) {

System.out.println("The number is posi ve.");

} else if (number < 0) {

System.out.println("The number is nega ve.");

} else {

System.out.println("The number is zero.");

In this case, the output will be "The number is zero." since all other condi ons are false.

4. switch Statement

The switch statement is a more elegant way to compare a variable against mul ple values.

Example:

java

Copy code

int day = 3;

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");
break;

case 3:

System.out.println("Wednesday");

break;

default:

System.out.println("Other day");

In this example, "Wednesday" will be printed because the value of day is 3. The break statement
prevents the execu on from falling through to the next case.

5. Nested if Statements

You can also place an if statement inside another if statement.

Example:

java

Copy code

int number = 10;

if (number >= 0) {

if (number == 0) {

System.out.println("The number is zero.");

} else {

System.out.println("The number is posi ve.");

} else {

System.out.println("The number is nega ve.");

In this example, "The number is posi ve." will be printed since the first condi on is true and the
second condi on is also true.

11. Repe on od Ques on 4

12. Explain the Concept of Garbage Collec on in Java

Garbage Collec on (GC) in Java is an automa c memory management process that helps to reclaim
memory by dele ng objects that are no longer in use. The Java Virtual Machine (JVM) is responsible
for managing memory, and it iden fies objects that are unreachable or no longer needed, freeing up
that memory for future use.

Key Concepts of Garbage Collec on:

1. Automa c Memory Management:

o Java developers do not need to explicitly free memory as they would in languages
like C or C++. The JVM handles this automa cally.

2. Reachability:

o An object is considered reachable if it can be accessed through references from the


root objects (e.g., local variables, sta c variables, ac ve threads). If there are no
references to an object, it becomes unreachable and eligible for garbage collec on.

3. Garbage Collector:

o The component of the JVM responsible for iden fying and disposing of unreachable
objects. Java provides several garbage collec on algorithms, including:

 Mark and Sweep: The GC marks all reachable objects, then sweeps through
memory to collect the unmarked objects.

 Genera onal Garbage Collec on: Divides memory into genera ons (young,
old) and focuses on collec ng the young genera on more frequently since
most objects have a short lifespan.

4. Finalize Method:

o The finalize() method is called by the garbage collector before an object is destroyed.
This method can be overridden to perform cleanup opera ons. However, its use is
discouraged in favor of more explicit resource management techniques (e.g., try-
with-resources).

5. Garbage Collec on Tuning:

o Developers can tune garbage collec on performance by adjus ng JVM parameters


(e.g., heap size, GC algorithm) to op mize memory usage based on applica on
needs.

13. Define a Class and Object. Explain the Syntax to Define a Class and an Object with Example.

Class

A class in Java is a blueprint for crea ng objects. It defines the proper es (a ributes) and behaviors
(methods) that the objects created from the class will have. A class encapsulates data and methods
that operate on that data.

Object

An object is an instance of a class. When a class is defined, no memory is allocated un l an object of


that class is created. Objects represent real-world en es and can have a ributes and methods
associated with them.
Syntax to Define a Class

To define a class in Java, use the following syntax:

java

Copy code

public class ClassName {

// A ributes (fields)

dataType a ributeName;

// Constructor

public ClassName(parameters) {

// Ini aliza on code

// Methods

returnType methodName(parameters) {

// Method body

Example of a Class:

java

Copy code

public class Car {

// A ributes

String model;

String color;

int year;

// Constructor

public Car(String model, String color, int year) {

this.model = model;

this.color = color;
this.year = year;

// Method

public void displayDetails() {

System.out.println("Model: " + model + ", Color: " + color + ", Year: " + year);

Syntax to Create an Object

To create an object of a class, use the following syntax:

java

Copy code

ClassName objectName = new ClassName(parameters);

Example of Crea ng an Object:

java

Copy code

public class Main {

public sta c void main(String[] args) {

// Crea ng an object of the Car class

Car myCar = new Car("Toyota", "Red", 2020);

// Calling a method on the object

myCar.displayDetails();

14. Create a Class Called Staff, Which Models an Employee with an ID, Name, and Salary. Develop
the Staff Class and Suitable Main Method for Demonstra on.

public class Staff {

// A ributes

private int id;


private String name;

private double salary;

// Constructor

public Staff(int id, String name, double salary) {

this.id = id;

this.name = name;

this.salary = salary;

// Method to raise salary

public void raiseSalary(double percent) {

salary += salary * (percent / 100);

// Method to display staff details

public void displayDetails() {

System.out.println("ID: " + id + ", Name: " + name + ", Salary: $" + salary);

public class Main {

public sta c void main(String[] args) {

// Crea ng an object of Staff

Staff staffMember = new Staff(101, "Alice", 50000);

// Display ini al details

System.out.println("Before salary raise:");

staffMember.displayDetails();

// Raising salary by 10%

staffMember.raiseSalary(10);

// Display updated details

System.out.println("A er salary raise:");


staffMember.displayDetails();

15. Define a Constructor. Give the Basic Syntax to Define a Constructor

Defini on of a Constructor

A constructor in Java is a special method that is called when an object of a class is created. It
ini alizes the newly created object and sets ini al values for its a ributes. Constructors have the
same name as the class and do not have a return type.

Basic Syntax of a Constructor

public ClassName(parameters) {

// Ini aliza on code

Key Characteris cs of Constructors:

1. Same Name as Class: A constructor must have the same name as the class it belongs to.

2. No Return Type: Constructors do not have a return type, not even void.

3. Can Have Parameters: Constructors can take parameters to ini alize a ributes with specific
values.

4. Overloading: You can have mul ple constructors in the same class with different parameter
lists (constructor overloading).

Example of a Constructor

java

Copy code

public class Book {

// A ributes

private String tle;

private String author;

private double price;

// Constructor

public Book(String tle, String author, double price) {

this. tle = tle;

this.author = author;
this.price = price;

// Method to display book details

public void displayDetails() {

System.out.println("Title: " + tle + ", Author: " + author + ", Price: $" + price);

public class Main {

public sta c void main(String[] args) {

// Crea ng an object of the Book class

Book myBook = new Book("Java Programming", "John Doe", 29.99);

// Displaying book details

myBook.displayDetails();

16. Explain the Different Types of Constructors with Example

In Java, there are two main types of constructors:

1. Default Constructor

2. Parameterized Constructor

1. Default Constructor

A default constructor is a constructor that does not take any parameters. It ini alizes the object with
default values.

Example of a Default Constructor:

public class Car {

// A ributes

private String model;

private String color;

// Default Constructor

public Car() {

model = "Unknown";
color = "Unknown";

// Method to display car details

public void displayDetails() {

System.out.println("Model: " + model + ", Color: " + color);

public class Main {

public sta c void main(String[] args) {

// Crea ng an object using the default constructor

Car myCar = new Car();

// Displaying car details

myCar.displayDetails(); // Output: Model: Unknown, Color: Unknown

2. Parameterized Constructor

A parameterized constructor is a constructor that takes parameters to ini alize the object with
specific values.

Example of a Parameterized Constructor:

public class Car {

// A ributes

private String model;

private String color;

// Parameterized Constructor

public Car(String model, String color) {

this.model = model;

this.color = color;

// Method to display car details

public void displayDetails() {


System.out.println("Model: " + model + ", Color: " + color);

public class Main {

public sta c void main(String[] args) {

// Crea ng an object using the parameterized constructor

Car myCar = new Car("Toyota", "Red");

// Displaying car details

myCar.displayDetails(); // Output: Model: Toyota, Color: Red

17. Write a Program to Create a Class Called Student Which Has the Following Data: Roll Number,
Name, Grade. Let It Have Constructors. It Should Also Have a Display Method to Display the
Student Details.

Java Code for Student Class:

public class Student {

// A ributes

private int rollNo;

private String name;

private char grade;

// Constructor

public Student(int rollNo, String name, char grade) {

this.rollNo = rollNo;

this.name = name;

this.grade = grade;

// Method to display student details

public void displayDetails() {

System.out.println("Roll Number: " + rollNo + ", Name: " + name + ", Grade: " + grade);

}
public class Main {

public sta c void main(String[] args) {

// Crea ng an object of the Student class

Student student1 = new Student(101, "Alice", 'A');

Student student2 = new Student(102, "Bob", 'B');

// Displaying student details

student1.displayDetails();

student2.displayDetails();

18. Develop a Stack Class to Hold a Maximum of 10 Integers with Suitable Methods. Develop a Java
Main Method to Illustrate Stack Opera ons.

Java Code for Stack Class:

class Stack {

private int[] stackArray;

private int top;

private final int MAX_SIZE = 10;

// Constructor

public Stack() {

stackArray = new int[MAX_SIZE];

top = -1; // Indicates an empty stack

// Method to push an element onto the stack

public void push(int value) {

if (top < MAX_SIZE - 1) {

stackArray[++top] = value;

System.out.println(value + " pushed onto the stack.");

} else {

System.out.println("Stack is full. Cannot push " + value);

}
}

// Method to pop an element from the stack

public int pop() {

if (top >= 0) {

return stackArray[top--];

} else {

System.out.println("Stack is empty. Cannot pop.");

return -1; // Indica ng empty stack

// Method to peek at the top element of the stack

public int peek() {

if (top >= 0) {

return stackArray[top];

} else {

System.out.println("Stack is empty. Cannot peek.");

return -1; // Indica ng empty stack

// Method to check if the stack is empty

public boolean isEmpty() {

return top == -1;

// Method to display the stack

public void display() {

if (isEmpty()) {

System.out.println("Stack is empty.");

} else {

System.out.print("Stack elements: ");

for (int i = 0; i <= top; i++) {

System.out.print(stackArray[i] + " ");


}

System.out.println();

public class Main {

public sta c void main(String[] args) {

Stack stack = new Stack();

// Stack opera ons

stack.push(10);

stack.push(20);

stack.push(30);

stack.display();

System.out.println("Top element is: " + stack.peek());

System.out.println("Popped element: " + stack.pop());

stack.display();

stack.push(40);

stack.push(50);

stack.push(60);

stack.push(70);

stack.push(80);

stack.push(90);

stack.push(100);

stack.push(110); // This should show stack full message

stack.display();

}
19. Explain Type Conversion and Cas ng in Java

Type conversion and cas ng in Java are processes used to convert a variable from one data type to
another. This can occur either implicitly or explicitly.

1. Implicit Type Conversion (Widening Conversion)

Implicit type conversion, also known as widening conversion, occurs when a smaller data type is
automa cally converted to a larger data type without any data loss. This typically happens when
assigning a value of one type to a variable of another, larger type.

Example of Implicit Conversion:

java

Copy code

public class ImplicitConversion {

public sta c void main(String[] args) {

int intValue = 100; // int is smaller than double

double doubleValue = intValue; // Implicit conversion from int to double

System.out.println("Integer value: " + intValue);

System.out.println("Double value: " + doubleValue); // Output: 100.0

2. Explicit Type Conversion (Narrowing Conversion)

Explicit type conversion, also known as narrowing conversion, is required when conver ng a larger
data type to a smaller data type. This may result in data loss, so it must be done manually using
cas ng.

Example of Explicit Conversion:

java

Copy code

public class ExplicitConversion {

public sta c void main(String[] args) {

double doubleValue = 100.99; // double is larger than int

int intValue = (int) doubleValue; // Explicit conversion from double to int

System.out.println("Double value: " + doubleValue);

System.out.println("Integer value a er cas ng: " + intValue); // Output: 100


}

20. Explain the Following Concepts of Java: a) Garbage Collec on b) finalize() Method

a) Repea on of Q12.

b) finalize() Method

The finalize() method is a protected method of the Object class that is called by the garbage collector
when it determines that there are no more references to an object. This method can be overridden
to perform cleanup opera ons before the object is destroyed.

Key Features of finalize():

1. Cleanup Opera ons:

o It allows the programmer to release resources (like closing file handles or database
connec ons) before an object is removed from memory.

2. Not Guaranteed:

o There is no guarantee when, or even if, finalize() will be called. This makes it
unreliable for cri cal cleanup tasks.

3. Deprecated:

o Star ng with Java 9, the use of finalize() has been deprecated in favor of more
explicit resource management strategies, like try-with-resources.

Example of finalize() Method:

public class FinalizeExample {

@Override

protected void finalize() throws Throwable {

System.out.println("Finalize method called for object: " + this);

super.finalize(); // Call the superclass's finalize method

public sta c void main(String[] args) {

FinalizeExample obj = new FinalizeExample();

obj = null; // Make the object eligible for garbage collec on

// Sugges ng JVM to run garbage collec on

System.gc(); // This does not guarantee the finalize method will be called

}
21. Explain the Following Syntax with Example Program: a) Constructor b) this Keyword

a) Constructor

A constructor is a special method in a class that is called when an object of that class is created. It
ini alizes the object's a ributes and sets up its ini al state. Constructors have the same name as the
class and do not have a return type.

Example of a Constructor:

java

Copy code

public class Rectangle {

// A ributes

private double length;

private double width;

// Constructor

public Rectangle(double length, double width) {

this.length = length; // Using 'this' to refer to the instance variable

this.width = width;

// Method to calculate area

public double area() {

return length * width;

// Method to display details

public void displayDetails() {

System.out.println("Length: " + length + ", Width: " + width + ", Area: " + area());

public class Main {

public sta c void main(String[] args) {

// Crea ng an object of Rectangle

Rectangle myRectangle = new Rectangle(5.0, 3.0);

myRectangle.displayDetails(); // Output: Length: 5.0, Width: 3.0, Area: 15.0


}

Explana on:

 The Rectangle class has a ributes for length and width.

 The constructor ini alizes these a ributes when a Rectangle object is created.

 The displayDetails() method shows the rectangle's details, including its area.

b) this Keyword

The this keyword is a reference variable in Java that refers to the current object. It is commonly used
to resolve naming conflicts between instance variables and parameters, especially in constructors
and se er methods.

Example of Using this:

public class Person {

// A ributes

private String name;

private int age;

// Constructor

public Person(String name, int age) {

this.name = name; // 'this.name' refers to the instance variable

this.age = age; // 'this.age' refers to the instance variable

// Method to display person details

public void displayDetails() {

System.out.println("Name: " + name + ", Age: " + age);

public class Main {

public sta c void main(String[] args) {

// Crea ng an object of Person

Person person1 = new Person("Alice", 30);

person1.displayDetails(); // Output: Name: Alice, Age: 30

}
22. Explain the Jump Statements (break, con nue, and return) with Example

In Java, jump statements are used to control the flow of execu on in loops and methods. The three
primary jump statements are break, con nue, and return.

a) break Statement

The break statement is used to terminate the nearest enclosing loop or switch statement. When a
break is encountered, control jumps to the statement immediately following the loop or switch.

Example of break:

java

Copy code

public class BreakExample {

public sta c void main(String[] args) {

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

if (i == 5) {

break; // Exit the loop when i is 5

System.out.println(i); // Output: 1 2 3 4

Explana on:

 In the example, the loop runs from 1 to 10.

 When i equals 5, the break statement is executed, and the loop terminates.

b) con nue Statement

The con nue statement skips the current itera on of a loop and proceeds to the next itera on. It is
commonly used to skip specific condi ons.

Example of con nue:

java

Copy code

public class Con nueExample {

public sta c void main(String[] args) {

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


if (i % 2 == 0) {

con nue; // Skip even numbers

System.out.println(i); // Output: 1 3 5 7 9

Explana on:

 In this example, the loop runs from 1 to 10.

 If i is even, the con nue statement skips the current itera on, resul ng in only odd numbers
being printed.

c) return Statement

The return statement is used to exit from a method and op onally return a value. It can be used to
stop method execu on and return control to the calling method.

Example of return:

public class ReturnExample {

// Method to add two numbers

public sta c int add(int a, int b) {

return a + b; // Return the sum

public sta c void main(String[] args) {

int sum = add(5, 10); // Call the add method

System.out.println("Sum: " + sum); // Output: Sum: 15

Explana on:

 In the add method, the return statement returns the sum of a and b.

 In the main method, the result of the add method is stored in sum and printed.

You might also like