KEMBAR78
Java 14 Question Answer | PDF | Method (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
29 views34 pages

Java 14 Question Answer

The document compares procedural programming with object-oriented programming (OOP), highlighting differences in approach, data handling, modularity, reusability, and security, with examples in C and Java. It explains the structure of a Java program, the concept of classpath, and key OOP principles such as encapsulation, inheritance, and polymorphism, along with practical Java code examples. Additionally, it covers access modifiers, matrix multiplication, and control flow statements (if-else and switch) in Java, providing examples for calculating grades based on average marks.

Uploaded by

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

Java 14 Question Answer

The document compares procedural programming with object-oriented programming (OOP), highlighting differences in approach, data handling, modularity, reusability, and security, with examples in C and Java. It explains the structure of a Java program, the concept of classpath, and key OOP principles such as encapsulation, inheritance, and polymorphism, along with practical Java code examples. Additionally, it covers access modifiers, matrix multiplication, and control flow statements (if-else and switch) in Java, providing examples for calculating grades based on average marks.

Uploaded by

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

1.

Di erentiae betwen procedural and OOP programming


language with an example. What are the advantages of OOP

Difference Between Procedural and Object-Oriented Programming

Aspect Procedural Programming Object-Oriented Programming (OOP)


Top-down: focuses on functions and
Approach Bottom-up: focuses on objects and classes
procedures
Data Handling Data and functions are separate Data and functions are encapsulated within
objects
Less modular; code is organized Highly modular; code is organized into
Modularity
into functions classes and objects
Reusability Limited; code reuse through High; code reuse through inheritance and
functions polymorphism
Security Less secure; data is exposed More secure; data is hidden using
globally encapsulation
Example
C, Pascal Java, C++, Python
Languages

Example

Procedural Programming (C-like pseudocode):

c
CopyEdit
int width = 5;
int height = 10;

int calculateArea(int w, int h) {


return w * h;
}

int area = calculateArea(width, height);


Object-Oriented Programming (Java):

java
CopyEdit
class Rectangle {
int width;
int height;

Rectangle(int w, int h) {
width = w;
height = h;
}

int calculateArea() {
ff
return width * height;
}
}

Rectangle rect = new Rectangle(5, 10);


int area = rect.calculateArea();
In the OOP example, the Rectangle class encapsulates both data (width and height) and
behavior (calculateArea), promoting modularity and reusability.

Advantages of Object-Oriented Programming

1. Modularity: Classes and objects allow for modular code, making it easier to debug and
maintain.

2. Reusability: Through inheritance, existing code can be reused, reducing redundancy. Robert
Half

3. Encapsulation: Data hiding protects object integrity by preventing unintended interference.

4. Polymorphism: Objects can take on multiple forms, allowing for exible and
interchangeable code components.

5. Abstraction: Complex systems can be modeled using simpli ed interfaces, making them
easier to understand and manage.

These principles contribute to more ef cient, maintainable, and scalable software development.

2.Explain the structure of a Java program with an example.


What is classpath , explain with example

Structure of a Java Program


A typical Java program comprises several components that de ne its structure. Here's a breakdown:

1. Documentation Section: Contains comments that describe the program.

2. Package Declaration: Speci es the package name if the class belongs to one.

3. Import Statements: Allow the program to access other Java classes.

4. Class Declaration: De nes the class and its members.


Ethans+2www.tpointtech.com+2W3Schools.com+2

5. Main Method: The entry point of the program. Scaler

Example:
fi
fi
fi
fi
fi
fl
java
CopyEdit
// Documentation Section
/**
* This is a simple Java program.
*/

// Package Declaration
package com.example;

// Import Statements
import java.util.Scanner;

// Class Declaration
public class HelloWorld {

// Main Method
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
In this example, the program prints "Hello, World!" to the console. The main method is the
starting point of the program. The package and import statements help organize and utilize
existing Java classes. Ethans

What is Classpath?
The classpath is a parameter that tells the Java Virtual Machine (JVM) and Java compiler where to
nd user-de ned classes and packages. It's essential when your program depends on external classes
or libraries. Princeton CS+2Reddit+2Wikipedia+2

Setting the Classpath:

1. Command Line: You can set the classpath using the -cp or -classpath option.
bash
CopyEdit

java -cp .;lib/mylib.jar com.example.MyClass

2.

This command tells the JVM to look in the current directory (.) and the lib/
mylib.jar le for classes.
fi
fi
fi
3. Environment Variable: Alternatively, set the CLASSPATH environment variable.
Wikipedia

◦ Windows:
cmd
CopyEdit

set CLASSPATH=.;lib\mylib.jar

◦ Unix/Linux:
bash
CopyEdit

export CLASSPATH=.:lib/mylib.jar

4. This method sets the classpath for the session.

Example Scenario:

Suppose you have a Java program that uses classes from a library located in lib/mylib.jar.
To compile and run your program, you'd set the classpath to include this JAR le so the JVM can
locate the necessary classes.

Understanding the structure of a Java program and the role of the classpath is fundamental for
developing and running Java applications effectively.

3. Explain Encapsulation, Inheritance, Polymorphism with


suitable examples Write a Java program to check a number is
palindrome. Read input from console and print the output.

🔐 Encapsulation
De nition:
Encapsulation is the process of wrapping data (variables) and code (methods) together as a single
unit. It restricts direct access to some of an object's components, which is a means of preventing
accidental interference and misuse of the data. TechAf nity
fi
fi
fi
Example:

java
CopyEdit
public class Person {
private String name; // private variable

// Public getter method


public String getName() {
return name;
}

// Public setter method


public void setName(String newName) {
this.name = newName;
}
}
In this example, the name variable is private, so it cannot be accessed directly from outside the
Person class. Instead, public getter and setter methods are provided to access and update the
value of name.

🧬 Inheritance
De nition:
Inheritance is a mechanism wherein a new class (subclass) inherits properties and behaviors ( elds
and methods) from an existing class (superclass). This promotes code reusability.

Example:

java
CopyEdit
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
Here, the Dog class inherits the eat() method from the Animal class and also has its own
method bark().
fi
fi
🔁 Polymorphism
De nition:
Polymorphism allows objects to be treated as instances of their parent class rather than their actual
class. The two types of polymorphism in Java are:

• Compile-time polymorphism (Method Overloading): Same method name with different


parameters.

• Runtime polymorphism (Method Overriding): Subclass provides a speci c


implementation of a method already de ned in its superclass.

Example:

java
CopyEdit
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Cat extends Animal {


@Override
void makeSound() {
System.out.println("Meow");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Bark");
}
}
In this example, both Cat and Dog classes override the makeSound() method of the Animal
class, providing their speci c implementations.

🔄 Java Program to Check if a Number is a Palindrome


A palindrome number is a number that remains the same when its digits are reversed. For example,
121 and 1331 are palindromes.

Here's a Java program that reads a number from the console and checks if it's a palindrome:
fi
fi
fi
fi
java
CopyEdit
import java.util.Scanner;

public class PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int originalNumber = scanner.nextInt();
int reversedNumber = 0;
int number = originalNumber;

// Reverse the number


while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}

// Check if the original number and reversed number


are the same
if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a
palindrome.");
} else {
System.out.println(originalNumber + " is not a
palindrome.");
}

scanner.close();
}
}
Sample Output:

