Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

UNIT 1

1. Demonstrate Constructor Overloading Concept with a example


program
class Sum{
public Sum(int a,int b){
System.out.println((a+b));
}

Public Sum(int a,int b ,int c){


System.out.println((a+b+c));
}
public Sum(Double a,Double b){
System.out.println((a+b));
}
}

class Ques1{
public static void main(String[] args) {

Sum obj1 = new Sum(3,4);


Sum obj2 = new Sum(5,1,3);
Sum obj3 = new Sum(2.4,5.2);
}
}

2. Illustrate the inheritance concept? Explain Different forms of


inheritance with suitable program segments
Sol:
1. Single Inheritance: A class inherits from only one superclass.
2. Multilevel Inheritance: A class inherits from a superclass, and
another class inherits from this subclass, forming a chain of
inheritance.
3. Hierarchical Inheritance: Multiple classes inherit from a single
superclass.
4. Multiple Inheritance (not supported in Java): A class inherits from
multiple superclasses. Java doesn't support this directly, but it can
be achieved through interfaces.
5. Hybrid Inheritance (combination of two or more types of
inheritance): For example, a combination of single and multiple
inheritances.

// Single Inheritance
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {


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

// Multilevel Inheritance
class BabyDog extends Dog {
void weep() {
System.out.println("Baby dog is weeping");
}
}

// Hierarchical Inheritance
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing");
}
}

// Main class to demonstrate inheritance


public class InheritanceDemo {
public static void main(String[] args) {
// Single Inheritance
Dog dog = new Dog();
dog.eat();
dog.bark();

// Multilevel Inheritance
BabyDog babyDog = new BabyDog();
babyDog.eat();
babyDog.bark();
babyDog.weep();

// Hierarchical Inheritance
Cat cat = new Cat();
cat.eat();
cat.meow();
}
}

3. Demostrate Package concept? How to access import a package?


Explain with examples programs
Sol:
Create a Directory
src
├── com
│ └── example
│ ├── math
│ └── geometry

Create Java classes inside the packages:


 src/com/example/math/Calculator.java
package com.example.math;

public class Calculator {


public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {


return a - b;
}
}
 src/com/example/geometry/Rectangle.java

package com.example.geometry;

public class Rectangle {


private int length;
private int width;

public Rectangle(int length, int width) {


this.length = length;
this.width = width;
}

public int calculateArea() {


return length * width;
}
}

Now, let's create a main class outside the packages to demonstrate how
to import and access classes from packages:
import com.example.math.Calculator;
import com.example.geometry.Rectangle;

public class Main {


public static void main(String[] args) {
// Accessing classes from the packages
int sum = Calculator.add(5, 3);
System.out.println("Sum: " + sum);

Rectangle rectangle = new Rectangle(4, 5);


int area = rectangle.calculateArea();
System.out.println("Area of Rectangle: " + area);
}
}

Compile and run the Main.java file:


javac src/Main.java
java -cp src Main
4. Write a Program to illustrate the concept of static inner class with
static method with program
Sol:
public class OuterClass {

private static int outerData = 10;

// Static inner class


public static class InnerStaticClass {
public static void display() {
System.out.println("Inside static inner class method");
System.out.println("Outer data: " + outerData);
}
}

public static void main(String[] args) {


// Accessing static inner class method directly
OuterClass.InnerStaticClass.display();
}
}

5. Explain the following keywords with example


a. this b. super c. final d. static
Sol: a. this
 this is a reference variable that refers to the current object in a non-static
context.
 It can be used to access instance variables and methods, as well as to invoke
constructors.
 It is commonly used to disambiguate between instance variables and
parameters with the same name.
 public class MyClass {
 private int number;

 public MyClass(int number) {
 this.number = number; // 'this' refers to the instance variable
 }

 public void printNumber() {
 System.out.println("Number: " + this.number); // Accessing
instance variable using 'this'
 }

 public static void main(String[] args) {
 MyClass obj = new MyClass(10);
 obj.printNumber(); // Output: Number: 10
 }
 }

b. Super
c. super is a reference variable that is used to refer to the immediate parent
class object.
d. It can be used to call methods of the superclass, access superclass
constructor, or access superclass variables.

