0% found this document useful (0 votes)
20 views

Java QA

Uploaded by

ag9998
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Java QA

Uploaded by

ag9998
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PART – C

Question 1. With the help of suitable example, discuss the various access modifier in Java.
Access modifiers are keywords used to define the accessibility of classes, methods, and
variables within a program. There are four types of access modifiers: public, private, protected,
and default (no explicit modifier).

Public Modifier:

• The public access modifier is the least restrictive.


• Classes, methods, and variables declared as public can be accessed from anywhere in
the program.
• This is the most commonly used access modifier, as it allows you to share your code
with other developers.

public class MyClass


{
public int publicVariable = 10;
public void publicMethod()
{
System.out.println("This is a public method");
}
}
Private Modifier:

• The private access modifier is the most restrictive.


• Classes, methods, and variables declared as private can only be accessed from within
the class in which they are declared.
• This is useful for hiding implementation details from other developers.

public class MyClass {


private int privateVariable = 20;
private void privateMethod() {
System.out.println("This is a private method");
}
}
Protected:

• The protected access modifier is a middle ground between public and private.
• Classes, methods, and variables declared as protected can be accessed from within the
class in which they are declared, as well as from subclasses of that class.
• This is useful for sharing code with subclasses, while still preventing it from being
accessed by other classes.

package mypackage;
public class MyClass {
protected int protectedVariable = 30;
protected void protectedMethod() {
System.out.println("This is a protected method");
}
}
Default:

• If no access modifier is specified, the default access modifier is used.


• Classes, methods, and variables declared with the default access modifier can only be
accessed from within the same package as the class in which they are declared.
• This is the least restrictive access modifier that is not public.

package mypackage;
class MyClass {
int defaultVariable = 40;
void defaultMethod() {
System.out.println("This is a default method");
}
}

examples of how access modifiers can be used in Java:

• A public class can be used by any other class in the program.


• A private method cannot be accessed by any other class in the program.
• A protected method can be accessed by subclasses of the class in which it is
declared.
• A variable declared with the default access modifier can only be accessed by
classes in the same package as the class in which it is declared.

Question 2: Different between multilevel inheritance and hierarchical inheritance in java.


Support your answers with suitable code examples.

Multilevel Inheritance:
• In multilevel inheritance, classes are organized in a hierarchical structure where each
class extends to another class, forming a chain or hierarchy. The derived class serves as
the base class for the next level.
Example:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking");
}
}

class Labrador extends Dog {


void color() {
System.out.println("Labrador is brown");
}
}
public class Main {
public static void main(String[] args) {
Labrador labrador = new Labrador();
labrador.eat(); // Output: Animal is eating
labrador.bark(); // Output: Dog is barking
labrador.color(); // Output: Labrador is brown
}
}
In the above example, the Animal class is the base class, the Dog class extends to the
Animal class, and the Labrador class extends to the Dog class. The Labrador class
inherits the properties and methods from both the Animal and Dog classes.

Hierarchical Inheritance:
• In hierarchical inheritance, multiple classes extend a single base class, creating a tree-like
structure. Each derived class inherits from the same base class independently.
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


void drawCircle() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
void drawRectangle() {
System.out.println("Drawing a rectangle");
}
}

public class Main {


public static void main(String[] args) {
Circle circle = new Circle();
circle.draw(); // Output: Drawing a shape
circle.drawCircle(); // Output: Drawing a circle

Rectangle rectangle = new Rectangle();


rectangle.draw(); // Output: Drawing a shape
rectangle.drawRectangle(); // Output: Drawing a rectangle
}
}
In the above example, the Shape class is the base class, and both the Circle and Rectangle
classes extend the Shape class independently. They inherit the properties and methods from
the Shape class separately.

In summary, the key differences between multilevel inheritance and hierarchical inheritance are
as follows:
• Multilevel inheritance involves extending classes in a linear chain, where each derived
class serves as the base class for the next level.
• Hierarchical inheritance involves multiple classes extending a single base class
independently, creating a tree-like structure.
PART – B
Question 1. (a). What is Object Oriented Programming? Discuss the various OOPs principles in
java.

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design


