Learn Java from Scratch: Variables and Data Types in Java (Comprehensive Guide)19 min read

Variables in Java Programming

Variable is a name (or identifier) that is associated with a value that can be changed such as age, name, address, etc… The name uniquely identifies each variable, assigning a value to the variable and retrieving the value stored. There are 3 types of variables in Java, which are a local variable, static (or class) variable and instance variable (as briefly mentioned in the previous article).

Declaring a variable

You must declare all variables before they can be used. Here is the basic syntax to declare a variable in Java:

data type variable [ = value][, variable [ = value] ...] ;

This is the basic syntax of declaring a variable in Java, first, you need to define the data type of this variable (you’ll learn about data type right away in the last part of this article) follow by your variable name then it’s optional to assign your variable value because you can assign value to your variable later. Here are some valid examples of variable declaration and initialization in Java:

int a, b; // declare 2 variables a and b with type int
a = 20, b = 30; // initializes 20 for a, and 30 for b

// declares and assigns value at the same time, called 'literal'
char x = 'X' 
boolean pass = true;

Types of variables

Local variable

The local variables are variables declared in constructors, methods or blocks. Their scope is limited to where it is declared, usually surrounded by curly brackets which means that you can’t change their values and access them outside of the methods, blocks or constructors you have defined their values. (Don’t worry about constructor, we will talk about it later). Here are some examples of local variables:

public class Example{
    public void PrintAge() {
        int age = 19; // local variable age, which is visiable inside PrintAge method
        System.out.println("My age is " + age);
    }
    public static void main(String[] args){
        Example a = new Example();
        a.PrintAge(); // My age is 19
    }
}

In this example above, we have a local variable age inside the PrintAge method. If we run this program, this will find the main method, and here compiler sees inside the main method we have created object a type of Example class, then we access PrintAge method by objectName then dot notation then follow by the method we want to call e.g a.PrintAge(), it will call the method PrintAge and print out the text “My age is 19” on the screen.

You may also declare local variables within blocks of code marked by braces. For example:

if(totalAmout > 3000){
   double discount = 10;
   double totalPayment;
   totalPayment = totalAmout - (totalAmout * discount / 100);
}

Here we have 2 variables, discount and totalPayment, which are just visbile in this if block. Other methods, blocks…don’t know the existence of those variables.

NOTE: It is best practice to assign a value before you use a local variable because local variables are not given initial default values. For example:

public class Example{
    public void PrintAge() {
        int age; 
        age = age + 1;
        System.out.println("My age is " + age);
    }
    public static void main(String[] args){
        Example a = new Example();
        a.PrintAge(); // error
    }
}

Instance Variable

The instance variable in Java is used by Objects to store their states. Variables that are defined outside any method, block and constructor declaration and inside a class without the static keyword are known as an instance variable.

The instance variables are different than the local variables because there are visible for all methods, constructors, and blocks in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.

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 VARIABLE TYPEDEFAULT VALUE
booleanfalse
byte(byte)0
short(short) 0
int0
long0L
charu0000
float0.0f
double0.0d
Objectnull

For example:

public class Example{
    public int age = 69; // instance variable with public access
    private String blogName = "learntocodetogether.com"; // instance variable with private access
    public void printBlogInfo(){
   // access the value of instance variable blogName
        System.out.println("You're reading a Java tutorial on " + blogName);
   // access the value of instance variable age.
        System.out.println("Your host is " + age + " years old."); 
    }
    
    public static void main(String[] args){
    // create a new instance of class Example
        Example a = new Example(); 
    // call the printBlogInfo method
        a.printBlogInfo();
    }
}

OUTPUT:

You're reading a Java tutorial on learntocodetogether.com
Your host is 69 years old.

Instance variables have their own separate copy of instance variable, which means when you modify the value of instance variable via an object, the only change is the instance value of this object and instance values of other objects stay intact. For better understanding, here is another example:

public class Example {
    String text = "learntocodetogether.com";

    public static void main(String args[]) {
        Example obj1 = new Example();
        Example obj2 = new Example();
        Example obj3 = new Example();

        System.out.println(obj1.text);
        System.out.println(obj2.text);
        System.out.println(obj3.text);

        obj2.text = "Learn to Code Together";

        System.out.println(obj1.text);
        System.out.println(obj2.text);
        System.out.println(obj3.text);
    }
}

OUTPUT:

learntocodetogether.com
learntocodetogether.com
learntocodetogether.com
learntocodetogether.com
Learn to Code Together
learntocodetogether.com

