Variables in Java: Declaration, Initialization and Scope
Introduction
Programs work with data - prices, names, counts, dates - and they keep that data in variables. This tutorial explains variables in Java: how to declare and initialize them, and where they can be used. We will start with what a variable is and how to declare one. We will then see how to initialize and change variables, and Java's rule that a local variable must have a value before it is used. Next we will look at the three kinds of variables - local, instance and static - and at scope, which decides where a variable can be used. Lastly, we will make a variable unchangeable with
(Note - The naming rules for variables are covered in Java Syntax BasicsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords.) What is a variable? A variable is a named location in memory which holds a value. Every variable in Java has -
Where,
OUTPUT of the above code
Explanation of the code
A local variable must be initialized before use
Variables declared inside a method are called local variables. Java does not give local variables a default value, and the compiler refuses to compile code which might read one before it has been assigned -
OUTPUT on compiling the above code
This rule catches a whole class of bugs at compile time. The compiler also rejects declaring two local variables with the same name in the same scope, and assigning a value of the wrong type - such as a
OUTPUT of the above code
Explanation of the code
Scope - where a variable can be used
The scope of a variable is the part of the program where its name can be used. A local variable's scope starts where it is declared and ends at the closing brace of the block it was declared in. Variables declared in an inner block are not visible outside it.
OUTPUT of the above code
Trying to use
OUTPUT on compiling the above code
Note - Declare variables in the smallest scope that works, as close as possible to where they are first used. This makes code easier to read, and prevents a variable from being changed by mistake elsewhere.
Constants with final
Adding
OUTPUT on compiling the above code
Named constants such as
final.(Note - The naming rules for variables are covered in Java Syntax BasicsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords.) What is a variable? A variable is a named location in memory which holds a value. Every variable in Java has -
- a type, which decides what kind of values it can hold - such as
intfor whole numbers,doublefor decimal numbers, orStringfor text; - a name, which you use to refer to it;
- and a value, which can usually change while the program runs.
type name = initialValue;typeis the variable's data type, andnameis its name.= initialValueis optional. Giving a variable its first value is called initializing it.
Declaring, initializing and changing variables
//VariablesDemo.java
public class VariablesDemo {
public static void main(String[] args) {
int quantity; // declared, not yet initialized
quantity = 3; // initialized later
double price = 249.50; // declared and initialized together
String product = "Java book";
boolean inStock = true;
int width = 4, height = 5; // two variables of the same type in one declaration
System.out.println(quantity + " x " + product + " at " + price + ", in stock: " + inStock);
System.out.println("Area = " + (width * height));
quantity = quantity + 2; // assigning a new value
System.out.println("New quantity = " + quantity);
}
}
3 x Java book at 249.5, in stock: true Area = 20 New quantity = 5
quantityis declared on one line and initialized on the next.price,productandinStockare declared and initialized in one statement - the most common style.int width = 4, height = 5;declares twointvariables at once. It is allowed, but one declaration per line is usually clearer.quantity = quantity + 2;reads the current value (3), adds 2, and stores the result back inquantity. The=sign means assign, not equals.
Using a local variable before initializing it
//Uninitialized.java
public class Uninitialized {
public static void main(String[] args) {
int total;
System.out.println(total);
}
}
Uninitialized.java:5: error: variable total might not have been initialized
System.out.println(total);
^
1 error
String to an int variable.
Local, instance and static variables
Where a variable is declared decides what kind of variable it is -- Local variables: Declared inside a method or block. They exist only while that method or block runs, and must be initialized before use. Method parameters are local variables too.
- Instance variables (fields): Declared inside a class, outside any method, without
static. Every object of the class gets its own copy. - Static variables (class variables): Declared inside a class with
static. There is only one copy, shared by all objects of the class.
0 for numbers, false for boolean, and null for objects such as String.
Local, instance and static variables
//Counter.java
public class Counter {
static int totalCounters = 0; // static variable - one copy shared by all Counters
String name; // instance variable - each Counter has its own
int count; // instance variable, default value 0
Counter(String name) { // name (the parameter) is a local variable
this.name = name;
totalCounters = totalCounters + 1;
}
void increment() {
int step = 1; // local variable
count = count + step;
}
public static void main(String[] args) {
Counter visits = new Counter("visits");
Counter clicks = new Counter("clicks");
visits.increment();
visits.increment();
clicks.increment();
System.out.println(visits.name + " = " + visits.count);
System.out.println(clicks.name + " = " + clicks.count);
System.out.println("Counters created = " + Counter.totalCounters);
}
}
visits = 2 clicks = 1 Counters created = 2
- Each
Counterobject has its ownnameandcount, sovisitscounted to 2 andclicksto 1 independently.countstarted at its default value, 0. totalCountersisstatic, so both objects share one copy, and it counted both of them.stepexists only whileincrement()runs. Classes, objects and constructors are covered in detail later in this series - for now, notice where each kind of variable is declared.
Variable scope in blocks
//ScopeDemo.java
public class ScopeDemo {
public static void main(String[] args) {
int outer = 10; // visible until the end of main()
if (outer > 5) {
int inner = 20; // visible only inside this if block
System.out.println("Inside the block: outer = " + outer + ", inner = " + inner);
}
for (int i = 1; i <= 2; i++) { // i is visible only inside the loop
System.out.println("Loop: i = " + i);
}
System.out.println("After the block: outer = " + outer);
}
}
Inside the block: outer = 10, inner = 20 Loop: i = 1 Loop: i = 2 After the block: outer = 10
inner after its block has ended is a compile error -
Using a variable outside its scope
//OutOfScope.java
public class OutOfScope {
public static void main(String[] args) {
if (true) {
int inner = 20;
}
System.out.println(inner);
}
}
OutOfScope.java:7: error: cannot find symbol
System.out.println(inner);
^
symbol: variable inner
location: class OutOfScope
1 error
final to a declaration makes a variable a constant - it can be assigned only once. A static final field is the usual way to define a named constant, written in capitals by convention.
Assigning to a final variable
//FinalDemo.java
public class FinalDemo {
static final double TAX_RATE = 0.18;
public static void main(String[] args) {
final int maxItems = 10;
maxItems = 20;
System.out.println(maxItems * TAX_RATE);
}
}
FinalDemo.java:7: error: cannot assign a value to final variable maxItems
maxItems = 20;
^
1 error
TAX_RATE make code easier to read than bare numbers, and if the value ever changes, you change it in only one place.
Summary
In this tutorial we first saw that a variable has a type, a name and a value. We then declared and initialized variables, assigned new values to them, and saw that a local variable must be initialized before it is used. Next we looked at local, instance and static variables, and saw that only instance and static variables get default values. We then learned how scope limits where a variable can be used. Lastly, we made variables into constants with final. In the next tutorial, we will look at Java's primitive data typesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples - the types of values a variable can hold.Java Fundamentals Tutorials
Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples Java var Keyword: Local Variable Type InferenceClick to read tutorial: Java var Keyword: Local Variable Type Inference Java Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators Java Bitwise and Shift Operators with ExamplesClick to read tutorial: Java Bitwise and Shift Operators with Examples
Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples Java var Keyword: Local Variable Type InferenceClick to read tutorial: Java var Keyword: Local Variable Type Inference Java Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators Java Bitwise and Shift Operators with ExamplesClick to read tutorial: Java Bitwise and Shift Operators with Examples