class Superclass {
public void display() {
System.out.println("Inside superclass");
}
}

public class Subclass extends Superclass {


public Subclass() {
super(); // Calling superclass constructor
}

public void display() {


super.display(); // Calling superclass method
System.out.println("Inside subclass");
}

public static void main(String[] args) {


Subclass obj = new Subclass();
obj.display();
/*
Output:
Inside superclass
Inside subclass
*/
}
}

c. final:
 final is a keyword that can be applied to variables, methods, and classes.
 When applied to a variable, it indicates that its value cannot be changed once
initialized.
 When applied to a method, it indicates that the method cannot be overridden
by subclasses.
 When applied to a class, it indicates that the class cannot be subclassed.
 public class Circle {
 private final double PI = 3.14;
 private final int radius;

 public Circle(int radius) {
 this.radius = radius;
 }

 public final double calculateArea() {
 return PI * radius * radius;
 }

 public static void main(String[] args) {
 Circle circle = new Circle(5);
 System.out.println("Area of circle: " +
circle.calculateArea()); // Output: Area of circle: 78.5
 }
 }

d. static:

 static is a keyword that can be applied to variables, methods, blocks, and


nested classes.
 When applied to a variable, it indicates that the variable belongs to the class,
not to instances of the class. There will be only one copy of the variable
shared among all instances.
 When applied to a method, it indicates that the method belongs to the class,
not to instances of the class. Static methods can be called directly using the
class name.
 When applied to a block, it creates a static initialization block that is executed
only once when the class is loaded
 public class Counter {
 private static int count = 0;

 public Counter() {
 count++; // Incrementing static variable
 }

 public static int getCount() {
 return count; // Accessing static variable
 }

 public static void main(String[] args) {
 Counter obj1 = new Counter();
 Counter obj2 = new Counter();
 System.out.println("Count: " + Counter.getCount()); // Output:
Count: 2
 }
 }

6. When does an object become eligible for garabage collection ?


Write a program which performs garbage collection.
An object becomes eligible for garbage collection when it is no longer
reachable or referenced by any active part of the program. In Java,
objects are eligible for garbage collection when they are no longer
reachable by any live thread or any static references
public class GarbageCollectionExample {

public static void main(String[] args) {


// Creating objects
Object obj1 = new Object();
Object obj2 = new Object();
Object obj3 = new Object();

// Making objects eligible for garbage collection


obj1 = null;
obj2 = null;

// Calling garbage collector


System.gc(); // Requesting garbage collector to run
}
}
7. what are uses of inner class ? write a program for anonymous
inner class
Sol:
1. Encapsulation: Inner classes can encapsulate helper classes that are only used
within a single class. This helps in organizing the code and reducing the scope
of helper classes.
2. Improved Readability: Inner classes can make the code more readable by
placing related classes closer together.
3. Access to Enclosing Class Members: Inner classes have access to the
members of the enclosing class, including private members, which can be
useful for certain design patterns.
4. Event Handling: Inner classes are commonly used for event handling in GUI
applications, where they can encapsulate event-handling logic.
5. Anonymous Inner Classes: Inner classes can be declared without a name,
known as anonymous inner classes, which are useful for implementing
interfaces or extending classes on the fly.

interface Greeting {
void greet();
}

public class AnonymousInnerClassExample {


public static void main(String[] args) {
// Using an anonymous inner class to implement the Greeting interface
Greeting greeting = new Greeting() {
@Override
public void greet() {
System.out.println("Hello, from anonymous inner class!");
}
};

// Invoking the greet method of the anonymous inner class


greeting.greet();
}
}
8. construct a realtion table for member access levels and visibilities

Access Level Class Package Subclass World


private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

Explanation:

 Private: Members with private access level are accessible only within the same
class. They are not accessible outside of the class, including subclasses and
other classes in the same package.
 Default (Package-private): Members with default access level are accessible
within the same package. They are not accessible outside of the package,
including subclasses and classes in other packages.
 Protected: Members with protected access level are accessible within the
same package and by subclasses, even if they are in a different package.
However, they are not accessible by other classes outside of the package that
are not subclasses.
 Public: Members with public access level are accessible from any other class.
