✅ Topics Covered:
Class and main() method
Variables and data types
Input/output with Scanner
Control statements: if, switch
Loops: for, while
Arrays
Methods
Object-Oriented Programming (OOP): classes, objects
Inheritance
Exception handling
Collections (ArrayList)
import java.util.*;
// Base class
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void introduce() {
System.out.println("Hi, I'm " + name + ", age " + age);
}
}
// Derived class (Inheritance)
class Student extends Person {
int grade;
Student(String name, int age, int grade) {
super(name, age);
this.grade = grade;
}
@Override
void introduce() {
super.introduce();
System.out.println("I'm a student in grade " + grade);
}
}
public class Main {
// Method to sum an array
static int sumArray(int[] arr) {
int sum = 0;
for (int num : arr) sum += num;
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Basic input/output
System.out.print("Enter your name: ");
String user = sc.nextLine();
System.out.println("Hello, " + user);
// Conditional statements
int x = 10, y = 20;
if (x < y) System.out.println(x + " is less than " + y);
// Switch case
int choice = 2;
switch (choice) {
case 1 -> System.out.println("Choice is 1");
case 2 -> System.out.println("Choice is 2");
default -> System.out.println("Unknown");
}
// Loops and arrays
int[] nums = {1, 2, 3, 4, 5};
System.out.print("Array: ");
for (int n : nums) System.out.print(n + " ");
System.out.println("\nSum = " + sumArray(nums));
// While loop
int i = 0;
while (i < 3) {
System.out.println("i = " + i);
i++;
}
// Object creation and inheritance
Student s1 = new Student("Alice", 16, 10);
s1.introduce();
// Exception handling
try {
int res = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
// Collections
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println("Fruits: " + fruits);
sc.close();
}
}
| Lines | Concepts |
| ----- | ------------------------------------------------------------ |
| 1–8 | Classes, constructors |
| 9–15 | Inheritance, method overriding |
| 17–71 | Main logic: I/O, arrays, loops, OOP, exceptions, collections |
🛠 How to Run:
Save the file as Main.java.
Compile: javac Main.java
Run: java Main