×
>
<

Aptitude

Variables and Constants

Java Variables

A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

Types of Variables

There are three types of variables in Java:

  • Local Variales
  • Instance Variales
  • Static Variales

1.Local Variable

A variable declared inside the body of the method is called local variable. We can use this variable only within that method and not the other methods as it is out of their scope.

A local variable cannot be defined with "static" keyword.

2.Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3.Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.

Static of Vaiable Example :

  
public class A  
{  
    static int m=100;//static variable  
    void show()  
    {    
        int n=90;//local variable
        System.out.println(n);    
    }  
    public static void main(String args[])  
    {  
        int data=50;//instance variable
        System.out.println(data);
        System.out.println(m);
        //System.out.println(n); // Can not access, presenet in another method
        A a = new A();
        a.show(); 
    }  
}//end of class   
  
output
  
50
100
90 
  

Java Constant

As the name suggests, a constant is an entity in programming that is immutable. In other words, the value that cannot be changed. In this section, we will learn about Java constant and how to declare a constant in Java.

What is constant?

Constant is a value that cannot be changed after assigning it. Java does not directly support the constants. There is an alternative way to define the constants in Java by using the non-access modifiers static and final.

How to declare constant in Java?

In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters.

Static and Final Modifiers

  • The purpose to use the static modifier is to manage the memory.
  • It also allows the variable to be available without loading any instance of the class in which it is defined.
  • The final modifier represents that the value of the variable cannot be changed. It also makes the primitive data type immutable or unchangeable.

Syntax
  
static final datatype identifier_name=value;   
  
Example:
  
static final double PRICE=432.78;    
  

Where static and final are the non-access modifiers. The double is the data type and PRICE is the identifier name in which the value 432.78 is assigned.

In the above statement, the static modifier causes the variable to be available without an instance of its defining class being loaded and the final modifier makes the variable fixed.

Here a question arises that why we use both static and final modifiers to declare a constant?

If we declare a variable as static, all the objects of the class (in which constant is defined) will be able to access the variable and can be changed its value. To overcome this problem, we use the final modifier with a static modifier.

When the variable defined as final, the multiple instances of the same constant value will be created for every different object which is not desirable.

When we use static and final modifiers together, the variable remains static and can be initialized once. Therefore, to declare a variable as constant, we use both static and final modifiers. It shares a common memory location for all objects of its containing class.

Why we use constants?

The use of constants in programming makes the program easy and understandable which can be easily understood by others. It also affects the performance because a constant variable is cached by both JVM and the application.

Some important points :

  • Write the identifier name in capital letters that we want to declare as constant. For example, MAX=12.
  • If we use the private access-specifier before the constant name, the value of the constant cannot be changed in that particular class.
  • If we use the public access-specifier before the constant name, the value of the constant can be changed in the program.

Declaring constants as private
  
import java.util.Scanner;  
public class ConstantExample1   
{  
	//declaring constant   
	private static final double PRICE=234.90;  
	public static void main(String[] args)  
	{  
		int unit;  
		double total_bill;  
		System.out.print("Enter the number of units you have used: ");  
		Scanner sc = new Scanner(System.in);  
		unit=sc.nextInt();  
		total_bill=PRICE*unit;  
		System.out.println("The total amount you have to deposit is: "+total_bill);  
	}  
}  
  
output
  
Enter the number of units you have used: 10
The total amount you have to deposit is: 2349.0 
  
Declaring Constant as Public

In the following example, we have declared constant PI as public. Inside the main() method, we have assigned 3.15 in the constant PI. After that, we have invoked the printValue() method. When we execute the program, it shows an error cannot assign a value to the final variable PI.

  
 public class ConstantExample3  
{  
	//declaring PI as constant   
	public static final double PI= 3.14;  
	public static void main(String[] args)   
	{  
		printValue();  
		//trying to assign 3.15 in the constant PI  
		PI = 3.15;  
		printValue();  
	}  
			
	void printValue()   
	{  
		System.out.print("The value of PI cannot be changed to " + PI);  
	}  
}  
  
output
  
ConstantExample3.java:7: error: non-static method printValue() cannot be referenced from a static context
printValue();  
^
ConstantExample3.java:9: error: cannot assign a value to final variable PI
PI = 3.15;  
^
ConstantExample3.java:10: error: non-static method printValue() cannot be referenced from a static context
printValue();  
^
3 errors
  
Using Enumeration (Enum) as Constant
  • It is the same as the final variables.
  • It is a list of constants.
  • Java provides the enum keyword to define the enumeration.
  • It defines a class type by making enumeration in the class that may contain instance variables, methods, and constructors.
  
public class EnumExample  
{    
	//defining the enum   
	public enum Color {Red, Green, Blue, Purple, Black, White, Pink, Gray}    
	
	public static void main(String[] args)   
	{    
		//traversing the enum    
		for (Color c : Color.values())    
		System.out.println(c);    
	}  
}     
  
output
  
Red
Green
Blue
Purple
Black
White
Pink
Gray