They are visible to all classes, regardless of the package or inheritance
relationship.

// ClassA.java
package com.example.packageA;

public class ClassA {


private int privateVarA = 10;
int defaultVarA = 20;
protected int protectedVarA = 30;
public int publicVarA = 40;
}

// ClassB.java
package com.example.packageB;
import com.example.packageA.ClassA;

public class ClassB extends ClassA {


public void accessVariables() {
// Accessing variables from ClassA
// privateVarA is not accessible in ClassB
// defaultVarA is accessible in the same package
System.out.println("defaultVarA from ClassA: " + defaultVarA);

// protectedVarA is accessible in subclass


System.out.println("protectedVarA from ClassA: " + protectedVarA);

// publicVarA is accessible from anywhere


System.out.println("publicVarA from ClassA: " + publicVarA);
}
}

// Main.java
import com.example.packageA.ClassA;
import com.example.packageB.ClassB;

public class Main {


public static void main(String[] args) {
ClassA objA = new ClassA();
// objA.privateVarA is not accessible here

// objA.defaultVarA is accessible in the same package


System.out.println("defaultVarA from ClassA: " + objA.defaultVarA);

// objA.protectedVarA is not accessible here

// objA.publicVarA is accessible from anywhere


System.out.println("publicVarA from ClassA: " + objA.publicVarA);

ClassB objB = new ClassB();


objB.accessVariables(); // Accessing variables of ClassA through
ClassB
}
}
UNIT 2
1. how do you classify the exceptions? explain
exceptions hierarchy
1. Checked Exceptions:
 Checked exceptions are the exceptions that are checked at compile-
time. This means that the compiler ensures that these exceptions are
either caught using a try-catch block or declared to be thrown by the
method using the throws keyword.
 Examples of checked exceptions include IOException, SQLException,
and ClassNotFoundException.
 Checked exceptions are subclasses of java.lang.Exception but not
subclasses of java.lang.RuntimeException.
2. Unchecked Exceptions (Runtime Exceptions):
 Unchecked exceptions are the exceptions that are not checked at
compile-time. This means that the compiler does not enforce catching
or declaring these exceptions.
 Unchecked exceptions are subclasses of java.lang.RuntimeException.
 Examples of unchecked exceptions include NullPointerException,
ArrayIndexOutOfBoundsException, and IllegalArgumentException.

Exceptions Hierarchy:

 All exceptions in Java are subclasses of the java.lang.Throwable class.


 Throwable has two direct subclasses: Error and Exception.
 Error: Represents serious, usually fatal, problems that are not expected to be
caught by the application, such as OutOfMemoryError or StackOverflowError.
Errors are typically caused by the environment in which the application is
running, rather than by the application itself.
 Exception: Represents conditions that are caused by the application or the
environment in which the application is running. Exceptions are further
divided into checked exceptions and unchecked exceptions, as described
above.
 Exception class has several direct subclasses, including RuntimeException and
IOException.
 RuntimeException: Represents exceptions that can occur at runtime and are
typically unchecked exceptions. Examples include NullPointerException,
ClassCastException, and ArithmeticException.
 IOException: Represents exceptions related to input-output operations, such
