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

java-old

PPU question

Uploaded by

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

java-old

PPU question

Uploaded by

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

Q1. What is Abstract Class?

Write a program to define arithmetic abstract class to perform arithmetic operation

An abstract class in programming is a class that cannot be instantiated on its own and is meant to be subclassed. It can
contain both abstract methods (without implementation) and concrete methods (with implementation). Abstract classes
are used to provide a common interface and some common functionality for its subclasses.
// Define the abstract class
abstract class Arithmetic {
// Abstract method for addition
abstract int add(int a, int b);

// Abstract method for subtraction


abstract int subtract(int a, int b);

// Abstract method for multiplication


abstract int multiply(int a, int b);

// Abstract method for division


abstract int divide(int a, int b);
}
// Subclass that provides implementation for the abstract methods
class BasicArithmetic extends Arithmetic {
@Override
int add(int a, int b) {
return a + b;
}

@Override
int subtract(int a, int b) {
return a - b;
}

@Override
int multiply(int a, int b) {
return a * b;
}

@Override
int divide(int a, int b) {
if (b != 0) {
return a / b;
} else {
throw new ArithmeticException("Division by zero is not allowed.");
}
}
}
// Main class to test the arithmetic operations
public class Main {
public static void main(String[] args) {
BasicArithmetic arithmetic = new BasicArithmetic();

System.out.println("Addition: " + arithmetic.add(10, 5));


System.out.println("Subtraction: " + arithmetic.subtract(10, 5));
System.out.println("Multiplication: " + arithmetic.multiply(10, 5));
System.out.println("Division: " + arithmetic.divide(10, 5));
}
}
Q2. What is constructor? How super keyword inherits the constructor in subclass?

A constructor in programming is a special method used to initialize objects. It is called when an instance of a class is
created. Constructors have the same name as the class and do not have a return type. They can be used to set initial values
for object attributes or perform any setup steps required when an object is created.

The super keyword in Java is used to refer to the immediate parent class object. It can be used to call methods and access
variables from the parent class. When it comes to constructors, the super() keyword is used to call the constructor of the
parent class from the subclass. This ensures that the parent class is properly initialized before the subclass adds its own
initialization.

Here’s an example to illustrate how the super keyword is used to inherit the constructor in a subclass:
// Parent class
class Animal {
String name;

// Constructor of the parent class


Animal(String name) {
this.name = name;
System.out.println("Animal is created: " + name);
}
}

// Subclass
class Dog extends Animal {
String breed;

// Constructor of the subclass


Dog(String name, String breed) {
// Call the constructor of the parent class
super(name);
this.breed = breed;
System.out.println("Dog is created: " + name + ", Breed: " + breed);
}
}

// Main class to test the constructors


public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", "Golden Retriever");
}
}
In this example:
 The Animal class has a constructor that initializes the name attribute.
 The Dog class extends Animal and has its own constructor that initializes
both name and breed.
 The super(name) call in the Dog constructor invokes the Animal constructor,
ensuring that the name attribute is properly initialized before
the Dog constructor adds its own initialization for the breed attribute12.
Q3. What is final keyword? Write use of final keyword with suitable exapmel

The final keyword in Java is a non-access modifier used to restrict the user from modifying the value of a variable, overriding
a method, or inheriting a class. It can be applied to variables, methods, and classes.

Here are the uses of the final keyword with suitable examples:

1. Final Variable: A variable declared as final cannot be changed once it is initialized. It essentially becomes a constant.
2. public class Main {
3. public static void main(String[] args) {
4. final int MAX_VALUE = 100;
5. // MAX_VALUE = 200; // This will cause a compile-time error
6. System.out.println("Max Value: " + MAX_VALUE);
7. }
8. }
9.
Final Method: A method declared as final cannot be overridden by subclasses. This is useful when you want to prevent
altering the behavior of a method in derived classes.
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}

class Child extends Parent {


// void display() { // This will cause a compile-time error
// System.out.println("Trying to override.");
// }
}

public class Main {


public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}

Final Class: A class declared as final cannot be subclassed. This is useful when you want to prevent inheritance.
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}

// class SubClass extends FinalClass { // This will cause a compile-time error


// }

public class Main {


public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display();
}
}
Using the final keyword helps in maintaining the integrity of your code by preventing unintended modifications
Q4. Explain polymorphism and types with suitable example

