Basic Syntax

Fields

🙋 Need help? Ask an expert now!

In Java, the "Fields" section of a class is used to house variables and to declare and initialize them to a value, if needed. A Java field is a variable inside a class. For instance, in the class below, we see four different variables:

FieldsExample.java
package exlcode;

public class FieldsExample {

  public static int exampleVariableOne = 5;
  public static int exampleVariableTwo = 10;
  public int exampleVariableThree;
  private int exampleVariableFour;

  public static void main(String[] args) {
    // this prints exampleVariableOne and exampleVariableTwo
    System.out.println(exampleVariableOne);
    System.out.println(exampleVariableTwo);
  }
}

There are multiple ways to declare a variable. We can either declare it or declare and initialize it with an initial value. Here are some examples:

  1. dataType variableName;

    We declared a variable and its data type but put nothing in the variable

  2. dataType variableName = initialValue;

    We declared a variable, its data type, and put an initial value into memory. The initial value must be of the correct data type.

  3. dataType variableNameOne, variableNameTwo;

    We declared two variables, both of the same data type, but put nothing in either variable. We can do this with more than two variables.

  4. dataType variableNameOne = initialValueOne, variableNameTwo = initialValueTwo;

    We declare two variables, both of the same data type, and put an initial value in each variable. Again, we can do this for more than two variables as long as we follow the same format.

You get to pick the name for each variable in the program. Various things in a program are given names. A name chosen by a programmer is called an "identifier". For example, in the code above, exampleVariableOne is an identifier.

Application Question

Which one of these choices below cause an error?