less
CopyEdit
Enter a number: 121
121 is a palindrome.
This program uses a Scanner to read input from the console, reverses the number using a
while loop, and then compares the reversed number with the original to determine if it's a
palindrome.

Feel free to ask if you need further clari cation or assistance with other Java concepts!
fi
4.Describe access modi er? Explain public, private, default
access modi ers Write a program to multiply two 3x3 matrices.

🔐 Access Modi ers in Java


Access modi ers in Java determine the visibility and accessibility of classes, methods, constructors,
and variables.They are fundamental to object-oriented programming as they help enforce
encapsulation, a core principle restricting direct access to some of an object's components.
WikipediaSimplilearn.com

1. public

• De nition: The public modi er allows elements to be accessible from any other class in
the application, regardless of the package. Simplilearn.com

• Usage: Used when the class, method, or variable needs to be accessed from any other class.

2. private

• De nition: The private modi er restricts access to the elements only within the class
they are declared.

• Usage: Used to encapsulate and protect data from external access.

3. default (no modi er)

• De nition: When no access modi er is speci ed, it is known as default access. The element
is accessible only within classes in the same package.

• Usage: Useful for package-level access where classes within the same package can interact
with each other.

Summary Table:

Access Clas Packag Subclas Worl


Modi er s e s d
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌
default ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌

✖ Java Program to Multiply Two 3x3 Matrices


Here's a Java program that multiplies two 3x3 matrices using nested loops: www.tpointtech.com
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
java
CopyEdit
public class MatrixMultiplication {
public static void main(String[] args) {
// Define two 3x3 matrices
int[][] matrixA = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] matrixB = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

// Initialize the result matrix


int[][] result = new int[3][3];

// Perform matrix multiplication


for (int i = 0; i < 3; i++) { // Iterate
over rows of matrixA
for (int j = 0; j < 3; j++) { // Iterate
over columns of matrixB
for (int k = 0; k < 3; k++) { // Iterate
over columns of matrixA / rows of matrixB
result[i][j] += matrixA[i][k] *
matrixB[k][j];
}
}
}

// Display the result


System.out.println("Product of the two matrices:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(result[i][j] + "\t");
}
System.out.println();
}
}
}
Sample Output:

yaml
CopyEdit
Product of the two matrices:
30 24 18
84 69 54
138 114 90
Explanation:

• Each element result[i][j] is calculated by multiplying the elements of the i-th row
of matrixA with the corresponding elements of the j-th column of matrixB and
summing the products.

• The nested loops facilitate this process:

◦ The outer loop iterates over the rows of matrixA.

◦ The middle loop iterates over the columns of matrixB.

◦ The inner loop performs the multiplication and addition to compute each element of
the result matrix.

This program demonstrates the use of nested loops to perform matrix multiplication, a fundamental
operation in various computational applications.

5.Explain the working of if-else and switch. Develop a Java


program to input marks of ve subjects and calculate the
average. Based on the average, show grades using 1> if-else
and 2>switch-case statements.

🔁 Understanding if-else and switch Statements in


Java
if-else Statement

The if-else statement allows you to execute certain blocks of code based on whether a
condition evaluates to true or false. It's suitable for evaluating complex conditions, including
ranges and multiple variables.

Syntax:

java
CopyEdit
if (condition) {
// Executes if condition is true
} else if (anotherCondition) {
fi
// Executes if anotherCondition is true
} else {
// Executes if none of the above conditions are true
}
switch Statement

The switch statement is used to execute one block of code among many based on the value of a
single variable. It's ideal when you have multiple discrete values to compare against.

Syntax:

java
CopyEdit
switch (variable) {
case value1:
// Code block
break;
case value2:
// Code block
break;
// You can have any number of case statements.
default:
// Code block
}
Key Differences:

• Condition Type: if-else can evaluate complex expressions; switch evaluates a


single variable against multiple constants.

• Readability: switch can be more readable when dealing with numerous discrete values.
Studocu

• Flexibility: if-else offers more exibility for complex conditions.

🧮 Java Program: Calculate Average and Assign Grades


This program will:

1. Prompt the user to enter marks for ve subjects.

2. Calculate the average of these marks. Codingzap

3. Assign and display a grade based on the average using both if-else and switch-
case statements.

Grading Criteria:
fi
fl
• Average ≥ 80: Grade A Code with Mosh Forum+13JavaMadeSoEasy.com (JMSE)
+13BeginnersBook -+13

• 60 ≤ Average < 80: Grade B

• 40 ≤ Average < 60: Grade C

• Average < 40: Grade D JavaMadeSoEasy.com (JMSE)

✅ Using if-else Statement

java
CopyEdit
import java.util.Scanner;

public class GradeCalculatorIfElse {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int totalMarks = 0;
int numberOfSubjects = 5;

System.out.println("Enter marks for five subjects:");

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


System.out.print("Subject " + i + ": ");
int mark = scanner.nextInt();
totalMarks += mark;
}

double average = (double) totalMarks /


numberOfSubjects;
System.out.println("Average Marks: " + average);

// Assign grade based on average


if (average >= 80) {
System.out.println("Grade: A");
} else if (average >= 60) {
System.out.println("Grade: B");
} else if (average >= 40) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: D");
}

scanner.close();
}
}
🔁 Using switch-case Statement

Since switch statements work with discrete values, we'll convert the average to an integer and
divide by 10 to simplify the grading logic.

java
CopyEdit
import java.util.Scanner;

public class GradeCalculatorSwitch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int totalMarks = 0;
int numberOfSubjects = 5;

System.out.println("Enter marks for five subjects:");

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


System.out.print("Subject " + i + ": ");
int mark = scanner.nextInt();
totalMarks += mark;
}

double average = (double) totalMarks /


numberOfSubjects;
System.out.println("Average Marks: " + average);

// Convert average to an integer for switch-case


int averageInt = (int) average;

// Determine grade category


int gradeCategory = averageInt / 10;

// Assign grade based on grade category


switch (gradeCategory) {
case 10:
case 9:
case 8:
System.out.println("Grade: A");
break;
case 7:
case 6:
System.out.println("Grade: B");
break;
case 5:
case 4:
System.out.println("Grade: C");
break;
default:
System.out.println("Grade: D");
break;
}

scanner.close();
}
}
Explanation:

• In the switch-case version, we divide the average by 10 to categorize it into ranges:

◦ 80–100 → 8–10

◦ 60–79 → 6–7

◦ 40–59 → 4–5

◦ Below 40 → 0–3

