Assignment 1
Assignment 1
Code snippets
01 error : Missing semicolon
The line
System.out.println("Hello world!")
is missing a semicolon ( ; )
Corrected code
Explanation: In Java, every statement must end with a semicolon (;). This tells the
compiler that the statement is complete. Without it, the code will not compile.
Corrected code
Assignment 1
Main main = new Main();
main.greet();
}
}
Explanation: In Java, method calls like greet(); must be placed inside a method
(such as main()), a constructor, or a block of code. Since greet() is a non-static
method, you need to create an instance of the Main class to call it.
Corrected code
Explanation: In Java, the int data type can only store integer values. A string
(enclosed in double quotes) cannot be directly assigned to an integer variable.
Corrected code
Assignment 2
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
// Accessing a valid index
System.out.println("The fourth element is: " + numbers[3
}
}
Corrected code
Assignment 3
06 error : Variable age Might Not Have Been Initialized
The variable age is declared but not initialized before being used in the if
condition.
Corrected code
Explanation: In Java, local variables (like age inside main) must be initialized
before use. Declaring int age; without assigning a value results in a compilation
error when it’s used in the if condition.
Corrected code
Assignment 4
i++; // Increment `i` outside the loop
System.out.println("Outside loop: " + i);
}
}
Explanation: When i is declared in the for loop (for (int i = 0; ...)), its scope is
limited to the loop block. To use i outside the loop, declare it before the loop.
Corrected code
Explanation: In Java, all variables must be declared and initialized before they are
used. Adding int count = 0; ensures that the program knows what count is and
starts from a valid initial value.
Assignment 5