Java Assignment Solutions
1. Object and Class in Java
A class in Java is a template for creating objects. It defines fields (attributes) and methods (behaviors). An object is an
instance of a class that holds data and can perform actions.
Example:
class Student {
String name;
int age;
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "John";
s1.age = 20;
s1.display();
}
}
2. Multi-threading in Java
Multithreading allows multiple tasks to run concurrently, improving performance. Java provides the Thread class and
Runnable interface.
Example using Runnable:
class MyTask implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task: " + i);
}
}
}
public class MultiThread {
public static void main(String[] args) {
Thread t1 = new Thread(new MyTask());
t1.start();
}
}
3. Java Program to Find Indexes of 'a' in "Java"
public class FindIndexes {
public static void main(String[] args) {
String str = "Java";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a') {
System.out.print(i + " ");
}
}
}
}
4. Code Reusability and Maintainability in Java
Java achieves code reusability through:
- **Encapsulation**: Hides data and allows controlled access.
- **Inheritance**: A child class inherits methods from a parent class.
- **Polymorphism**: Enables different implementations of the same method.
Example (Inheritance):
class Animal {
void sound() { System.out.println("Animal makes a sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
5. Arrays, ArrayList, LinkedList, and Vector
- **Array**: A fixed-size collection of elements.
int[] arr = {1, 2, 3};
- **ArrayList**: A resizable array.
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
- **LinkedList**: Uses nodes for fast insertions and deletions.
LinkedList<String> list = new LinkedList<>();
list.add("Hello");
- **Vector**: Like ArrayList but synchronized.
Vector<String> vec = new Vector<>();
vec.add("World");
6. Garbage Collection
Garbage Collection in Java removes unused objects automatically to free memory.
Example:
class Demo {
protected void finalize() { System.out.println("Garbage Collected"); }
}
public class GCExample {
public static void main(String[] args) {
Demo d1 = new Demo();
d1 = null;
System.gc();
}
}