• This approach simpli es the switch logic by handling ranges through grouped cases.

Feel free to use either version based on your preference or speci c requirements. Let me know if
you need further assistance or explanations!

6. Explain the concept of type conversion. With a Java program


illustrate both implicit (widening) and explicit (narrowing) type
conversions. The program should accept a oat value from the
user, explicitly convert it into an integer (narrowing), and then
promote it to a double (widening). Print appropriate output

In Java, type conversion refers to changing a variable from one data type to another. There are two
primary types:

1. Widening (Implicit) Conversion: Automatically converts a smaller data type to a larger


one, such as int to double.

2. Narrowing (Explicit) Conversion: Manually converts a larger data type to a smaller one,
like float to int, using casting.

🔄 Example: Narrowing and Widening in Java


fi
fi
fl
The following Java program demonstrates both narrowing and widening conversions:

java
CopyEdit
import java.util.Scanner;

public class TypeConversionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input: float value from user


System.out.print("Enter a float value: ");
float floatValue = scanner.nextFloat();

// Narrowing: float to int (explicit)


int intValue = (int) floatValue;

// Widening: int to double (implicit)


double doubleValue = intValue;

// Output
System.out.println("\n--- Type Conversion Results
---");
System.out.println("Original float value: " +
floatValue);
System.out.println("After narrowing to int: " +
intValue);
System.out.println("After widening to double: " +
doubleValue);

scanner.close();
}
}
Sample Output:

pgsql
CopyEdit
Enter a float value: 45.67

--- Type Conversion Results ---


Original float value: 45.67
After narrowing to int: 45
After widening to double: 45.0
Explanation:

• Narrowing Conversion: The oat value 45.67 is explicitly cast to an integer, resulting in
45. This truncates the decimal part.
fl
• Widening Conversion: The integer 45 is implicitly converted to a double, yielding 45.0.
This is done automatically by Java without explicit casting.

This example illustrates how Java handles type conversions between different numeric data types.

7. Write a Java program using nested loops to print the


following pattern : a ab abc abcd abcde Write a java program
to check whether the given year is a leap year or not. Print the
result

1. Java Program to Print the Pattern:


This program uses nested loops to print the following pattern:

css
CopyEdit
a
ab
abc
abcd
abcde
java
CopyEdit
public class AlphabetPattern {
public static void main(String[] args) {
int rows = 5; // Number of rows in the pattern

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


for (char ch = 'a'; ch < 'a' + i; ch++) {
System.out.print(ch);
}
System.out.println();
}
}
}

Explanation:

• The outer loop runs from 1 to 5, representing each row.

• The inner loop prints characters starting from 'a' up to the current row's character.

• After each inner loop, a newline is printed to move to the next row.
2. Java Program to Check Leap Year:
This program checks whether a given year is a leap year.

java
CopyEdit
import java.util.Scanner;

public class LeapYearChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();

boolean isLeap = false;

// Leap year is divisible by 4 but not by 100, or


divisible by 400
if (year % 4 == 0) {
if (year % 100 != 0 || year % 400 == 0) {
isLeap = true;
}
}

if (isLeap) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap
year.");
}

scanner.close();
}
}

Explanation:

• The program prompts the user to enter a year.

• It checks if the year is divisible by 4.

◦ If divisible by 4, it further checks:

▪ If the year is not divisible by 100, it's a leap year.


▪ If the year is divisible by 100, it must also be divisible by 400 to be a leap
year.

• Based on these conditions, the program prints whether the year is a leap year or not.

These programs demonstrate the use of nested loops for pattern printing and conditional statements
for logical checks in Java.

8. Explain how objects are created and how object reference


variables are used in Java.
Write a Java program to de ne a class Student with instance
variables for name, roll number, and marks in three subjects.
Include separate methods to: Accept student details, Calculate
the average marks, and Display the student's result. Create
objects for three students, call the respective methods for
each object, and display their results.
In Java, objects are instances of classes that encapsulate data and behavior. To work with objects,
we use object reference variables, which store the memory address of the object rather than the
object itself. This allows multiple references to point to the same object, facilitating object
manipulation and data sharing.

🔹 Creating Objects and Using Reference Variables

To create an object and use a reference variable:

java
CopyEdit
ClassName objRef = new ClassName();
• ClassName: The name of the class. FSU Computer Science

• objRef: The reference variable that will point to the new object.

• new: The operator that allocates memory for the new object. Java Programming
MOOC+6FSU Computer Science+6Oracle Documentation+6

• ClassName(): The constructor call that initializes the object.

This process involves two steps: declaring the reference variable and creating the object with the
new operator, then assigning the object to the reference variable. FSU Computer Science+1Oracle
Documentation+1

