Solutions To 2022 Java
Solutions To 2022 Java
Questions
class Parent {
void display() {
System.out.println("This is the parent class.");
}
}
Q1c: Explain an array, how to declare it in Java, and compare C and Java
arrays.
Array: A data structure used to store multiple elements of the same type.
Declaration in Java: int[] arr = new int[5];
Comparison:
o Java arrays are objects and have built-in bounds checking, whereas C arrays are
raw memory blocks.
o Java arrays have a length property, while in C, you need to manage size
manually.
class Polymorphism {
int add(int a, int b) {
return a + b;
}
class Parent {
void show() {
System.out.println("Parent method.");
}
}
import java.util.Arrays;
interface Animal {
void sound();
}
Some examples:
// File: mypackage/MyClass.java
package mypackage;
// File: Test.java
import mypackage.MyClass;
java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}
java
Copy code
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running.");
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
Graphics Class: It is part of java.awt and provides methods to draw shapes, text, and images
on components.
Three Drawing Methods:
1. drawLine(int x1, int y1, int x2, int y2): Draws a line between two points.
2. drawRect(int x, int y, int width, int height): Draws a rectangle.
3. drawOval(int x, int y, int width, int height): Draws an oval within a
bounding rectangle.
import javax.swing.*;
import java.io.*;