Polymorphism is a core concept in object-oriented programming that allows objects to be treated as instances of their
parent class rather than their actual class. It enables a single interface to represent different underlying forms (data types).
Polymorphism enhances flexibility and maintainability in code by allowing the same operation to behave differently on
different classes.

There are two main types of polymorphism in Java:

1. Compile-time Polymorphism (Static Polymorphism):

o Achieved through method overloading.

o The method to be invoked is determined at compile time.

o Example:
2. class MathOperations {
3. // Method overloading
4. int add(int a, int b) {
5. return a + b;
6. }
7.
8. int add(int a, int b, int c) {
9. return a + b + c;
10. }
11. }
12.
13. public class Main {
14. public static void main(String[] args) {
15. MathOperations math = new MathOperations();
16. System.out.println("Sum of 2 numbers: " + math.add(5, 10));
17. System.out.println("Sum of 3 numbers: " + math.add(5, 10, 15));
18. }
19. }
In this example, the add method is overloaded with different parameter lists. The appropriate method is chosen at compile
time based on the number of arguments passed

Runtime Polymorphism (Dynamic Polymorphism):

 Achieved through method overriding.

 The method to be invoked is determined at runtime.

 Example:

 class Animal {
 void makeSound() {
 System.out.println("Animal makes a sound");
 }
 }

 class Dog extends Animal {
 @Override
 void makeSound() {
 System.out.println("Dog barks");
 }
 }

 class Cat extends Animal {
 @Override
 void makeSound() {
 System.out.println("Cat meows");
 }
 }

 public class Main {
 public static void main(String[] args) {
 Animal myAnimal;

 myAnimal = new Dog();
 myAnimal.makeSound(); // Outputs: Dog barks

 myAnimal = new Cat();
 myAnimal.makeSound(); // Outputs: Cat meows
 }
 }

In this example, the makeSound method is overridden in the Dog and Cat classes. The method that gets called is determined
at runtime based on the actual object type.
Q5. What is interface? Write types of interface with structure

An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default
methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. They are used to
specify a set of methods that a class must implement, providing a way to achieve abstraction and multiple inheritance in
Java.

Types of Interfaces in Java

1. Marker Interface:

o An interface with no methods or fields.

o Used to signal to the JVM or other tools that the class implementing the interface has some special
property.

o Example: Serializable, Cloneable.


public interface MarkerInterface {
// No methods or fields
}
1. Functional Interface:

o An interface with exactly one abstract method.

o Can contain any number of default or static methods.

o Used primarily for lambda expressions and method references.

o Example: Runnable, Callable.

2. @FunctionalInterface
3. public interface FunctionalInterfaceExample {
4. void abstractMethod();
5.
6. default void defaultMethod() {
7. System.out.println("This is a default method.");
8. }
9.
10. static void staticMethod() {
11. System.out.println("This is a static method.");
12. }
13. }
14. }

15. Single Abstract Method (SAM) Interface:

o Similar to functional interfaces, but the term is often used for pre-Java 8 interfaces that have a single abstract method.

o Example: Comparator, ActionListener.

Java

public interface SAMInterface {


void singleAbstractMethod();
}
1. Normal Interface:

o An interface with one or more abstract methods.

o Can also contain default and static methods (since Java 8).

o Example: List, Set.

2. public interface NormalInterface {


3. void method1();
4. void method2();
5.
6. default void defaultMethod() {
7. System.out.println("This is a default method.");
8. }
9.
10. static void staticMethod() {
11. System.out.println("This is a static method.");
12. }
13. }

14. Example usage


// Define the interface
interface Animal {
void makeSound();

default void sleep() {


System.out.println("Sleeping...");
}
}

// Implement the interface in a class


class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}

// Main class to test the interface


public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound(); // Outputs: Bark
dog.sleep(); // Outputs: Sleeping...
}
}
Q6. What is exception? Discuss types of exception handling and methods of exception.

An exception in Java is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
Exceptions can be caused by various issues such as invalid user input, file not found, division by zero, etc. When an
exception occurs, it is represented by an object of a subclass of the java.lang.Exception class.

Types of Exceptions

1. Checked Exceptions:

o Checked at compile-time.

o The compiler ensures that these exceptions are either caught or declared in the method signature using
the throws keyword.

o Examples: IOException, SQLException, ClassNotFoundException.


Java

import java.io.*;