🧑🎓 Java Program: Student Class with Methods


fi
Below is a Java program that de nes a Student class with instance variables for name, roll
number, and marks in three subjects. It includes methods to accept student details, calculate the
average marks, and display the student's result. The program creates objects for three students and
displays their results.

java
CopyEdit
import java.util.Scanner;

class Student {
// Instance variables
String name;
int rollNumber;
int[] marks = new int[3];
double average;

// Method to accept student details


void acceptDetails() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
name = scanner.nextLine();
System.out.print("Enter roll number: ");
rollNumber = scanner.nextInt();
System.out.println("Enter marks for 3 subjects:");
for (int i = 0; i < 3; i++) {
System.out.print("Subject " + (i + 1) + ": ");
marks[i] = scanner.nextInt();
}
}

// Method to calculate average marks


void calculateAverage() {
int sum = 0;
for (int mark : marks) {
sum += mark;
}
average = sum / 3.0;
}

// Method to display student result


void displayResult() {
System.out.println("\nStudent Details:");
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: ");
for (int i = 0; i < 3; i++) {
fi
System.out.println("Subject " + (i + 1) + ": " +
marks[i]);
}
System.out.printf("Average Marks: %.2f\n", average);
}
}

public class StudentTest {


public static void main(String[] args) {
// Create objects for three students
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();

// Accept details, calculate average, and display


results for each student
System.out.println("Enter details for Student 1:");
student1.acceptDetails();
student1.calculateAverage();
student1.displayResult();

System.out.println("\nEnter details for Student 2:");


student2.acceptDetails();
student2.calculateAverage();
student2.displayResult();

System.out.println("\nEnter details for Student 3:");


student3.acceptDetails();
student3.calculateAverage();
student3.displayResult();
}
}
Explanation:

• Student class: Contains instance variables name, rollNumber, marks, and


average.

• acceptDetails(): Prompts the user to enter the student's name, roll number, and
marks for three subjects.

• calculateAverage(): Calculates the average of the three subject marks.

• displayResult(): Displays the student's details and average marks.

• StudentTest class: Contains the main method, creates three Student objects, and
invokes the methods to accept details, calculate averages, and display results.
This program demonstrates how to create and use objects in Java, utilizing object reference
variables to manage and access the data encapsulated within each Student object.

9. Describe how one-dimensional arrays are declared,


initialized, and accessed using indices. Mention the
advantages of using arrays when handling a xed collection of
similar data types. Write a Java program to declare and
initialize a one-dimensional array of 10 integers. Using
appropriate control and loop structures:
(i) Display only the even numbers from the array, and
(ii) Calculate and print the sum of all odd numbers.
In Java, a one-dimensional array is a data structure that stores a xed-size sequence of elements of
the same data type.

🔹 Declaring, Initializing, and Accessing One-Dimensional Arrays

Declaration:

java
CopyEdit
int[] numbers;
This declares an array named numbers that can hold integers.

Initialization:

java
CopyEdit
numbers = new int[10]; // Initializes the array with 10
elements, defaulting to 0
Alternatively, you can declare and initialize in one line:

java
CopyEdit
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Accessing Elements: Array elements are accessed using indices, starting from 0. For example:

java
CopyEdit
int firstElement = numbers[0]; // Accesses the first element
numbers[1] = 20; // Sets the second element to
20

✅ Advantages of Using Arrays


fi
fi
• Ef cient Data Management: Arrays allow storing multiple elements of the same type
under a single variable name, making code more organized.

• Indexed Access: Elements can be accessed directly via indices, enabling quick retrieval and
modi cation.

• Memory Ef ciency: Arrays provide a way to allocate memory for multiple elements at
once, which can be more ef cient than individual variable declarations.

• Ease of Iteration: Arrays can be easily traversed using loops, facilitating operations on
multiple elements.

🧮 Java Program: Working with a One-Dimensional Array

The following Java program demonstrates:

1. Declaration and initialization of a one-dimensional array with 10 integers.

2. Displaying only the even numbers from the array.

3. Calculating and printing the sum of all odd numbers.

java
CopyEdit
public class ArrayOperations {
public static void main(String[] args) {
// Declare and initialize the array
int[] numbers = {12, 7, 9, 20, 33, 18, 5, 42, 11, 6};

// Display even numbers


System.out.println("Even numbers in the array:");
for (int num : numbers) {
if (num % 2 == 0) {
System.out.print(num + " ");
}
}

// Calculate sum of odd numbers


int sumOfOdd = 0;
for (int num : numbers) {
if (num % 2 != 0) {
sumOfOdd += num;
}
}
System.out.println("\nSum of odd numbers: " +
sumOfOdd);
}
}
fi
fi
fi
fi
Explanation:

