- Java Fields
- Field Declaration Syntax
- Java Field Access Modifiers
- Static and Non-static Fields
- Final Fields
- Naming Java Fields
- Initial Field Value
- Class Field and Instance Field in Java
- the Local Variable in Java
- the Input Parameter in Java
- the Class Field in Java
- the Properties of Class Field in Java
- the Instance Field in Java
- the Properties of Instance Field in Java
Java Fields
A Java field is a variable inside a class. For instance, in a class representing an employee, the Employee class might contain the following fields:
The corresponding Java class could be defined like this:
Field Declaration Syntax
A Java field is declared using the following syntax:
[access_modifier] [static] [final] type name [= initial value] ;
The square brackets [ ] around some of the keywords mean that this option is optional. Only type and name are required.
First an access modifier can be declared for a Java field. The access modifier determines which object classes that can access the field. In the Employee example above there were no access modifiers.
Second, a data type for the Java field must be assigned. In the Employee example above the data types String , int and Date were used.
Third, the Java field can be declared static . In Java, static fields belongs to the class, not instances of the class. Thus, all instances of any class will access the same static field variable. A non-static field value can be different for every object (instance) of a class.
Fourth, the Java field can be declared final or not. A final field cannot have its value changed. A final field must have an initial value assigned to it, and once set, the value cannot be changed again. A final field is often also declared static . A field declared static and final is also called a «constant».
Fifth, the Java field is given a name. You can choose this name freely, but there are some restrictions on what characters the name can contain.
Sixth, you can optionally set an initial value for the field.
Some of the above options are described in more detail in the following sections.
Java Field Access Modifiers
The Java field access modifier determines whether the field can be accessed by classes other than the the class owning the field. There are four possible access modifiers for Java fields:
The private access modifier means that only code inside the class itself can access this Java field.
The package access modifier means that only code inside the class itself, or other classes in the same package, can access the field. You don’t actually write the package modifier. By leaving out any access modifier, the access modifier defaults to package scope.
The protected access modifier is like the package modifier, except subclasses of the class can also access the field, even if the subclass is not located in the same package.
The public access modifier means that the field can be accessed by all classes in your application.
Here are a few examples of fields declared with access modifiers. The modifiers are in bold.
The above use of Java field access modifiers are for the sake of this example only. You would probably not use all access modifiers in the same class. Most often you use private and protected . For simple, data carrying classes you may declare all fields public .
The Java access modifiers are covered in more detail in my Java access modifiers tutorial.
Static and Non-static Fields
A Java field can be static or non-static.
A static field belongs to the class. Thus, no matter how many objects you create of that class, there will only exist one field located in the class, and the value of that field is the same, no matter from which object it is accessed. Here is a diagram illustrating static fields:
Static Java fields are located in the class, not in the instances of the class. |
You define a static field by using the static keyword in the field declaration, like this:
Static fields are located in the class, so you don’t need an instance of the class to access static fields. You just write the class name in front, like this:
Customer.staticField1 = "value"; System.out.println(Customer.staticField1);
Non-static Java fields, on the other hand, are located in the instances of the class. Each instance of the class can have its own values for these fields. Here is a diagram illustrating non-static fields:
Non-static Java fields are located in the instances of the class. |
You define a non-static Java field simply by leaving out the static keyword. Here is an example:
To access a non-static field you need an instance of the class (an object) on which you can access it. Here is an example:
Customer customer = new Customer(); customer.field1 = "value"; System.out.println(customer.field1);
Final Fields
A Java field can be declared final . A final field cannot have its value changed, once assigned. You declare a field to be final by adding the final keyword to the field declaration. Here is an example:
The value of the field1 field cannot be changed now. That means, that even if the field belongs to objects (class instances), you cannot vary the value of the field from object to object.
When you cannot change the value of a final field anyways, in many cases it makes sense to also declare it static . That way it only exists in the class, not in every object too. Here is an example:
Since static final fields are often used as constants, the naming convention is to write the field name in all uppercase, and to separate the words with underscore _ . Here is a Java static final field example:
Naming Java Fields
The name of a Java field is used to refer to that field from your code. Here is an example:
Customer customer = new Customer(); customer.city = "New York"; System.out.println(customer.city);
The first line creates a new Customer object (an instance of the Customer class), and stores it in a variable called customer . The second line assigns the String value New York to the Customer objects city field. The third line prints out the value of the city field to the console output.
The naming restrictions and naming conventions for fields are the same as for any other type of variable.
Initial Field Value
A Java field can have be given an initial value. This value is assigned to the field when the field is created in the JVM. Static fields are created when the class is loaded. A class is loaded the first time it is referenced in your program. Non-static fields are created when the object owning them are created.
Here is an example of a Java field being declared with an initial value:
Whether you want to initialize your Java fields (and other variables) to an initial value is up to you. I have made it a habit to always initialize my variables to some sensible value, but it is just a habit. It is not necessary to do so.
Class Field and Instance Field in Java
- the Local Variable in Java
- the Input Parameter in Java
- the Class Field in Java
- the Properties of Class Field in Java
- the Instance Field in Java
- the Properties of 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); > >
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(); > >
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.
- 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(); > >
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(x18) 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); > >
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); > >
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:
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); > >
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()); > >
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
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.
Copyright © 2023. All right reserved