Java Variables

Java Variables


A variable refers to the memory location that holds values like: numbers, texts etc. in the computer memory. A variable is a name of location where the data is stored when a program executes.  To be able to use a variable it needs to be declared. Declaring variables is normally the first thing that happens in any program.

Declaring Variables:

One variable in your program can store numeric data while another variable can store text data. Java has special keywords to signify what type of data each variable store. Use keywords like boolean, byte, char, int etc., when declaring your variables to set the data type of the variable. The basic form of a variable declaration is shown here:

type identifier [= value] [, identifier [= value] …];

The type is one of Java’s data types. The identifier is the name of the variable. To declare more than one variable of the specified type, use a comma-separated list.


char aCharacter;

int aNumber;

You can assign a value to a variable at the same time that it is declared. This process is known as initialization:


char aCharacter = ‘a’;

int aNumber = 10;

Declaring a variable and then giving it a value:

char aCharacter;

aCharacter = ‘a’;

int aNumber;

aNumber = 10;

A variable must be declared with a data type or an error will be generated! The data type of a variable should be used only once with the variable name – during declaration. After that, you can refer to the variable by its name without the data type.

Naming variables:

Rules that must be followed when naming variables:

•    No spaces in variable names.

•    No special symbols in variable names such [email protected]#%^&*

•    Variable names can only contain letters, numbers, and the underscore (_) symbol.

•    Variable names cannot start with numbers, only letters or the underscore (_) symbol but variable names can contain numbers.

Types of Variables:

There are three kinds of variables in Java:

•    Local variables

•    Instance variables

•    Class/static variables

Local variables:

•    Local variables are declared in methods, constructors, or blocks.

•    Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.

•    Access modifiers cannot be used for local variables.

•    Local variables are visible only within the declared method, constructor or block.

•    Local variables are implemented at stack level internally.

•    There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.

Instance Variables:

•    In object oriented programming, objects store their individual states in the “non-static fields” that is declared without the static keyword.

•    Each object of the class has its own set of values for these non-static variables so we can say that these are related to objects (instances of the class).

•    Hence these variables are also known as instance variables. These variables take default values if not initialized.

Class Variables:

•    These are collectively related to a class and none of the object can claim them its sole-proprietor.

•    The variables defined with static keyword are shared by all objects. Here Objects do not store an individual value but they are forced to share it among themselves.

•    These variables are declared as “static fields” using the static keyword.

•    Always the same set of values is shared among different objects of the same class. So these variables are like global variables which are same for all objects of the class.

•    These variables take default values if not initialized.

Example for types of variables:

class A {
int data=50; //instance variable
static int m=100; //static variable
void method () {
int n=90; //local variable
}//end of class

Variable Type Conversion & Type Casting:

A variable of one type can receive the value of another type. Here there are 2 cases:

Case 1: Variable of smaller capacity is to be assigned to another variable of bigger capacity.
double d;
int i=10;

This process is Automatic, and non-explicit is known as Conversion.

Case 2: Variable of larger capacity is to be assigned to another variable of smaller capacity.
double d=10;
int i;
i= (int) d;
In such cases you have to explicitly specify the type cast operator, here int is the type cast operator. This process is known as Type Casting.
In case, you do not specify a type cast operator, the compiler gives an error. Since this rule is enforced by the compiler, it makes the programmer aware that the conversion he is about to do may cause some loss in data and prevents accidental losses.

Java Modifiers:

A modifier is a keyword placed in a class, method or variable declaration that changes how it operates. In the Java programming language the following keywords are modifiers: abstract, final, native, private, protected, public, static, synchronized, transient, and volatile.

There are two types of java modifiers, they are

•    Java Access Modifiers

•    Non Access Modifiers

Java Access Modifiers:

Access modifiers specify who can access them. There are four access modifiers used in java. They are public, private, protected, no modifier (declaring without an access modifier). Using ‘no modifier’ is also sometimes referred as ‘package-private’ or ‘default’ or ‘friendly’ access. Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

Class level access modifiers (java classes only): Only two access modifiers is allowed, public and no modifier

•    If a class is ‘public’, then it CAN be accessed from ANYWHERE.

•    If a class has ‘no modifier’, then it CAN ONLY be accessed from ‘same package’.

Member level access modifiers (java variables and java methods): All the four public, private, protected and no modifier is allowed.

•    public and no modifier – the same way as used in class level.

•    private – members CAN ONLY access.

•    protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access.

public keyword in Java: public is the least restrictive access modifier in Java programming language and its bad practice to declare field, method or class by default public because once you make it public it’s very difficult to make any change on internal structure of class as it affect all clients using it.

Making class or instance variable public is also violated principle of Encapsulation which is not good at all and affects maintenance badly. Instead of making variable public you should make it private and provided public getter and setter. public modifier can also be applied to top level class. In Java name of file must be same with public class declared in the file.


The following function uses public access control:

public static void main (String [] arguments) {
// …
The main () method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.
private keyword in Java: private keyword or modifier in java can be applied to member field, method or nested class in Java. You cannot use private modifier on top level class. private variables, methods and class are only accessible on the class on which they are declared. Private is highest form of Encapsulation Java API provides and should be used as much as possible.

It’s best coding practice in Java to declare variable private by default. private method can only be called from the class where it has declared. As per Rules of method overriding in Java, private method cannot be overridden as well. private keyword can also be applied to constructor and if you make constructor private you prevent it from being sub-classed. Popular example of making constructor private is Singleton class in Java which provides get Instance () method to get object instead of creating new object using constructor in Java. Here are some differences between private and protected, public and package level access.


The following class uses private access control:
public class Logger {
private String format;
public String getFormat () {
return this.format;
public void setFormat (String format) {
this.format = format;

Here, the format variable of the Logger class is private, so there’s no way for other classes to retrieve or set its value directly. So to make this variable available to the outside world, we defined two public methods: getFormat (), which returns the value of format, and setFormat (String), which sets its value.
protected keyword in java: The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a super class can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.


The following parent class uses protected access control, to allow its child class override open Speaker () method:
class Audio Player {
protected boolean open Speaker (Speaker sp) {
// implementation details
class StreamingAudioPlayer {
boolean open Speaker (Speaker sp) {
// implementation details

Here if we define open Speaker () method as private then it would not be accessible from any other class other than Audio Player. If we define it as public then it would become accessible to the entire outside world. But our intension is to expose this method to its subclass only, that’s why we used protected modifier.
Package or default access level in Java: There is no access modifier called package instead package is a keyword which is used to declare package in Java, package is a directory on which a class in Java belongs. Package or default access level is second highest restrictive access modifier after private and any variable, method or class declared as package-private is only accessible on the package it belongs. Good thing about default modifier is that, top level class can also be package-private if there is no class level access modifier.


Variables and methods can be declared without any modifiers, as in the following examples:

String version = “1.5.1”;

boolean process Order () {
return true;
Access Control and Inheritance:

The following rules for inherited methods are enforced:

•    Methods declared public in a super class also must be public in all subclasses.

•    Methods declared protected in a super class must either be protected or public in subclasses; they cannot be private.

•    Methods declared without access control (no modifier was used) can be declared more private in subclasses.

•    Methods declared private are not inherited at all, so there is no rule for them.

Non Access Modifiers:

Java provides a number of non-access modifiers to achieve much other functionality.

•    The static modifier for creating class methods and variables

•    The final modifier for finalizing the implementations of classes, methods, and variables.

•    The abstract modifier for creating abstract classes and methods.

•    The synchronized and volatile modifiers, which are used for threads.


•    Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.

•    Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.

•    A static method in a super class can be shadowed by another static method in a subclass, as long as the original method was not declared final.

•    However, you can’t override a static method with a nonstatic method.

•    In other words, you can’t change a static method into an instance method in a subclass.


•    A final class can’t be extended i.e., final class may not be sub classed.

•    A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant).

•     An abstract class is a class designed with implementation gaps for subclasses t fill in and is deliberately incomplete.

•    A class cannot be both final and abstract.

•    abstract methods cannot be private.

•    abstract methods cannot be final.


Abstract Class:

An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is for the class to be extended.

A class cannot be both abstract and final. (Since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise a compile error will be thrown.

An abstract class may contain both abstract methods as well normal methods.


abstract class Caravan {

private double price;
private String model;
private String year;
public abstract void goFast (); //an abstract method
public abstract void changeColor ();

Abstract Methods:

An abstract method is a method declared without any implementation. The methods body (implementation) is provided by the subclass. Abstract methods can never be final or strict.
Any class that extends an abstract class must implement all the abstract methods of the super class unless the subclass is also an abstract class.
If a class contains one or more abstract methods then the class must be declared abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample ();


public abstract class SuperClass {
abstract void m (); //abstract method
class SubClass extends SuperClass {
// implements the abstract method
void m () {


The synchronized key word used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier can be applied with any of the four access level modifiers.

public synchronized void showDetails (){
The volatile is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory.
Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables which are of type object or private. A volatile object reference can be null.
public class MyRunnable implements Runnable
private volatile boolean active;
public void run ()
active = true;
while (active) // line 1
// some code here
public void stop ()
active = false; // line 2
Usually, run () is called in one thread (the one you start using the Runnable), and stop () is called from another thread. If in line 1 the cached value of active is used, the loop may not stop when you set active to false in line 2. That’s when you want to use volatile.



This site uses Akismet to reduce spam. Learn how your comment data is processed.