• Array Initialization: An array numbers is initialized with 10 integer values.

• Displaying Even Numbers: A for-each loop iterates through each element, and the if
condition checks if the number is even (num % 2 == 0). If true, the number is printed.

• Calculating Sum of Odd Numbers: Another for-each loop adds up all numbers that
are odd (num % 2 != 0) to the sumOfOdd variable.

Sample Output:

yaml
CopyEdit
Even numbers in the array:
12 20 18 42 6
Sum of odd numbers: 65
This program effectively demonstrates the use of arrays in Java for storing and manipulating a xed
collection of similar data types.

10. Explain the role of the constructor and how it di ers from a
regular method. Write a Java program that illustrates the use
of constructors by de ning a class Rectangle with length and
breadth as data members. Include a parameterized
constructor to initialize values and a method to calculate area.
Create two objects using the constructor and display their
respective areas.

In Java, a constructor is a special method used to initialize objects when they are created. Unlike
regular methods, constructors:

• Have the same name as the class.

• Do not have a return type, not even void.

• Are invoked automatically when an object is instantiated using the new keyword.

• Can be parameterized to allow initialization with speci c values.


Reddit+3W3Schools.com+3Stack Over ow+3

In contrast, regular methods are used to de ne behaviors or operations that can be performed on
objects. They can be called explicitly on an object and can return values. Stack Over ow

🧱 Java Program: Rectangle Class with Constructor and Area Calculation


fi
fl
fi
fi
ff
fl
fi
The following Java program de nes a Rectangle class with instance variables for length and
breadth. It includes a parameterized constructor to initialize these values and a method to calculate
the area. Two objects are created using the constructor, and their areas are displayed.

java
CopyEdit
public class Rectangle {
// Instance variables
double length;
double breadth;

// Parameterized constructor to initialize length and


breadth
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}

// Method to calculate the area of the rectangle


public double calculateArea() {
return length * breadth;
}

public static void main(String[] args) {


// Creating two Rectangle objects with different
dimensions
Rectangle rect1 = new Rectangle(5.0, 3.0);
Rectangle rect2 = new Rectangle(7.5, 4.5);

// Displaying the areas of the rectangles


System.out.println("Area of Rectangle 1: " +
rect1.calculateArea());
System.out.println("Area of Rectangle 2: " +
rect2.calculateArea());
}
}
Explanation:

• Instance Variables: length and breadth represent the dimensions of the rectangle.

• Parameterized Constructor: Rectangle(double length, double


breadth) initializes the instance variables with the provided values.

• Method calculateArea: Calculates and returns the area of the rectangle using the
formula:
Area
=
fi
length
×
breadth

Area=length×breadth

• main Method: Creates two Rectangle objects with different dimensions and prints
their areas.

Sample Output:

mathematica
CopyEdit
Area of Rectangle 1: 15.0
Area of Rectangle 2: 33.75
This program demonstrates how constructors are used to initialize objects with speci c values and
how methods can perform operations on those objects.

11.Explain method overloading and explain how Java resolves


overloaded methods during compilation. Write a Java program
that overloads a method called display(). The rst version
should accept an integer and print it, the second version
should accept a string and print it, and the third should accept
both and print them in a formatted way.

In Java, method overloading is a feature that allows a class to have multiple methods with the
same name, provided they differ in the number or type of their parameters. This enhances code
readability and allows methods to perform similar tasks with different types or numbers of inputs.
Medium+2BeginnersBook -+2Great Learning+2Medium+1Great Learning+1
Key Points:

• Same Method Name: Overloaded methods share the same name. Stack
Over ow+1Programiz+1

• Different Parameters: They differ in the number, type, or both of their parameters.
Medium+5Great Learning+5java-iitd.vlabs.ac.in+5

• Return Type: Overloading is determined by method signatures, which include the method
name and parameter list; the return type is not considered.

Example of Method Overloading:

java
CopyEdit
fl
fi
fi
public class Display {
// Method to display an integer
public void show(int num) {
System.out.println("Integer: " + num);
}

// Method to display a string


public void show(String text) {
System.out.println("String: " + text);
}

// Method to display both an integer and a string


public void show(int num, String text) {
System.out.println("Integer: " + num + ", String: " +
text);
}

public static void main(String[] args) {


Display display = new Display();

// Calling the overloaded methods


display.show(10); // Calls show(int
num)
display.show("Hello, World!"); // Calls show(String
text)
display.show(10, "Hello"); // Calls show(int
num, String text)
}
}

Explanation:

• Method De nitions:

◦ show(int num): Accepts an integer and prints it.

