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.

class Example 
{
    public static void main(String[] args) 
    {
        String firstName = "Bob";
        String lastName = "Jones";
        System.out.println(firstName);
        System.out.println(lastName);
    }
}

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.

class Example
{
    static String firstName;
    static String lastName;
 
    public static void main(String[] args)
    {
        firstName = "Bob";
        lastName = "Jones";
        System.out.println(firstName);
        System.out.println(lastName);
    }
}

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.

import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.*;

public class CodingRoomsUnitTests {

    @Test
    public void testDefaultCase() {
        Example.main(null);
        assertEquals(Example.firstName, "Bob");
        assertEquals(Example.lastName, "Jones");
    }
}

Last updated