java-old
java-old
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);
@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();
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;
// Subclass
class Dog extends Animal {
String breed;
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.");
}
}
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.");
}
}
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.
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
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.
1. Marker Interface:
o Used to signal to the JVM or other tools that the class implementing the interface has some special
property.
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. }
o Similar to functional interfaces, but the term is often used for pre-Java 8 interfaces that have a single abstract method.
Java
o Can also contain default and static methods (since Java 8).
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.
import java.io.*;
try {
} catch (FileNotFoundException e) {
o Usually occur due to programming errors such as logic errors or incorrect assumptions.
Java
3. Errors:
Java
try {
recursiveMethod();
} catch (StackOverflowError e) {
1. try-catch Block:
o Syntax:
Java
try {
} catch (ExceptionType e) {
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 {
} catch (ExceptionType e) {
} finally {
3. throw Keyword:
o Used to explicitly throw an exception.
o Syntax:
Java
} else {
4. throws Keyword:
o Used in method signatures to declare that a method can throw one or more exceptions.
o Syntax:
Java
Java
import java.io.*;
try {
readFile("nonexistentfile.txt");
} catch (IOException e) {
} finally {
System.out.println("Execution completed.");
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.
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.*;
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.*;
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.*;
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.*;
frame.add(checkBox1);
frame.add(checkBox2);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}