as reading or writing to files, sockets, or streams.
 import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;

 public class ExceptionExample {
 // Method to demonstrate a checked exception (IOException)
 public void readFromFile(String filename) throws IOException {
 File file = new File(filename);
 FileReader reader = new FileReader(file);
 reader.close();
 }

 // Method to demonstrate an unchecked exception
(ArithmeticException)
 public void divide(int dividend, int divisor) {
 if (divisor == 0) {
 throw new ArithmeticException("Division by zero");
 }
 int result = dividend / divisor;
 System.out.println("Result of division: " + result);
 }

 // Method to demonstrate a custom checked exception
 public void processInput(String input) throws
IllegalArgumentException {
 if (input == null || input.isEmpty()) {
 throw new IllegalArgumentException("Input cannot be null or
empty");
 }
 System.out.println("Processing input: " + input);
 }

 public static void main(String[] args) {
 ExceptionExample example = new ExceptionExample();

 // Example of handling a checked exception (IOException)
 try {
 example.readFromFile("nonexistent-file.txt");
 } catch (IOException e) {
 System.err.println("IOException caught: " +
e.getMessage());
 }

 // Example of throwing an unchecked exception
(ArithmeticException)
 try {
 example.divide(10, 0);
 } catch (ArithmeticException e) {
 System.err.println("ArithmeticException caught: " +
e.getMessage());
 }

 // Example of throwing a custom checked exception
(IllegalArgumentException)
 try {
 example.processInput(null);
 } catch (IllegalArgumentException e) {
 System.err.println("IllegalArgumentException caught: " +
e.getMessage());
 }
 }
 }

2.Where we can use synchronized keyword in


java? Explain with example
The synchronized keyword in Java is used to control access to critical sections of code by
allowing only one thread at a time to execute that section. It can be applied to methods or
blocks of code.

1.Synchronized Methods:
 You can use the synchronized keyword to make an entire method synchronized.
This means that only one thread can execute the synchronized method of an object
at any given time.
 class Counter {
 private int count = 0;

 public synchronized void increment() {
 count++;
 }

 public synchronized void decrement() {
 count--;
 }

 public synchronized int getCount() {
 return count;
 }
2.Synchronized Blocks:
 You can use the synchronized keyword to create a synchronized block of code
within a method. This allows you to synchronize specific sections of code
rather than entire methods.
 class SharedResource {
 private int sharedData = 0;

 public void performTask() {
 synchronized(this) {
 // Synchronized block
 sharedData++;
 }
 }
 }

3.Static Synchronization:
 You can also use the synchronized keyword with static methods or blocks to
synchronize access to static variables or methods across all instances of a
class.
 class SharedResource {
 private static int sharedData = 0;

 public static synchronized void increment() {
 sharedData++;
 }

 public static synchronized int getSharedData() {
 return sharedData;
 }
 }

3.How do you place a try block with in another try block for two
different exceptions? Explain with program
public class NestedTryExample {
public static void main(String[] args) {
try {
// Outer try block
int[] numbers = {1, 2, 3};
System.out.println("Outer try block starts");

try {
// Inner try block
System.out.println("Inner try block starts");
System.out.println("Accessing element at index 3: " +
numbers[3]);
System.out.println("Inner try block ends");
} catch (ArrayIndexOutOfBoundsException e) {
// Catch block for ArrayIndexOutOfBoundsException
System.err.println("Inner catch block: Array index out of
bounds");
}

// Division operation which may throw ArithmeticException


int result = 10 / 0; // ArithmeticException

System.out.println("Outer try block ends");


} catch (ArithmeticException e) {
// Catch block for ArithmeticException
System.err.println("Outer catch block: Arithmetic exception
occurred");
}

System.out.println("Program continues after exception handling");


}
}

How inter thread commuication works explain with program

Inter-thread communication in Java refers to the mechanism where threads


communicate with each other by signaling or notifying each other about the state
changes or sharing data. This is typically achieved using the wait(), notify(), and
notifyAll() methods provided by the Object class.

class SharedResource {
private int data;
private boolean newDataAvailable = false;

// Method to produce data


public synchronized void produce(int value) {
while (newDataAvailable) {
try {
// Wait until consumer consumes the previous data
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
data = value;
System.out.println("Produced: " + data);
newDataAvailable = true;
// Notify consumer that new data is available
notify();
}

// Method to consume data


public synchronized void consume() {
while (!newDataAvailable) {
try {
// Wait until producer produces new data
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Consumed: " + data);
newDataAvailable = false;
// Notify producer that data has been consumed
notify();
}
}

class Producer extends Thread {


private SharedResource sharedResource;

public Producer(SharedResource sharedResource) {


this.sharedResource = sharedResource;
}

public void run() {


for (int i = 1; i <= 5; i++) {
sharedResource.produce(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

class Consumer extends Thread {


private SharedResource sharedResource;

public Consumer(SharedResource sharedResource) {


this.sharedResource = sharedResource;
}
public void run() {
for (int i = 1; i <= 5; i++) {
sharedResource.consume();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

public class InterThreadCommunicationExample {


public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
Producer producer = new Producer(sharedResource);
Consumer consumer = new Consumer(sharedResource);

producer.start();
consumer.start();
}
}

You might also like