◦ show(String text): Accepts a string and prints it. Reddit

◦ show(int num, String text): Accepts both an integer and a string,


printing them together.

• Method Invocation:

◦ The appropriate show method is called based on the arguments passed,


demonstrating method overloading. Programiz

Output:
fi
vbnet
CopyEdit
Integer: 10
String: Hello, World!
Integer: 10, String: Hello

How Java Resolves Overloaded Methods During Compilation:

Java determines which overloaded method to invoke at compile time by analyzing the method's
signature and the arguments provided in the method call. The compiler selects the method that best
matches the number, type, and order of the arguments. If multiple methods could match, Java
applies the following rules to resolve ambiguity:

1. Exact Match: Prefers methods where the arguments match exactly.

2. Widening Primitive Conversion: If no exact match, the compiler considers methods where
arguments can be converted to a wider type (e.g., int to long).

3. Varargs: If methods with variable arguments (varargs) are available, they are considered
last.

This process ensures that the most speci c and appropriate method is called based on the provided
arguments, leading to ef cient and predictable method resolution.

12. Explain how objects can be passed to methods and


returned from methods in Java. Write a Java program to
illustrate the concept of passing objects as parameters. De ne
a class Complex with real and imaginary parts. Include a
method to add two complex numbers and return the result as
an object.
In Java, objects are instances of classes that encapsulate data and behavior. Understanding how
objects are passed to and returned from methods is crucial for effective programming.

Passing Objects to Methods

• Pass-by-Value of References: Java passes the value of the reference to methods, not the
actual object. This means: www.tpointtech.com+1Medium+1

◦ Modifying Object State: ** Changes to the object's elds within the method affect
the original object since both the caller and the method operate on the same object in
memory. Medium

◦ Reassigning References: ** Assigning a new object to the parameter inside the


method does not affect the original reference; the caller's reference remains
unchanged. Medium
fi
fi
fi
fi
Reference: Medium

Returning Objects from Methods

• Returning Object References: Methods can return object references, allowing the caller to
receive and utilize the object created or modi ed within the method.

• Example: A method that adds two complex numbers and returns the result as a new
Complex object.

Java Program: Complex Number Addition

The following program de nes a Complex class with real and imaginary parts. It includes a
method to add two complex numbers and return the result as a new Complex object.

java
CopyEdit
public class Complex {
// Instance variables for real and imaginary parts
private double real;
private double imaginary;

// Constructor to initialize complex number


public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}

// Method to add two complex numbers


public Complex add(Complex other) {
double resultReal = this.real + other.real;
double resultImaginary = this.imaginary +
other.imaginary;
return new Complex(resultReal, resultImaginary);
}

// Method to display the complex number


public void display() {
System.out.println(real + " + " + imaginary + "i");
}

public static void main(String[] args) {


// Creating two Complex objects
Complex num1 = new Complex(3.0, 2.0);
Complex num2 = new Complex(1.5, 4.5);
fi
fi
// Adding num1 and num2
Complex sum = num1.add(num2);

// Displaying the result


System.out.print("Sum of ");
num1.display();
System.out.print("and ");
num2.display();
System.out.print("is: ");
sum.display();
}
}
Explanation:

• Instance Variables: real and imaginary store the real and imaginary parts of the
complex number.

• Constructor: Initializes a Complex object with speci ed real and imaginary values.

• add Method: Takes another Complex object as a parameter, adds corresponding real and
imaginary parts, and returns a new Complex object representing the sum.

• display Method: Prints the complex number in a readable format.

• main Method: Creates two Complex objects, adds them using the add method, and
displays the result.

Output:

go
CopyEdit
Sum of 3.0 + 2.0i
and 1.5 + 4.5i
is: 4.5 + 6.5i

This program demonstrates how objects can be passed to methods (by passing the reference value)
and returned from methods in Java, facilitating modular and reusable code design.

13. Explain the following: static method, static variable and


static block. Develop a Java program that includes a method
to compute the factorial of a number using recursion. Also,
include a static method to compute the power of a number. "
In Java, the static keyword is used to de ne class-level members that are shared among all
instances of the class.Here's an explanation of the key components: BeginnersBook -
fi
fi
🔹 Static Variable

A static variable is a class-level variable that is shared among all instances of the class. It is
initialized only once when the class is loaded into memory and can be accessed using the class
name or through an instance. Java Guides

Example:

java
CopyEdit
class Counter {
static int count = 0;

Counter() {
count++;
}

static void displayCount() {


System.out.println("Count: " + count);
}
}

In this example, count is a static variable that keeps track of the number of Counter objects
created.

🔹 Static Method