As can be observed, we can access the instance variable directly by object name and follow by the name of the instance variable. We have changed the instance value of obj2 and just instance variable of this object has been changed, others stay the same.

Static variable

The static or class variable is variable which defined by static keyword. The static variable can be used to refer to the common property of all objects. If you create several objects and access a static variable, it would share among all of the objects with the same value, if you change the value of a static variable in one object (unlike the instance variable), all static variable value of other objects would also be changed. For example:

public class Example {
    static String text = "learntocodetogether.com";

    public static void main(String args[]) {
        Example obj1 = new Example();
        Example obj2 = new Example();
        Example obj3 = new Example();

        System.out.println(obj1.text);
        System.out.println(obj2.text);
        System.out.println(obj3.text);

        Example.text = "Learn to Code Together";

        System.out.println(obj1.text);
        System.out.println(obj2.text);
        System.out.println(obj3.text);
    }
}

OUTPUT:

learntocodetogether.com
learntocodetogether.com
learntocodetogether.com
Learn to Code Together
Learn to Code Together
Learn to Code Together

Because static variables are variables which belong to the class rather than a specific object, then we can access the static variables by some different ways, such as:

System.out.println(text); // directly print the static variable
System.out.println(Example.text) // display the static variable by className.staticVariableName
System.out.println(obj1.text) // display the static variable via obj1

Data Types in Java Programming

In Java and many other programming languages, data types define the value and specify the size that a variable can take, for example, a variable has a type int then this variable can only have a value as an integer. There are 2 types of data types in Java:

  • Primitive data-types: Primitive data-types variables are variables that directly contain values. There are 8 primitive types include byte, short, int, long, char, float, double and boolean.
  • Non-primitive data types: The non-primitive data types are references to objects include Classes, Interfaces, and Arrays (but we talk about Classes, Interfaces, and Arrays in upcoming articles).

Java is a statically and strongly typed language. A language is statically typed if the data type of a variable is known at compile time. Like C, C++ or some other languages, this means that you must specify the type of a variable before using it.

Primitive Data Types

Byte Data Type

The byte data type is an 8-bit signed two’s complement integer. Its value-range lies between \(-2^7\) -128 to \(2^7 – 1\) 127 (inclusive). This data type is mostly used to save memory and when you are certain that the numbers would be in the limit specified by byte data type and its default value is 0. For example:

public class Example{
    public static void main(String[] args){
        byte luckyNum;
        luckyNum = 77;
        System.out.println(luckyNum); // 77
    }
}

But be careful with the value you want to give for a specific type, in this case, the data type is byte, which is range around -128 to 127, if you assign to your variable a value larger or smaller than the given range, you will get something like type mismatch. For instance:

public class Example{
    public static void main(String[] args){
        byte luckyNum;
        luckyNum = -178;
        System.out.println(luckyNum); // error, type mismatch
    }
}

You already know that 1 byte equals 8 bits and if you wonder why there is \(2^7\) not \( 2^8\) because this data type is signed data type, which means it spends 1 bit to store the sign of a given value (positive and negative), and the rest 7 bit for the actual value.

Short Data Type

The short data type is a 16-bit signed two’s complement integer. Its value-range lies between -215  to 215 – 1 (inclusive). Its minimum value is -32,768 and the maximum value is 32,767. Its default value is 0 and its default size is 2 bytes. The short data type can be used to save the memory with the specific values in the given short data type range. For example:

public class Example{
    public static void main(String[] args){
        short luckyNum;
        luckyNum = -178;
        System.out.println(luckyNum); // -178
    }
}

Int Data Type

By default, the int data type is a 32-bit signed two’s complement integer and its size is 4 bytes, which has a minimum value of -231 and a maximum value of 231-1. However, in Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer which is just for positive integer has a minimum value of 0 and a maximum value of 232-1.

The minimum value and maximum values of the signed int data type lie between  -2,147,483,648 and 2,147,483,647 (inclusive). For unsigned integer, its value-range lies between 0 and 4294967295. Its default value is 0. For instance:

public class Example{
    public static void main(String[] args){
        int a, b;
        a = 10000000;
        b = -20000000;
        System.out.println(a); // 10000000
        System.out.println(b); // -20000000
    }
}

Here we have two variables a and b type signed int, we will talk about how to use unsigned int later.

Long Data Type

The long data type is a 64-bit two’s complement integer. Its size is 8 bytes. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1.

