Class Field and Instance Field in Java

Shikha Chaudhary Feb 17, 2022
  1. the Local Variable in Java
  2. the Input Parameter in Java
  3. the Class Field in Java
  4. the Properties of Class Field in Java
  5. the Instance Field in Java
  6. the Properties of Instance Field in Java
Class Field and Instance Field in Java

This article will learn basic terms of Java programming language like local variables, input parameters, class fields, and instance fields in Java.

the Local Variable in Java

A variable whose scope is bound to the block, method, or constructor is called a local variable. Say, we have a method, testing.

We declare a val variable and assign 10 to this method. Write the print statement inside the main block.

public class Experiment{

    public static void testing()
    {
       int val = 10;
    }

    public static void main(String[] args)
    {
      //try printing the local variable of the function demo
      System.out.printf("%d", val);
    }
}

Output:

error: cannot find symbol
      System.out.printf("%d", val);
                              ^
  symbol:   variable val
  location: class Experiment
1 error

Although the variable val is present in this code, we get an error. Here, the variable val is a local variable to the testing() method.

Since it is defined inside the method testing, its scope is limited. We get an error when the print statement tries to access this variable outside of this scope.

Now, declare the print statement inside the method testing and call the method from the main block.

public class Experiment{

    public static void testing()
    {
       int val = 10;
       System.out.printf("%d", val);
    }

    public static void main(String[] args)
    {
      //call the method
      testing();
    }
}

Output:

10

This time, the print statement is accessing the variable from within its scope.

Now try to figure out the local variable in this code.

public class Treat{

    public static void main(String[] args)
    {
      for(int i = 0, i< 1; i++){
          System.out.println("You will get a Cake if you answer correctly!");
      }
    }
}

The variable i is a local variable. Its scope is limited to the for loop.

Note the following points about local variables:

  • We cannot use access modifiers like public, protected, and private to declare local variables.
  • These variables get implemented internally at the stack level.

the Input Parameter in Java

Some information needs to execute while others may not. Look at this method welcome.

public class Greet{
     //a function that does not need any parameter or information
     public static void welcome()
     {
          System.out.println("Hello, we are happy you visited.");
     }
     public static void main(String[] args)
     {
          //call the function
          welcome();
     }
}

Output:

Hello, we are happy you visited.

We call the method without passing any values in it. We do not give any information to this method, and it executes properly.

public class Test{
     //a function that needs some information/parameter
     public static void hello(int x)
     {
          int a;
          System.out.println("Hello, we are happy you visited.");
          if(x<18){
          a = 18 - x;
          System.out.printf("Please come back after %d years.", a);
          }

     }
     public static void main(String[] args)
     {
          int age = 2;
          
          //call the function
          hello(age);
     }
}

Output:

Hello, we are happy you visited.
Please come back after 16 years.

The method hello will not properly execute if we do not pass a value for age.

The method receives this value through the variable x defined inside the parenthesis. The variable x is nothing but an input parameter or, simply, a parameter.

An input parameter or a parameter in Java is a variable used to define a method to help the method run.

Do not mix parameters with arguments. They have the same value, but they are not the same thing.

public class Test{

     //function to add ages
     public static int totalAge(int age1, int age2)
     {
         return age1 + age2;
     }
     public static void main(String[] args)
     {
         int a1 = 10;
         int a2 = 12;

         int total = totalAge(a1,a2);
         System.out.println("Sum of ages: " + total);
     }
    
}

Output:

Sum of ages: 22

Here, age1 and age2 are the input parameters.

the Class Field in Java

Any variable inside a class can be referred to as a field in Java. All the variables like price, quantity, and name are fields.

However, note that the variable quantity starts with the static keyword. Such fields with the keyword static in their definition are called class fields in Java.

Class fields are also referred to as class variables or static fields in Java.

class Cake{
     int price;
     static int quantity;
     string name;
}

the Properties of Class Field in Java

The following points are a class field:

  • A class field must be declared with the static keyword.
public static NameOfClass{
    static datatype name_of_variable;
}
  • Many instances of a class share the class field, and thus class fields are memory efficient. In very simple words, the value of an instance field is the same for all the instances of a class in Java.
  • We can access a class field in Java using an instance of the class and the class name itself. Note that an instance is not necessarily needed to access any static field.
 class Cake{

     int price;
     static int quantity = 10;
     String name;

     public static void main(String[] args){

         //create the object of Cake class
         Cake c1 = new Cake();

         //Access the class field using the object
         System.out.println(c1.quantity);

         //Access the class field using the class
         System.out.println(Cake.quantity);
     }
}

Output:

10
10

In the above example, we access the class field using an object using the dot operator like this - c1.quantity. Similarly, to access the variable by class, use the class name Cake.quantity.

the Instance Field in Java

public class Cake{
    int cost;
    String flavor;

    public Cake(int cost, String flavor)
    {
         this.cost = cost;
         this.flavor = flavor;
    }

    public int expense()
    {
         return cost;

    }

    public static void main(String[] args){

        Cake cake1 = new Cake(1000,"Choco lava");
        Cake cake2 = new Cake(2000,"Pineapple");

        System.out.println(cake1.expense());
        System.out.println(cake2.expense());
    }
}

Output:

1000
2000

Inside the class Cake, we have two variables - cost and flavor. We create cake1 and cake2.

These variables that can take different values for different objects are called instance variables or instance fields.

the Properties of Instance Field in Java

The instance fields in java are also called non-static variables. Here are a few points about instance fields.

  • Instance Fields are not declared with Java’s static keyword.
public class ClassName{
     datatype variable_name;
}
  • They are not shared with all the instances. Each instance can have its unique value for an instance field in Java.
  • You saw how we could access a class field with the help of the class itself. Well, this is not true for an instance field in Java. We need an instance/object to access an instance field in Java.
  • We can use any access specifier with an instance field in Java. Refer to this documentation to know more about fields in Java.