around objects, which are instances of classes. OOP promotes the concept of encapsulating
data and behavior into reusable objects, allowing for modular and efficient software
development. In Java, OOP is a fundamental aspect of the language. Let's discuss the various
principles of OOP in Java:
1. Encapsulation:
• Encapsulation is the process of bundling data and methods together within a
class, providing access to the data through well-defined methods.
• It helps in data hiding, allowing access to data only through controlled interfaces,
thus ensuring data integrity and security.
2. Inheritance:
• Inheritance allows a class (subclass) to inherit properties and behaviors from
another class (superclass).
• It facilitates code reuse, enables hierarchical relationships, and promotes the
concept of generalization and specialization.
• In Java, a subclass extends to a superclass using the extends keyword.
3. Polymorphism:
• Polymorphism enables objects to exhibit different behaviors based on their
specific types or the context in which they are used.
• It allows methods to be overridden in subclasses, providing different
implementations while adhering to a common interface or inheritance hierarchy.
• Polymorphism is achieved through method overriding and method overloading in
Java.
4. Abstraction:
• Abstraction focuses on creating simplified and generalized models of real-world
entities or concepts.
• It allows the creation of abstract classes and interfaces, which define common
behavior and characteristics without specifying implementation details.
• Abstraction helps in achieving modular and loosely coupled designs.
5. Association:
• Association represents relationships between objects, where one object is
related to another in some way.
• It can be a one-to-one, one-to-many, or many-to-many relationship.
• Associations can be implemented through instance variables, parameter passing,
or method return types.
6. Composition:
• Composition represents a "has-a" relationship between objects, where one
object contains other objects as its parts.
• It implies a strong relationship, where the existence of the contained object
depends on the existence of the container object.
• Composition is achieved by creating instances of other classes as member
variables within a class.
7. Aggregation:
• Aggregation is a form of association that represents a whole-part relationship
between objects.
• It implies a weaker relationship, where the existence of the contained object is
independent of the existence of the container object.
• Aggregation is represented by creating references to other classes as member
variables within a class.
These principles of OOP provide a structured approach to software development, allowing for
modularity, reusability, and maintainability of code. By following these principles, developers
can design robust and efficient Java applications.

Question 1. (b). Different between method overloading and overriding in Java.


Method Overloading:
1. Definition:
• Method overloading allows multiple methods with the same name but different
parameters to coexist within a class.
2. Syntax:
• Overloaded methods have the same name but different parameter lists (number,
order, or types of parameters).
3. Occurrence:
• Overloading occurs within a single class.
4. Polymorphism:
• Overloading is an example of static polymorphism (compile-time polymorphism)
as the decision is made during compilation based on the method signature.
5. Relationship:
• Overloaded methods are related by having the same name but different method
signatures (parameters).
6. Return Type:
• Overloaded methods may have the same or different return types.
Method Overriding:
1. Definition:
• Method overriding occurs when a subclass provides its own implementation of a
method that is already defined in its superclass.
2. Syntax:
• Overriding methods have the same name, return type, and parameter list as the
method in the superclass.
3. Occurrence:
• Overriding occurs between a superclass and its subclass.
4. Polymorphism:
• Overriding is an example of dynamic polymorphism (runtime polymorphism) as
the decision is made during runtime based on the actual object type.
5. Relationship:
• Overriding methods are related by inheritance, where the subclass inherits the
method from the superclass.
6. Return Type:
• Overriding methods must have the same return type as the method in the
superclass, or a covariant return type (a subtype of the original return type).
In summary, method overloading is the process of having multiple methods with the same
name but different parameters within a class, while method overriding occurs when a
subclass provides its own implementation of a method inherited from its superclass.
Method overloading is determined at compile-time (static polymorphism), while method
overriding is determined at runtime (dynamic polymorphism).