Its minimum value is – 9,223,372,036,854,775,808 and maximum value is 9,223,372,036,854,775,807. For unsigned long, the values are between 0 and \(1.84467\dots E19\). Its default value is 0. Use long as a data type when you want to represent really huge numbers that int data type cannot hold. For example:

public class Example{
    public static void main(String[] args){
        long a;
        a = -1696969696969696969l;
        System.out.println(a); // -1696969696969696969
    }
}

Char Data Type

The char data type is a single 16-bit Unicode character. Its size is 2 bytes and its value-range lies between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive). The char data type is used to store characters. Its default value is ‘\u0000’. For example:

public class Example{
    public static void main(String[] args){
        char aLetter;
        aLetter = 'A';
        System.out.println(aLetter); // A
    }
}

When declaring a variable as a char type, the value of this variable when you assign should be put in the single quote, if you put it into a double quote Java will think you are assigning this value to a variable with the type of String (String in Java is treated as an object), not char, for example:

public class Example{
    public static void main(String[] args){
        char aLetter;
        aLetter = "A";
        System.out.println(aLetter); // error, type mismatch
    }
}

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating-point. Its range of values is beyond the scope of this article. Its default value is 0.0F and its default size is 4 bytes. For example:

public class Example{
    public static void main(String[] args){
        float mark;
        mark = 9.8f;
        System.out.println(mark); // 9.8
    }
}

It is recommended that you shouldn’t use float to store values that need integrity or complete precision such as currency, money because when using float as a data type the precision of this value can be lost.

Double Data Type

The double data type is pretty the same as float, the double data type is a double-precision 64-bit IEEE 754 floating-point. Its ranges of values also are beyond the scope of this article. Its default size is 8 bytes and its default value is 0.0d, for example:

public class Example{
    public static void main(String[] args){
        double mark;
        mark = 79.8d;
        System.out.println(mark); // 79.8
    }
}

It is also recommended that you shouldn’t use double to store values that need integrity or complete precision such as currency, money because when using double as a data type the precision of this value can be lost.

Boolean Data Type

This is the last primitive data type in Java, boolean data type just has either 2 values, true or false. This data type is used for simple flags that track true/false conditions. Its “size” isn’t something that’s precisely defined and its default value is false. For instance:

public class Example{
    public static void main(String[] args){
        boolean flag;
        flag = true;
        System.out.println(flag); // true
    }
}

NOTE: It is important to note that a variable is associated with a type, and is only capable of storing values of that particular type. For example, an int variable can store integer values, such as 1234; but it cannot store a real number such as 65.65, a character, a boolean value, etc… For example:

public class Example{
    public static void main(String[] args){
        boolean flag; // a varible with type boolean
        flag = 2; // but assign it an integer
        char name; // a variable with type character 
        name = true; // but assign it a boolean value 
        int num; // a varible with type int
        num = 12.45f; // but assign it a float value
        System.out.println(flag); // type mismatch
        System.out.println(name); // type mismatch
        System.out.println(num); // type mismatch
    }
}

The following chart summarizes the default values for the above data types.

Data TypeDefault ValueDefault size
booleanfalse1 bit
char‘\u0000’2 byte
byte01 byte
short02 byte
int04 byte
long0L8 byte
float0.0f4 byte
double0.0d8 byte

Java Literal

literal is a fixed value that we assign to a variable in a program; literals are represented directly in your code without requiring computation. For example:

boolean flag = true;
char firstLetter = 'A';
int num = 100000;
short a = 2500;
byte b = 10;
float pi = 3.14f;
double c = 234.43d;
long manyDigits = 1234345445435345345l;

Integer Literal

You can represent integer literal with 3 number systems, which are decimal (which we usually use), hexadecimal and binary. The example below shows the correct syntax for each number system.

// The number 26, in decimal
int decVal = 26;
//  The number 26, in hexadecimal
int hexVal = 0x1a;
// The number 26, in binary
int binVal = 0b11010;

Float Literal

A floating-point literal is of type float if it ends with the letter F or f; otherwise, its type is double and it can optionally end with the letter D or d.

The floating-point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).

double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1  = 123.4f;

Char and String Literal

Literals of types char and String may contain any Unicode (UTF-16) characters, for example:

char ch = 'L';
String str = "Learntocodetogether.com";
0 0 votes
Article Rating
Previous Article
Next Article
Subscribe
Notify of
guest
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Every support is much appreciated ❤️

Buy Me a Coffee

0
Would love your thoughts, please comment.x
()
x