A static method belongs to the class rather than any instance. It can be called without creating an
object of the class and can only access other static members (variables and methods) of the class.
Sololearn: Apprenez à coder+1Java Guides+1

Example:

java
CopyEdit
class MathOperations {
static int square(int x) {
return x * x;
}
}

Here, square is a static method that calculates the square of a number. It can be called as
MathOperations.square(5);without creating an instance of MathOperations.
🔹 Static Block

A static block is used for static initialization of a class. It runs once when the class is loaded into
memory, before any objects are created or static methods are called. This is useful for complex
initialization tasks. Java Guides+1BeginnersBook -+1

Example:

java
CopyEdit
class Config {
static String configValue;

static {
configValue = "Configuration Loaded";
System.out.println("Static block executed");
}
}

In this example, the static block initializes configValue and prints a message when the class is
loaded. BeginnersBook -

🧮 Java Program: Factorial and Power Calculations

The following Java program demonstrates the use of recursion for calculating the factorial of a
number and a static method for calculating the power of a number:

java
CopyEdit
import java.util.Scanner;

public class MathOperations {

// Recursive method to calculate factorial


static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

// Static method to calculate power


static double power(double base, int exponent) {
double result = 1;
for (int i = 0; i < Math.abs(exponent); i++) {
result *= base;
}
return (exponent < 0) ? 1 / result : result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Factorial calculation
System.out.print("Enter a number to calculate its
factorial: ");
int num = scanner.nextInt();
System.out.println("Factorial of " + num + " is " +
factorial(num));

// Power calculation
System.out.print("Enter base and exponent to
calculate power: ");
double base = scanner.nextDouble();
int exponent = scanner.nextInt();
System.out.println(base + " raised to the power of "
+ exponent + " is " + power(base, exponent));
}
}

Explanation:

• factorial(int n) is a static method that calculates the factorial of a number using


recursion.

• power(double base, int exponent) is a static method that calculates the


power of a number using a loop.

• In the main method, the user is prompted to enter a number for factorial and a base and
exponent for power calculations.

Sample Output:

vbnet
CopyEdit
Enter a number to calculate its factorial: 5
Factorial of 5 is 120
Enter base and exponent to calculate power: 2 3
2.0 raised to the power of 3 is 8.0
14. Explain the role and uses of the ”this” keyword in Java.
Write a Java program that illustrates the use of the ”
this” keyword. The program should include a class with
instance variables and a constructor where ”this” is used to
distinguish between instance and local variables. Also, include
a method that returns the current class instance using ”this”.

In Java, the this keyword serves as a reference to the current instance of a class. It is primarily
used within instance methods and constructors to: Stack Over ow+2Learn R, Python & Data
Science Online+2Oracle Documentation+2

1. Distinguish Instance Variables from Local Variables: When instance variables ( elds)
and method or constructor parameters have the same name, this helps differentiate
between them. Oracle Documentation

2. Invoke Current Class Methods: this can be used to call other methods within the same
class.

3. Invoke Current Class Constructors: It allows one constructor to call another constructor
in the same class, facilitating constructor chaining.

4. Pass the Current Object as a Parameter: this can be passed as an argument to other
methods or constructors, referring to the current object. Learn R, Python & Data Science
Online+1W3Schools.com+1

5. Return the Current Object from a Method: Methods can return the current object using
this, enabling method chaining.

Example Program Illustrating the Use of this:

java
CopyEdit
public class Calculator {
private int number;

// Constructor with parameter


public Calculator(int number) {
this.number = number; // 'this.number' refers to the
instance variable, 'number' refers to the parameter
}

// Method to add a value to 'number'


public Calculator add(int value) {
this.number += value;
return this; // Returning the current object
}
fl
fi
// Method to subtract a value from 'number'
public Calculator subtract(int value) {
this.number -= value;
return this; // Returning the current object
}

// Method to display the current value of 'number'


public void display() {
System.out.println("Current number: " + this.number);
}

public static void main(String[] args) {


Calculator calc = new Calculator(10); // Creating a
new Calculator object with initial value 10
calc.add(5).subtract(3).display(); // Chaining
methods
}
}
Explanation:

• Instance Variable and Constructor Parameter Naming Con ict: In the constructor
Calculator(int number), the parameter number shadows the instance variable
number. Using this.number = number; assigns the parameter value to the
instance variable.

• Method Chaining with this: The methods add and subtract modify the number
and return the current Calculator object (this). This allows for method chaining, as
demonstrated in the main method.

Output:

sql
CopyEdit
Current number: 12
This example demonstrates how the this keyword is used to distinguish between instance
variables and parameters, as well as to enable method chaining by returning the current object.
fl

You might also like