Java 14 Question Answer
Java 14 Question Answer
Example
c
CopyEdit
int width = 5;
int height = 10;
java
CopyEdit
class Rectangle {
int width;
int height;
Rectangle(int w, int h) {
width = w;
height = h;
}
int calculateArea() {
ff
return width * height;
}
}
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
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. Package Declaration: Speci es the package name if the class belongs to one.
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
1. Command Line: You can set the classpath using the -cp or -classpath option.
bash
CopyEdit
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
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.
🔐 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
🧬 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:
Example:
java
CopyEdit
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
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;
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.
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.
• 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:
int[][] matrixB = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
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 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.
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:
• Readability: switch can be more readable when dealing with numerous discrete values.
Studocu
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
java
CopyEdit
import java.util.Scanner;
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;
scanner.close();
}
}
Explanation:
◦ 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!
In Java, type conversion refers to changing a variable from one data type to another. There are two
primary types:
2. Narrowing (Explicit) Conversion: Manually converts a larger data type to a smaller one,
like float to int, using casting.
java
CopyEdit
import java.util.Scanner;
// 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
• 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.
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
Explanation:
• 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;
if (isLeap) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap
year.");
}
scanner.close();
}
}
Explanation:
• 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.
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
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
CopyEdit
import java.util.Scanner;
class Student {
// Instance variables
String name;
int rollNumber;
int[] marks = new int[3];
double average;
• acceptDetails(): Prompts the user to enter the student's name, roll number, and
marks for three subjects.
• 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.
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
• 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
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};
• 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:
• Are invoked automatically when an object is instantiated using the new keyword.
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
CopyEdit
public class Rectangle {
// Instance variables
double length;
double breadth;
• Instance Variables: length and breadth represent the dimensions of the rectangle.
• 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.
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.
java
CopyEdit
fl
fi
fi
public class Display {
// Method to display an integer
public void show(int num) {
System.out.println("Integer: " + num);
}
Explanation:
• Method De nitions:
• Method Invocation:
Output:
fi
vbnet
CopyEdit
Integer: 10
String: Hello, World!
Integer: 10, String: Hello
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:
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.
• 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
• 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.
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;
• 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.
• 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.
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++;
}
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 -
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;
// 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:
• 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.
java
CopyEdit
public class Calculator {
private int number;
• 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