Question 2. (a). Write a program in java to display student id and name using default and
parameterized constructors.
class Student {
private int id;
private String name;

// Default Constructor
public Student() {
id = 101;
name = "Suresh";
}

// Parameterized Constructor
public Student(int id, String name) {
this.id = id;
this.name = name;
}

public void display() {


System.out.println("Student ID: " + id);
System.out.println("Student Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
// Using Default Constructor
Student student1 = new Student();
System.out.println("Using Default Constructor:");
student1.display();
System.out.println();
// Using Parameterized Constructor
Student student2 = new Student(102, "Aravind");
System.out.println("Using Parameterized Constructor:");
student2.display();
}
}
In the above program, we have a Student class with a default constructor and a
parameterized constructor. The default constructor initializes the id and name with default
values, while the parameterized constructor takes values for id and name as parameters.
In the Student class, the display method is defined to print the student ID and name.
In the Main class, we create two instances of the Student class. The first instance uses the
default constructor, and the second instance uses the parameterized constructor. We then
call the display method on both instances to display the student ID and name.
When you run the program, the output will be:
Using Default Constructor:
Student ID: 101
Student Name: Suresh
Using Parameterized Constructor:
Student ID: 102
Student Name: Aravind
Question 2. (b). What is inheritance and explain the terms parent class and child class? State
the advantage of inheritance in java.
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class
to inherit properties and behaviors from another class. It establishes a hierarchical relationship
between classes, where the derived class (child class) inherits the characteristics of the base
class (parent class).
Parent Class:
• A parent class (also known as a superclass or base class) is the class that is being
extended or inherited from.
• It defines common attributes and behaviors that can be shared by its child classes.
• The parent class serves as a blueprint for its child classes to build upon.
Child Class:
• A child class (also known as a subclass or derived class) is a class that inherits properties
and behaviors from its parent class.
• It extends or specializes in the functionality of the parent class by adding its own unique
attributes and behaviors.
• The child class can access and utilize the members (methods and variables) of the parent
class, along with its own members.
Advantages of Inheritance in Java:
1. Code Reusability:
2. Code Organization and Maintenance
3. Method Overriding
4. Polymorphism
5. Code Extensibility.
Overall, inheritance in Java promotes code reusability, enhances code organization, and
enables extensibility and flexibility in the object-oriented design. It is a powerful
mechanism for creating hierarchical relationships and building complex class hierarchies.
Question 3. (a). Discuss the differences between checked and unchecked exceptions in Java.
Checked Exceptions:
Checked exceptions are typically used to handle expected exceptional conditions
that can occur during the execution of a program, such as file I/O errors or database
connection issues.

1. Definition:
• Checked exceptions are exceptions that are checked at compile-time.
• Methods that can potentially throw checked exceptions must declare them using
the throws keyword.
2. Handling Requirement:
• Checked exceptions must be either caught and handled within a try-catch block
or declared to be thrown by the method using the throws keyword.
3. Examples:
• Some examples of checked exceptions in Java include IOException,
SQLException, ClassNotFoundException, and InterruptedException.
4. Inheritance:
• Checked exceptions are subclasses of the Exception class or its subclasses
(excluding RuntimeException and its subclasses).
5. Recovery:
• Checked exceptions are typically recoverable. The programmer is expected to
anticipate and handle these exceptions gracefully, allowing the program to
recover from exceptional conditions.
Unchecked Exceptions:
Unchecked exceptions are often used for programming errors, such as null
pointer dereferences or array out-of-bounds errors, which may indicate bugs in the code
or incorrect usage of methods.

1. Definition:
• Unchecked exceptions are exceptions that are not checked at compile-time.
• They do not require explicit handling or declaration using the throws keyword.
2. Handling Requirement:
• Unchecked exceptions can be caught and handled within a try-catch block, but it
is not mandatory.
• They can also be allowed to propagate up the call stack without being caught or
declared.
3. Examples:
• Some examples of unchecked exceptions in Java include NullPointerException,
ArrayIndexOutOfBoundsException, IllegalArgumentException, and
ArithmeticException.
4. Inheritance:
• Unchecked exceptions are subclasses of the RuntimeException class or its
subclasses.
5. Recovery:
• Unchecked exceptions are typically unrecoverable and indicate programming
errors or exceptional conditions that cannot be easily handled during runtime.
Question 3. (b). What is Deadlock in Java? What are the precautions to avoid a deadlock state
in java?
Deadlock in Java refers to a situation where two or more threads are blocked indefinitely,
waiting for each other to release resources. It occurs when two or more threads acquire
different locks but are unable to proceed because each thread is waiting for a lock held by
another thread. As a result, the threads are effectively stuck, and the program cannot make
progress.
Precautions to Avoid Deadlock in Java:
1. Avoid Circular Dependency:
• Ensure that threads do not form a circular dependency while acquiring locks. This
can be achieved by defining a consistent order for acquiring locks and ensuring
that all threads follow the same order.
2. Avoid Holding Multiple Locks:
• Minimize the usage of multiple locks within a critical section. Holding multiple
locks increases the likelihood of potential deadlocks.
• If multiple locks are required, ensure that the order of acquiring and releasing
locks is consistent across all threads.
3. Use Timeout with Locks:
• When acquiring locks, use a timeout mechanism to avoid waiting indefinitely.
This allows threads to proceed if a lock is not available within a specified time.
• The tryLock() method of Lock interface in Java provides a way to attempt to
acquire a lock with a timeout.
4. Avoid Nested Locking:
• Avoid acquiring locks within a critical section that already holds a lock. This can
lead to nested locking, which increases the risk of deadlock.
• If nested locking is necessary, ensure that proper precautions are taken to avoid
circular dependencies and to release locks in the reverse order of acquisition.
5. Resource Ordering:
• If multiple threads need to acquire multiple resources, establish a consistent
order for acquiring those resources.
• By acquiring resources in a predefined order, you reduce the chance of
conflicting resource acquisition and potential deadlock.
6. Deadlock Detection and Recovery:
• Implement mechanisms to detect and recover from deadlock situations.
• Techniques such as timeout-based locking, periodic deadlock detection
algorithms, and thread interruption can be employed to identify and recover
from deadlocks.
7. Design and Test Concurrency:
• Properly design and test concurrent programs to identify and address potential
deadlock scenarios.
• Use synchronized blocks, locks, and another concurrency constructs judiciously,
ensuring they are correctly implemented and tested.
Question 4. (a). With regard to event handling, describe the different Layout Managers in Java
Layout Managers are used to determine how components are arranged within a container. They
play a crucial role in event handling and graphical user interface (GUI) design. Here are some
commonly used Layout Managers in Java:
1. FlowLayout:
• FlowLayout arranges components in a left-to-right flow, wrapping to the next line
if necessary.
• Components are placed one after another in the order they are added to the
container.
• It is useful for simple designs where components are meant to be displayed in a
sequential flow.
2. BorderLayout:
• BorderLayout divides the container into five regions: North, South, East, West,
and Center.
• Components are added to these regions, and they occupy the available space
within their respective regions.
• It is useful for organizing components in a larger container with distinct regions.
3. GridLayout:
• GridLayout arranges components in a grid-like structure with a specified number
of rows and columns.
• Components are placed in cells of equal size, occupying the available space
equally.
• It is useful for creating uniform layouts with a fixed number of rows and columns.
4. GridBagLayout:
• GridBagLayout provides more flexibility and control in component placement
compared to GridLayout.
• It uses constraints to define the placement and sizing of components within a
grid-based layout.
• It is useful for complex layouts where components need to be positioned and
resized precisely.
5. CardLayout:
• CardLayout allows multiple components to be stacked on top of each other, like a
deck of cards.
• Only one component is visible at a time, and switching between components is
done using methods like next() or previous().
• It is useful for creating panels with multiple views or steps, such as wizard-like
interfaces.
6. GroupLayout:
• GroupLayout is a flexible and powerful layout manager introduced in Java Swing.
• It allows precise positioning and alignment of components using GroupLayout's
auto-generated code.
• GroupLayout is typically used when designing GUIs using a GUI builder tool like
the NetBeans GUI Builder.
Question 4. (b). With the help of suitable examples, explain the different kinds of operators in
Java.
Arithmetic Operators:
• Arithmetic operators perform basic arithmetic operations like addition, subtraction,
multiplication, division, and modulo.
int a = 10;
int b = 5;
int addition = a + b; // 15
int subtraction = a - b; // 5
int multiplication = a * b; // 50
int division = a / b; // 2
int modulo = a % b; // 0
Relational Operators:
• Relational operators compare two values and return a boolean result (true or false).
int x = 5;
int y = 10;
boolean isEqual = (x == y); // false
boolean isGreater = (x > y); // false
boolean isLess = (x < y); // true

Logical Operators:
• Logical operators perform logical operations on boolean values and return a boolean
result.
boolean p = true;
boolean q = false;
boolean logicalAnd = p && q; // false
boolean logicalOr = p || q; // true
boolean logicalNot = !p; // false

Assignment Operators:
• Assignment operators are used to assign values to variables.
int num = 10;
num += 5; // num = num + 5 (15)
num -= 3; // num = num - 3 (12)
num *= 2; // num = num * 2 (24)
num /= 4; // num = num / 4 (6)

Bitwise Operators:
• Bitwise operators perform operations on individual bits of integers.
int m = 5; // 0101 in binary
int n = 3; // 0011 in binary
int bitwiseAnd = m & n; // 0001 (1)
int bitwiseOr = m | n; // 0111 (7)
int bitwiseXor = m ^ n; // 0110 (6)
int bitwiseComplement = ~m; // 1010 (-6)
Ternary Operator:
• The ternary operator is a shorthand conditional operator that evaluates a condition and
returns a value based on the result.
int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";
// result will be "Adult" since the condition is true.

Question 5. (a). With the help of suitable examples, discuss in detail the java AWT buttons and
AWT labels.
Java AWT Buttons:
AWT Buttons are interactive components used for user input or triggering actions. They can be
clicked by the user to perform certain tasks.
Example:
import java.awt.*;
import java.awt.event.*;

public class ButtonExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("Button Example");

// Create a button
Button button = new Button("Click Me");

// Add button to the frame


frame.add(button);
// Add action listener to the button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Action to be performed when the button is clicked
System.out.println("Button Clicked!");
}
});