public class CheckedExceptionExample {

public static void main(String[] args) {

try {

FileReader file = new FileReader("nonexistentfile.txt");

} catch (FileNotFoundException e) {

System.out.println("File not found!");

AI-generated code. Review and use carefully. More info on FAQ.

2. Unchecked Exceptions (Runtime Exceptions):

o Not checked at compile-time.

o Usually occur due to programming errors such as logic errors or incorrect assumptions.

o Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.

Java

public class UncheckedExceptionExample {

public static void main(String[] args) {

int[] numbers = {1, 2, 3};

System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException

AI-generated code. Review and use carefully. More info on FAQ.

3. Errors:

o Serious issues that a reasonable application should not try to catch.

o Typically indicate problems with the JVM or hardware.


o Examples: OutOfMemoryError, StackOverflowError.

Java

public class ErrorExample {

public static void main(String[] args) {

try {

recursiveMethod();

} catch (StackOverflowError e) {

System.out.println("Stack overflow error!");

public static void recursiveMethod() {

recursiveMethod(); // This will eventually throw StackOverflowError

AI-generated code. Review and use carefully. More info on FAQ.

Exception Handling Methods

1. try-catch Block:

o Used to catch exceptions and handle them gracefully.

o Syntax:

Java

try {

// Code that may throw an exception

} catch (ExceptionType e) {

// Code to handle the exception

2. finally Block:

o Used to execute important code such as closing resources, regardless of whether an exception is thrown or not.

o Syntax:

Java

try {

// Code that may throw an exception

} catch (ExceptionType e) {

// Code to handle the exception

} finally {

// Code to be executed regardless of an exception

3. throw Keyword:
o Used to explicitly throw an exception.

o Syntax:

Java

public void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least 18 years old.");

} else {

System.out.println("Access granted - You are old enough!");

4. throws Keyword:

o Used in method signatures to declare that a method can throw one or more exceptions.

o Syntax:

Java

public void readFile(String fileName) throws IOException {

FileReader file = new FileReader(fileName);

Example of Exception Handling

Here’s a comprehensive example demonstrating various exception handling techniques:

Java

import java.io.*;

public class ExceptionHandlingExample {

public static void main(String[] args) {

try {

readFile("nonexistentfile.txt");

} catch (IOException e) {

System.out.println("Caught IOException: " + e.getMessage());

} finally {

System.out.println("Execution completed.");

public static void readFile(String fileName) throws IOException {

FileReader file = new FileReader(fileName);

BufferedReader reader = new BufferedReader(file);

System.out.println(reader.readLine());

reader.close();

}}
Q7 . What is swing? Write any four swing controls with structure and example

Swing is a part of Java's Java Foundation Classes (JFC), which provides a set of lightweight, platform-
independent GUI (Graphical User Interface) components. Swing is used to create windows-based applications in
Java. It offers rich and flexible components like buttons, text fields, tables, and trees, which can be customized and
styled.

Swing is built on top of the Abstract Window Toolkit (AWT) and provides more advanced features. Unlike
AWT, Swing components are lightweight and written entirely in Java, making them platform-independent.

Four Swing Controls

1. JButton
o Structure: Used to create buttons in a GUI. A button can trigger an action when clicked.
o Example:

java
Copy code
import javax.swing.*;

public class JButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JButton Example");
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 100, 40);
frame.add(button);

frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}

2. JLabel
o Structure: Displays a short string or an image as a label. It is commonly used for titles, instructions,
or displaying static text.
o Example:

java
Copy code
import javax.swing.*;

public class JLabelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JLabel Example");
JLabel label = new JLabel("Hello, Swing!");
label.setBounds(50, 50, 150, 20);
frame.add(label);

frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

3. JTextField
o Structure: Allows the user to input text. It's often used in forms or applications requiring user input.
o Example:

java
Copy code
import javax.swing.*;

public class JTextFieldExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Example");
JTextField textField = new JTextField("Enter text here");
textField.setBounds(50, 50, 150, 20);
frame.add(textField);

frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

4. JCheckBox
o Structure: Represents a checkbox that can be selected or deselected. It's used to allow multiple
selections from a set of options.
o Example:

java
Copy code
import javax.swing.*;

public class JCheckBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JCheckBox Example");
JCheckBox checkBox1 = new JCheckBox("Option 1");
checkBox1.setBounds(50, 50, 100, 30);
JCheckBox checkBox2 = new JCheckBox("Option 2");
checkBox2.setBounds(50, 80, 100, 30);

frame.add(checkBox1);
frame.add(checkBox2);

frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

You might also like