Class fields and instance fields in Java
In this article, you will learn the basic terminology of Java programming language such as local variables, input parameters, class fields, and instance fields in Java.
Local variables in Java
Variables whose scope is bound to a block, method or constructor are called local variables. For example, we have a method, testing.
We declare a valvariable and 10assign to this method. mainInside the block write printthe statement.
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 there is a variable in this code val, we get an error. Here, the variable valis testing()a local variable of the method.
Since it is testingdefined inside the method , its scope is limited. When printthe statement tries to access this variable outside this scope, we get an error.
Now, testingdeclare printthe statement in the method and maincall the method from the 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, printthe statement accesses the variable from within its scope.
Now try to find out the local variables 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 iis a local variable. Its scope is limited to forthe loop.
Note the following points about local variables:
-
We cannot declare local variables using access modifiers such as
public, ,protectedand .private - These variables are implemented internally at the stack level.
Input parameters in Java
Some information is required for execution, while other information may not be. Take a 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 this method without passing any value. We don't provide any information to this method and it executes normally.
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.
If we don't pass agea value for , the method hellowill not execute correctly.
xThe method receives this value
through the variable defined inside the brackets . The variable xis nothing but an input parameter, or in simple terms, a parameter.
Input parameters or arguments in Java are variables used to define a method to help the method run.
Don't 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, age1and age2are input parameters.
Class fields in Java
Any variable in a class can be called in Java 字段. All variables like price, , quantityand are fields.name
However, notice that the variable begins quantitywith staticthe keyword. Such fields with the keyword in the definition staticare called class fields in Java.
类Class fields are also called variables or
in Java 静态字段.
class Cake {
int price;
static int quantity;
string name;
}
Attributes of class fields in Java
The following points are fields of a class:
staticClass fields must be declared with the keyword.
public static NameOfClass {
static datatype name_of_variable;
}
- Many instances of a class share class fields, so class fields are memory efficient. In very simple words, the value of an instance field is the same for all instances of a class in Java.
- We can access class fields in Java using both the instance of the class and the class name itself. Note that an instance is not necessarily required 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 have used dotthe operator like this - c1.quantityto access the class field using the object. Similarly, to access a variable by class, use the class name Cake.quantity.
Instance fields 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
In the class Cake, we have two variables - costand flavor. We create cake1and cake2.
These variables that can take different values for different objects are called 实例变量or 实例字段.
Instance FieldProperties
in Java
Instance fields in java are also called non-static variables. Following are a few points about instance fields.
staticInstance fields are not declared using the Java keyword.
public class ClassName {
datatype variable_name;
}
- They are not shared with all instances. In Java, each instance can have its own unique instance field values.
-
You saw how we can access class fields with the help of the class itself. Well, this is not true for instance fields in Java. We need a
instance/objectto access instance fields in Java. - We can use any access specifier with instance fields in Java.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Class file editor in Java
Publish Date:2025/04/14 Views:156 Category:Java
-
In this article, we will discuss Java Class File Editor, a tool created in Java to edit Java compiled classes. We can decompile Java classes after creating them and view them, but we need a tool like Java Class File Editor to modify them. F
How to clear the console in Java
Publish Date:2025/04/14 Views:170 Category:Java
-
In this tutorial, we will look at two ways to clear the console screen in Java. We will learn how to execute Java clear screen commands at runtime through examples. Clearing the console using ANSI escape codes in Java We can use special cod
console.log in Java
Publish Date:2025/04/14 Views:195 Category:Java
-
This tutorial explains the function in Java console.log() and how to display logs to the console in Java. console.log() is a function in JavaScript that is used to display log messages to the browser console. There is no such message in Jav
Java Change Date Format
Publish Date:2025/04/14 Views:65 Category:Java
-
There are various options available for converting date string to date format. The methods mentioned below can bring the desired result. Let us understand the various ways from the following code block. import java.text.ParseException ; imp
Calendar date in YYYY-MM-DD format in Java
Publish Date:2025/04/14 Views:72 Category:Java
-
Java Date encapsulates the current time and date. The Date class does this with the help of two constructors - Date() and Date(long millisec) constructor. We use Date() the constructor to initialize the object with the current time and date
Implementing a min-max heap in Java
Publish Date:2025/04/14 Views:53 Category:Java
-
In this article, we will implement a max heap and a min heap using PriorityQueue the class. We will also demonstrate inserting and removing elements from the heap. Introduction to Min-Max Heap in Java Heap is a tree-based data structure, wh
Implementing a Min Heap in Java
Publish Date:2025/04/14 Views:197 Category:Java
-
A min heap is a heap in which every internal node is less than or equal to the value of its child nodes. We will see in the following points how to implement a min heap with and without using a library. Minimal heap implementation in Java w
Increasing the heap space in Java
Publish Date:2025/04/14 Views:190 Category:Java
-
In Java, the heap space is mainly used for garbage collection and allocating memory for objects. A default heap space is allocated when JVM is installed on our machine, but it may be different. The following points show how we can increase
Detecting EOF in Java
Publish Date:2025/04/14 Views:91 Category:Java
-
In this tutorial, we will see how to while detect EOF( End OF File ) in Java using a loop. We will also discuss developing a program that continues reading content until it reaches the end of a file. From a programming perspective, EOF is a