// Set frame size and make it visible


frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
In the above example, we create an AWT Button named "Click Me" and add it to an Frame. We
also attach an ActionListener to the button, which listens for button clicks. When the button is
clicked, the actionPerformed method of the ActionListener is invoked, and in this example, it
simply prints "Button Clicked!" to the console.
Java AWT Labels:
AWT Labels are used to display text or an image on the GUI. They provide information or
captions for other components.
Example:
import java.awt.*;

public class LabelExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("Label Example");
// Create a label
Label label = new Label("Hello, World!");

// Add label to the frame


frame.add(label);

// Set frame size and make it visible


frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
In this example, we create an AWT Label with the text "Hello, World!" and add it to the Frame.
The label is displayed on the GUI, providing information or a caption.

Question 5. (b). Describe in detail the string constructor in java.


the String class provides several constructors to create string objects. The String constructor
allows you to instantiate a new String object with different initial values. Here is a detailed
description of the String constructor in Java:
Empty Constructor:
• String(): Creates an empty string with a length of 0.
String str = new String();
Character Array Constructor:
• String(char[] value): Creates a new string object with the characters from the provided
character array.
• String(char[] value, int offset, int count): Creates a new string object with a substring of
characters from the character array, starting from the specified offset and having the
specified count.
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str1 = new String(chars); // "Hello"
String str2 = new String(chars, 1, 3); // "ell"

