Java
Version
Running Java on OpenJDK v21
Supported languages
Java
Testing framework
Special reminders and implementation details
package challenge;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
@DisplayName("Hello World")
public class HelloWorldTest {
@Test
@DisplayName("It should return 'Hello World!'")
public void testHelloWorld() {
assertEquals("Hello World!", HelloWorld.helloWorld());
}
}Included libraries
Reading input (stdin)
Programs that read values use standard input. Run opens an interactive terminal: the program starts, prints its prompt, and you type the answer and press Enter, as in a real terminal. The tests of an output-test challenge feed the input themselves.
package challenge;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int age = Integer.parseInt(scanner.nextLine().trim());
System.out.println("Hello, " + name + "! Next year you will be " + (age + 1) + ".");
}
}nextLine() throws NoSuchElementException at end-of-file. Do not print a prompt before reading in output-test challenges: it would become part of the compared output.
How to debug
Debugging Java code is essential for every developer. One of the simplest yet effective ways to debug is by using System.out.println() statements.
Steps to Debug Using System.out.println() Statements
Identify the Problem Area: Locate the section of your code where you suspect the problem might be.
Insert
System.out.println()Statements: AddSystem.out.println()statements before and after the suspected problematic code to print out variable values and flow control.Check the Results Output of your tests
Analyze the Output: Look at the values printed on the results console to understand what's going wrong in your code. Adjust your code based on the findings and repeat as necessary.
Here’s an example of how to use System.out.println() for debugging:
public class DebugExample {
public static int calculateSum(int a, int b) {
System.out.println("calculateSum called with arguments: " + a + ", " + b); // Log function call
int sum = a + b;
System.out.println("Sum after addition: " + sum); // Log sum calculation
return sum;
}
public static void main(String[] args) {
int result = calculateSum(5, 10);
System.out.println("Result of calculateSum: " + result); // Log the result
}
}