Check Variable Values
Checking variable values can be a bit tricky in Java. For example, it can be hard to check the following variable values.
1
class Example
2
{
3
public static void main(String[] args)
4
{
5
String firstName = "Bob";
6
String lastName = "Jones";
7
System.out.println(firstName);
8
System.out.println(lastName);
9
}
10
}
Copied!
This is because firstName and lastName are local to the main() method and created when it is executed and destroyed when it is done.
We can prevent this by declaring these variables as static outside the main() method.
1
class Example
2
{
3
static String firstName;
4
static String lastName;
5
6
public static void main(String[] args)
7
{
8
firstName = "Bob";
9
lastName = "Jones";
10
System.out.println(firstName);
11
System.out.println(lastName);
12
}
13
}
Copied!
We typically do not teach students to declare variables this way (most curriculums do not) so you may need to tweak your curriculum to auto-grade early assignments that teacher variable assignment and console output.
The grading test involves calling the main method (where you expect the variables to be assigned values and checking that each variable equals the expected value.
1
import org.junit.Before;
2
import org.junit.After;
3
import org.junit.Test;
4
import static org.junit.Assert.*;
5
​
6
public class CodingRoomsUnitTests {
7
​
8
@Test
9
public void testDefaultCase() {
10
Example.main(null);
11
assertEquals(Example.firstName, "Bob");
12
assertEquals(Example.lastName, "Jones");
13
}
14
}
Copied!
​
​
Last modified 2mo ago
Export as PDF
Copy link