Java Pyq - Gemini
Java Pyq - Gemini
Java exception handling uses five keywords: try, catch, finally, throw, and throws. The
try block encloses code that might throw an exception. The catch block handles
specific exception types thrown within the try block. The finally block contains code
that always executes, regardless of whether an exception occurred or was caught.
The throw keyword is used to explicitly throw an exception, while the throws keyword
indicates that a method might throw certain exceptions, delegating handling to the
caller.
Naming conventions in Java are suggested rules for naming identifiers like classes,
interfaces, methods, variables, constants, and packages. Following these conventions
improves code readability and maintainability. Key conventions include:
● Classes/Interfaces: Use UpperCamelCase (e.g., MyClass, Runnable).
● Methods: Use lowerCamelCase (e.g., calculateTotal, getName).
● Variables: Use lowerCamelCase (e.g., userName, totalAmount).
● Constants: Use all uppercase letters with underscores (e.g., MAX_VALUE, PI).
● Packages: Use all lowercase letters (e.g., java.util, com.example.myapp).
Java provides four access specifiers (or access modifiers) that control the visibility
and accessibility of classes, interfaces, variables, methods, and constructors:
1. public: Accessible from any other class anywhere.
2. protected: Accessible within its own package and by subclasses (even if in
different packages).
3. default (no keyword): Accessible only within the same package. This is the
default level if no specifier is used.
4. private: Accessible only within the declared class itself. It offers the highest level
of restriction.
Q6. Explain the abstract class in Java. Describe abstract method with a suitable
example.
Word Count: ~120
An abstract class in Java is a class declared with the abstract keyword. It cannot be
instantiated directly; it must be subclassed. Abstract classes can contain both
abstract methods (methods without a body, declared with the abstract keyword) and
concrete methods (regular methods with implementation). They serve as templates
for subclasses, enforcing a common structure.
Java
// Abstract class
abstract class Shape {
// Abstract method (no implementation)
abstract double calculateArea();
// Concrete method
void display() {
System.out.println("Displaying shape.");
}
}
// Concrete subclass
class Circle extends Shape {
double radius;
Circle(double r) {
radius = r;
}
// Implementation of the abstract method
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
// Cannot create an object of Shape: Shape s = new Shape(); // Error!
Circle c = new Circle(5.0);
c.display();
System.out.println("Area of Circle: " + c.calculateArea());
}
}
Example Program:
Java
public class ExceptionDemo {
public static void main(String[] args) {
// 1. ArithmeticException Handling
try {
int numerator = 10;
int denominator = 0;
int result = numerator / denominator; // This line will cause ArithmeticException
System.out.println("Result: " + result); // This won't execute
} catch (ArithmeticException e) {
System.err.println("Arithmetic Exception caught: Cannot divide by zero.");
// e.printStackTrace(); // Optionally print the stack trace
}
System.out.println("\n--- Moving to next demonstration ---\n");
// 2. ArrayIndexOutOfBoundsException Handling
try {
int[] numbers = {1, 2, 3};
System.out.println("Accessing element at index 3...");
int number = numbers[3]; // This line will cause ArrayIndexOutOfBoundsException
System.out.println("Element: " + number); // This won't execute
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Array Index Out Of Bounds Exception caught: Invalid index access.");
// e.printStackTrace(); // Optionally print the stack trace
}
System.out.println("\nProgram finished.");
}
}
Q8. Illustrate polymorphism and its types in Java. Differentiate between run-time
and compile-time polymorphism. Write super class Shape with method
displayArea() and sub class Rectangle. Demonstrate method overriding with this
example.
Word Count: ~180
Polymorphism: Meaning "many forms," polymorphism in Java allows objects of
different classes to respond to the same method call in ways specific to their class
type. It enhances flexibility and extensibility.
Types of Polymorphism:
1. Compile-Time Polymorphism (Static Binding / Method Overloading):
Achieved through method overloading. Multiple methods in the same class share
the same name but have different parameter lists (number, type, or order of
parameters). The compiler determines which method to call at compile time
based on the method signature (name and parameters).
2. Run-Time Polymorphism (Dynamic Binding / Method Overriding): Achieved
through method overriding. A subclass provides a specific implementation for a
method that is already defined in its superclass. The1 determination of which
method version (superclass's or subclass's) to execute happens at runtime,
based on the actual object type referred to by a superclass reference variable.
This requires inheritance.
Java
// Superclass
class Shape {
// Method to be overridden
{
void displayArea()
System.out.println("Calculating area in Shape class (no specific shape defined)");
}
}
// Subclass
class Rectangle extends Shape {
double length;
double width;
Rectangle(double l, double w) {
this.length = l;
this.width = w;
}
// Overriding the displayArea method
@Override
void displayArea() {
double area = length * width;
System.out.println("Area of Rectangle: " + area);
}
}
public class Main {
public static void main(String[] args) {
// Superclass reference pointing to a subclass object
Shape myShape = new Rectangle(10.0, 5.0);
// Calls the overridden method in the Rectangle class at runtime
myShape.displayArea(); // Output: Area of Rectangle: 50.0
Shape genericShape = new Shape();
genericShape.displayArea(); // Output: Calculating area in Shape class...
}
}
Q9. Illustrate Constructors and their applications in Java. Describe the types of
constructors used in Java. Write a class with name Employee with attributes
empId, name, department and email. Write all argument constructor for class
Student and create two objects with this constructor.
Word Count: ~200
Applications:
● Initializing instance variables with default or specific values.
● Setting up the initial state of an object.
● Performing necessary setup tasks before an object can be used.
Types of Constructors:
1. Default Constructor: If no constructor is explicitly defined in a class, the Java
compiler provides a default, no-argument constructor automatically. It initializes
instance variables to their default values (0 for numeric types, false for boolean,
null for object references).
2. No-Argument Constructor: A constructor explicitly defined by the programmer
that takes no parameters. It allows custom initialization without arguments.
3. Parameterized Constructor: A constructor that accepts one or more
parameters. It's used to initialize instance variables with values provided at the
time of object creation.
4. Copy Constructor (Not built-in, but a pattern): A constructor that takes an
object of the same class as a parameter and initializes the new object using the
values from the passed object.
Employee Class:
Java
class Employee {
intempId;
String name;
String department;
String email;
// Example: Parameterized constructor for Employee
public Employee(int empId, String name, String department, String email) {
this.empId = empId;
this.name = name;
this.department = department;
this.email = email;
}
// Other methods like getters/setters can be added here
}
Student Class with All-Argument Constructor and Object Creation:
Java
class Student {
int studentId;
String studentName;
String major;
// All-argument constructor
public Student(int studentId, String studentName, String major) {
this.studentId = studentId;
this.studentName = studentName;
this.major = major;
System.out.println("Student object created: ID=" + studentId + ", Name=" +
studentName);
}
}
public class School {
public static void main(String[] args) {
// Create two Student objects using the all-argument constructor
Student student1 = new Student(101, "Alice", "Computer Science");
Student student2 = new Student(102, "Bob", "Physics");
// You can now use student1 and student2 objects
}
}
Q10. Explain abstraction and abstract classes in Java. Describe abstract method.
With a suitable example demonstrate the application of abstract classes.
Word Count: ~210
Abstract Class: As explained in Q6, an abstract class (declared with abstract) serves
as a blueprint for other classes. It cannot be instantiated directly. It can contain:
● Abstract Methods: Methods declared with abstract and having no
implementation body (ending with a semicolon). They define a method signature
that must be implemented by any concrete (non-abstract) subclass.
● Concrete Methods: Regular methods with full implementations. These provide
common functionality inherited by all subclasses.
● Instance variables, constructors, static methods, etc.
Application Example: Abstract classes are useful when you want to define a
common base for a group of related subclasses, ensuring they all share certain
characteristics (implemented methods) and forcing them to implement specific
behaviors (abstract methods) in their own unique ways.
Java
Q11. Define the concept of classes and object in Java with a suitable example.
Word Count: ~220
Class: A class in Java is a blueprint or template for creating objects. It defines a set of
properties (instance variables or fields) and behaviors (methods) that objects of that
type will possess. It's a logical construct that doesn't occupy memory until an object is
created from it. Think of it as the design specification for a house; it defines the
number of rooms, dimensions, etc., but isn't the house itself. Classes encapsulate data
and the functions that operate on that data.
Example:
Java
Example:
Java
Q13. What is Encapsulation? How do you use Encapsulation for data hiding? Give
a suitable example.
Word Count: ~240
Encapsulation for Data Hiding: Data hiding (or information hiding) is achieved by
declaring the instance variables of a class as private. This prevents external code
(outside the class) from accessing or modifying the data directly. Instead, access is
controlled through public methods, commonly known as getters (accessor methods)
and setters (mutator methods).
● Getters: Public methods used to retrieve the value of a private instance variable.
● Setters: Public methods used to modify the value of a private instance variable.
Setters often include validation logic to ensure the data remains in a valid state.
By controlling access through methods, the class maintains control over its internal
state, preventing invalid data assignments and hiding the internal implementation
details from the outside world. This enhances security, flexibility (internal
implementation can change without affecting external code using the public
methods), and maintainability.
Example:
Java
class BankAccount {
// Private instance variable - hidden from outside access
private double balance;
private String accountNumber;
// Constructor
public BankAccount(String accNum, double initialBalance) {
this.accountNumber = accNum;
// Use setter for initial validation if needed
this.setBalance(initialBalance);
}
// Public getter method for balance
public double getBalance() {
return balance;
}
// Public setter method for balance with validation
public void setBalance(double newBalance) {
if (newBalance >= 0) { // Validation logic
this.balance = newBalance;
} else {
System.err.println("Error: Balance cannot be negative.");
}
}
// Public getter for account number (read-only after creation perhaps)
public String getAccountNumber() {
return accountNumber;
}
// Other methods (deposit, withdraw) would also use getters/setters internally
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount; // Direct access is okay WITHIN the class
System.out.println("Deposited: " + amount);
} else {
System.err.println("Error: Deposit amount must be positive.");
}
}
}
public class Banking {
public static void main(String[] args) {
BankAccount myAccount = new BankAccount("12345", 1000.0);
// Cannot access balance directly:
// System.out.println(myAccount.balance); // Compile-time error!
// Access balance via getter
System.out.println("Current Balance: " + myAccount.getBalance());
// Modify balance via setter
myAccount.setBalance(1500.0);
System.out.println("New Balance: " + myAccount.getBalance());
// Attempt invalid modification
myAccount.setBalance(-50.0); // Setter prevents this
System.out.println("Balance after invalid attempt: " + myAccount.getBalance());
myAccount.deposit(200);
System.out.println("Final Balance: " + myAccount.getBalance());
}
}
The Java architecture relies heavily on the concepts of the Java Virtual Machine (JVM)
and bytecode to achieve its "Write Once, Run Anywhere" (WORA) capability.
Bytecode: When you compile a Java source file (.java), the Java compiler (javac) does
not produce native machine code specific to the operating system or hardware (like a
C++ compiler might). Instead, it generates an intermediate, platform-independent
code called bytecode (.class files). Bytecode consists of a set of instructions that are
similar to assembly language but are designed for the JVM, not for a specific
processor. It's a highly optimized set of instructions created to be executed efficiently
by the Java interpreter/JVM.
The history of Java began in the early 1990s at Sun Microsystems. Initially conceived
as a project called "Oak" by James Gosling, Mike Sheridan, and Patrick Naughton
(often referred to as the "Green Team"), the goal was to develop a language for digital
devices like set-top boxes and interactive television. Oak was designed to be simple,
robust, platform-independent, and secure, suitable for networked environments and
consumer electronics.
The initial focus on consumer electronics didn't gain much traction. However, with the
rise of the World Wide Web in the mid-1990s, the team realized Oak's potential for
internet programming. Its platform independence was particularly well-suited for the
diverse hardware and operating systems accessing the web.
In 1995, Oak was renamed "Java" (reportedly inspired by coffee). Sun Microsystems
formally announced Java and its "HotJava" web browser (which could run Java
applets embedded in web pages) at the SunWorld conference. Netscape quickly
announced its intention to license Java for its popular Navigator browser, significantly
boosting Java's visibility and adoption.
The key philosophy was "Write Once, Run Anywhere" (WORA), enabled by compiling
Java code into intermediate bytecode executed by a Java Virtual Machine (JVM)
specific to each platform. This freed developers from writing and compiling different
code versions for different operating systems.
Java 1.0 was released in January 1996. Subsequent major releases introduced
significant enhancements:
● JDK 1.1 (1997): Inner classes, JavaBeans, JDBC (Java Database Connectivity),
RMI (Remote Method Invocation).
● J2SE 1.2 (1998): Swing GUI toolkit, Collections Framework, introduction of the
Java Plug-in, JVM improvements. Renamed to Java 2 Platform.
● J2SE 1.3 & 1.4 (2000, 2002): Performance enhancements (HotSpot JVM),
assertions, regular expressions, NIO (New I/O).
● J2SE 5.0 (2004): Major release introducing generics, enhanced for loop,
autoboxing/unboxing, annotations, enums, static import.
● Java SE 6 (2006): Performance improvements, scripting language support,
improved web services support.
● Java SE 7 (2011): First release under Oracle (after acquiring Sun Microsystems in
2010). Included Project Coin features (like try-with-resources, diamond operator),
Fork/Join framework, NIO.2.
● Java SE 8 (2014): Landmark release introducing Lambda expressions, Stream
API, Default methods in interfaces, new Date/Time API.
● Later Releases (9+): Introduction of the Module System (Project Jigsaw), faster
release cadence (every six months), and numerous other features like var for local
variables, switch expressions, text blocks, records, sealed classes, pattern
matching for instanceof.
Java evolved from a language for consumer electronics to a dominant force in web
applications, enterprise software, Android mobile development, big data, and more,
known for its robustness, portability, and extensive ecosystem.
The "life cycle" of a Java program typically refers to the sequence of steps from
writing the source code to its execution and termination. It involves several distinct
phases managed by the Java Development Kit (JDK) and the Java Runtime
Environment (JRE), specifically the Java Virtual Machine (JVM).
1. Writing Source Code: A developer writes human-readable Java code using a
text editor or an Integrated Development Environment (IDE). This code is saved in
files with a .java extension (e.g., MyProgram.java). The code defines classes,
methods, variables, and logic according to Java syntax rules.
2. Compilation: The Java source code (.java file) is compiled using the Java
compiler (javac), which is part of the JDK. The compiler performs several checks:
○ Syntax Checking: Ensures the code follows Java's grammatical rules.
○ Type Checking: Verifies that operations are performed on compatible data
types. If compilation is successful, the compiler translates the source code
into platform-independent bytecode. This bytecode is saved in .class files
(e.g., MyProgram.class). If errors are found, the compiler reports them, and
the .class file is not generated until the errors are fixed.
3. Loading: When the program is executed (e.g., using the java command), the Java
Virtual Machine (JVM) starts. The first step within the JVM is loading the
necessary .class files. The JVM's ClassLoader subsystem finds and loads the
main class (containing the main method) and any other classes required by the
program into memory (specifically, the Method Area).
4. Verification: Before execution, the loaded bytecode undergoes verification by
the Bytecode Verifier. This crucial security step checks if the bytecode is valid,
adheres to JVM specifications, and doesn't violate security constraints (e.g.,
ensuring proper stack usage, preventing illegal memory access). This protects the
host system from potentially malicious or malformed code.
5. Execution: After verification, the JVM's Execution Engine executes the bytecode.
This can happen in two ways:
○ Interpretation: The interpreter reads and executes the bytecode instruction
by instruction. This is slower but allows for quick startup.
○ Just-In-Time (JIT) Compilation: The JIT compiler analyzes the bytecode
during runtime. Frequently executed sections ("hotspots") are compiled into
native machine code specific to the underlying hardware and OS. This native
code is then executed directly by the processor, leading to significant
performance improvements compared to pure interpretation. Most modern
JVMs use a combination of interpretation and JIT compilation (like the
HotSpot JVM).
6. Runtime Operations: During execution, the JVM manages runtime data areas
(Heap for objects, Stack for method calls/local variables), handles object
creation, performs automatic garbage collection to reclaim memory from
unreferenced objects, and manages threads if the application is multithreaded.
7. Termination: The program execution continues until the main method completes,
an exit method (like System.exit()) is called, or an unhandled exception terminates
the program. Upon termination, the JVM instance shuts down, releasing all
allocated resources.
Q17. Describe static Data member, static methods in java
Word Count: ~310
In Java, the static keyword is used to associate a member (variable or method) with
the class itself, rather than with a specific instance (object) of the class. This means
static members belong to the class definition, and there is only one copy shared
among all objects created from that class.
● Single Copy: Only one copy of a static variable exists per class, regardless of
how many objects of that class are created. All instances share this single copy. If
one object changes the value of a static variable, the change is reflected across
all other objects of that class.
● Memory Allocation: Memory for static variables is allocated only once when the
class is loaded by the JVM, typically in the Method Area. Instance variables get
memory allocated each time an object is created (in the Heap).
● Access: Static variables can be accessed directly using the class name (e.g.,
Counter.count) without needing to create an object. They can also be accessed
through an object reference (e.g., myCounterObject.count), but using the class
name is preferred for clarity as it emphasizes that the variable belongs to the
class.
● Usage: Often used for constants (when combined with final), counters shared
across all instances, or properties common to all objects of a class (e.g., a default
interest rate for all BankAccount objects).
final, finally, and finalize are three distinct keywords/concepts in Java that sound
similar but serve entirely different purposes. Misunderstanding their roles is a
common source of confusion.
1. final Keyword:
● final Class: A class declared final cannot be subclassed (inherited from). This is
often done for security reasons or to ensure the immutability of a class (like the
String class).
Java
final class Immutable { /* ... */ }
// class SubImmutable extends Immutable {} // Compile Error: Cannot inherit from final class
2. finally Block:
finally is a keyword used in exception handling, specifically with try-catch blocks. The
finally block defines code that is guaranteed to execute, regardless of whether an
exception was thrown or caught within the preceding try block.
● Purpose: Primarily used for resource cleanup (e.g., closing files, network
connections, database connections) to ensure that resources are released
properly, preventing leaks, even if errors occur.
● Execution: The code inside finally executes after the try block finishes normally,
or after a catch block finishes handling an exception, or even if an exception
occurs in try but isn't caught by any catch block (the finally block runs before the
exception propagates further up the call stack). The only times finally might not
run are JVM crashes or if System.exit() is called within the try or catch block.
Java
try {
// Code that might throw an exception or requires cleanup
System.out.println("Inside try block");
} catch (Exception e) {
System.out.println("Inside catch block");
} finally {
System.out.println("Inside finally block - always executes for cleanup");
}
3. finalize() Method:
In Summary:
● final: Modifier for immutability/preventing extension.
● finally: Block for guaranteed code execution in exception handling (resource
cleanup).
● finalize(): Method called (unreliably) by GC before object destruction
(discouraged for cleanup).
The combination of final and static applied to data members (variables) or functions
(methods) creates specific behaviors and constraints in Java, primarily related to
constants and class-level utility methods that cannot be altered or overridden.
When a data member (variable) is declared as both final and static, it creates a
compile-time constant if initialized with a constant expression (a literal value or an
expression involving only other compile-time constants).
● Declaration: public static final <Type> VARIABLE_NAME = <Compile-Time
Constant Value>;
Java
public class Configuration {
public static final int MAX_CONNECTIONS = 10; // Compile-time constant
public static final String DEFAULT_GREETING = "Hello"; // Compile-time constant
public static final double PI = 3.14159; // Compile-time constant
// Not a compile-time constant if value requires runtime calculation
// public static final long START_TIME = System.currentTimeMillis();
}
● Characteristics:
1. static: Belongs to the class, not any specific object. Only one copy exists for
the class. Accessible via the class name (e.g.,
Configuration.MAX_CONNECTIONS).
2. final: Its value cannot be changed after initialization. It must be initialized
either at the point of declaration or within a static initializer block.
3. Constant: Represents a fixed value. By convention, the names of such
constants are written in all uppercase letters with words separated by
underscores (e.g., MAX_CONNECTIONS).
4. Optimization: For true compile-time constants (initialized with constant
expressions), the Java compiler often replaces references to the constant
directly with its value in the bytecode (inlining). This can improve
performance.
● Usage: Widely used to define unchanging values that are universally applicable
within the application domain, such as mathematical constants (Math.PI), default
configuration values, or representing fixed states or codes.
● Characteristics:
1. static: The method belongs to the class (Utility) and can be called directly
using the class name (e.g., Utility.getAppName()) without needing an object
instance. It cannot access instance members directly and doesn't have a this
reference.
2. final: The method cannot be overridden by any subclass. While static
methods cannot technically be overridden in the same way instance methods
are (because they don't participate in runtime polymorphism), declaring a
static method final prevents subclasses from hiding it with another static
method of the same signature. It explicitly signals that this class-level
method's implementation is fixed and should not be replaced or hidden down
the inheritance chain.
● Usage: This combination is less common than final static variables. It might be
used for critical utility methods belonging to a class where ensuring the exact
implementation is used, and preventing subclasses from providing an alternative
static method with the same signature, is paramount. However, since static
methods don't participate in polymorphism, the primary benefit is preventing
hiding, which is often less of a concern than preventing instance method
overriding. If the entire class is final, its static methods are implicitly
non-overridable (as there can be no subclasses), making the final keyword on the
static method redundant in that specific case.
In essence, final static signifies something that is both tied to the class definition
(shared, no object needed) and fixed (unchangeable value or
non-overridable/non-hideable implementation).
Q20. What do you understand by Inheritance? Explain its type with example.
Word Count: ~400
Sources
1. https://github.com/Babludhaker/Java-OOPS-Concept
2.
https://abhisheks008.hashnode.dev/technical-interview-questions-commonly-asked-during-cam
pus-placement-drives
3. https://github.com/singhprincekumar12006011/JavaCoding
4. https://github.com/jyppro/Coding-diary
5. https://medium.com/feed/@aarthihonguthi025
6. https://github.com/NK29/com.loa.javaExample
7. https://teachingbee.in/blog/diamond-problem-in-java/
8. https://www.scribd.com/document/796057756/Java-Threads-Overview