Byte Array Constructor:


• String(byte[] bytes): Creates a new string object by decoding the byte array using the
platform's default charset.
• String(byte[] bytes, Charset charset): Creates a new string object by decoding the byte
array using the specified charset.
byte[] bytes = {72, 101, 108, 108, 111};
String str3 = new String(bytes); // "Hello"

String Constructor:
• String(String original): Creates a new string object with the same content as the original
string.
String original = "Hello";
String str4 = new String(original); // "Hello"

StringBuffer/StringBuilder Constructor:
• String(StringBuffer buffer): Creates a new string object with the same characters as the
StringBuffer object.
• String(StringBuilder builder): Creates a new string object with the same characters as
the StringBuilder object.
StringBuffer buffer = new StringBuffer("Hello");
String str5 = new String(buffer); // "Hello"

Unicode Code Point Array Constructor:


• String(int[] codePoints, int offset, int count): Creates a new string object by converting
the specified range of Unicode code points to characters.
int[] codePoints = {72, 101, 108, 108, 111};
String str6 = new String(codePoints, 0, 5); // "Hello"
These are some of the commonly used String constructors in Java. Each constructor allows you
to create a String object with different initial values, such as character arrays, byte arrays,
existing strings, StringBuffer, StringBuilder, or Unicode code points. The appropriate
constructor can be chosen based on the available data and the desired representation of the
string.

You might also like