Java Variable Types
In Java, all variables must be declared before they can be used. The basic format for declaring variables is as follows:
type identifier [ = value][, identifier [= value] ...] ;
Format explanation: type
is the Java data type. identifier
is the variable name. Multiple variables of the same type can be declared using commas.
Here are some examples of variable declarations. Note that some include initialization.
int a, b, c; // Declares three ints: a, b, c
int d = 3, e = 4, f = 5; // Declares three ints and initializes them
byte z = 22; // Declares and initializes z
String s = "tutorialpro"; // Declares and initializes the string s
double pi = 3.14159; // Declares a double variable pi
char x = 'x'; // Declares a variable x with the value 'x'
Java supports the following variable types:
Class variables: Variables declared outside methods, using the
static
modifier.Instance variables: Variables declared outside methods, but without the
static
modifier.Local variables: Variables declared within a method of a class.
Example
public class Variable{
static int allClicks=0; // Class variable
String str="hello world"; // Instance variable
public void method(){
int i =0; // Local variable
}
}
Java Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor, or block is entered and destroyed once it exits.
Access modifiers cannot be used for local variables.
Local variables are only visible within the declared method, constructor, or block.
Local variables are allocated on the stack.
Local variables do not have default values, so they must be initialized before use.
Example 1
In the following example, age
is a local variable. It is defined within the pupAge()
method and its scope is limited to this method.
package com.tutorialpro.test;
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy's age is: " + age);
}
public static void main(String[] args){
Test test = new Test();
test.pupAge();
}
}
The compilation and running result of the above example is:
Puppy's age is: 7
Example 2
In the following example, the age
variable is not initialized, so it will cause a compilation error:
package com.tutorialpro.test;
public class Test{
public void pupAge(){
int age;
age = age + 7;
System.out.println("Puppy's age is : " + age);
}
public static void main(String[] args){
Test test = new Test();
test.pupAge();
}
}
The compilation and running result of the above example is:
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
Instance Variables
Instance variables are declared in a class, but outside methods, constructors, and blocks.
When an object is instantiated, the values of each instance variable are determined.
Instance variables are created when an object is created with the use of the
new
keyword and destroyed when the object is destroyed.Instance variables must be referenced by at least one method, constructor, or block to ensure external access.
Instance variables can be declared before or after use.
Access modifiers can be applied to instance variables.
Instance variables are visible to all methods, constructors, and blocks in the class. It is good practice to make instance variables private and provide public access methods.
Instance variables have default values. For numbers, the default value is 0, for booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by their variable names. However, in static methods and other classes, they should be accessed using the fully qualified name: ObjectReference.VariableName.
Example
Employee.java File Code:
import java.io.*;
public class Employee {
// This instance variable is visible to subclasses
public String name;
// Private variable, visible only within this class
private double salary;
// Assigning value to name in the constructor
public Employee(String empName) {
name = empName;
}
// Setting the value of salary
public void setSalary(double empSal) {
salary = empSal;
}
// Printing information
public void printEmp() {
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
public static void main(String[] args) {
Employee empOne = new Employee("tutorialpro");
empOne.setSalary(1000.0);
empOne.printEmp();
}
}
The above example compiles and runs with the following result:
$ javac Employee.java
$ java Employee
Name: tutorialpro
Salary: 1000.0
Class Variables (Static Variables)
Class variables are also known as static variables, declared with the static keyword in a class, but outside of methods.
No matter how many objects are created, there is only one copy of the class variable.
Static variables are rarely used other than being declared as constants. Static variables are declared as public/private, final, and static. Static variables are initialized once and cannot be changed.
Static variables are stored in the static memory. They are often declared as constants and are rarely used alone as static variables.
Static variables are created when they are first accessed and destroyed when the program ends.
They have similar visibility as instance variables. However, to be visible to users of the class, most static variables are declared as public.
Default values are similar to instance variables. For numerical types, the default value is 0; for boolean types, it is false; for reference types, it is null. Values can be specified at the time of declaration or in the constructor. Additionally, static variables can be initialized in static blocks.
Static variables can be accessed using: ClassName.VariableName.
When class variables are declared as public static final, the variable names are typically in uppercase. If the static variables are not public and final, the naming format is the same as instance variables and local variables.
Example:
Employee.java File Code:
import java.io.*;
public class Employee {
// salary is a static private variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Developer";
public static void main(String[] args) {
salary = 10000;
System.out.println(DEPARTMENT + " Average Salary: " + salary);
}
}
The above example compiles and runs with the following result:
Developer Average Salary: 10000.0
Note: If other classes want to access this variable, they can do so like this: Employee.DEPARTMENT.
In this chapter, we learned about Java variable types. In the next chapter, we will introduce the use of Java modifiers.