Java Variables and Literals



In this tutorial, you will learn about variables and literals in Java, with the help of examples.


Java Variables

A variable is a container holding values, or we can say it is a location in memory to store data.

Each variable must be given a unique name (identifier) to designate different storage areas (memory locations).


Create Variables in Java

In the following example, we will see how to create a variable in Java:

int userAge = 23;

Above, userAge is a variable of int data type, and we have assigned value 23 to it.

The int data type designates a variable that can only hold integers.

We can assign a value to a variable during declaration, but it is not mandatory.

In the following example, we will first declare variables and after assign value to them.

int userAger;
userAger = 23;

Note: Java is a statically-typed language. This is why all variables must be declared before they can be used.


Change values of variables

In Java, the value of a variable can be changed in the program. For example.

int userAger = 23;
...
userAger = 26;

Above, the value of userAger is 23, and we changed it to 26.

However, we cannot modify the data type of a variable in Java within the same scope.

The scope of a variable in Java is the area of the program where the variable is accessible.

Remember we can not write the following program:

int userAge = 23;
...
float userAge;

Naming Variables Rules in Java

Java language has its own set of rules and conventions for naming variables. Let us see them:

  • Java is case-sensitive. Meaning, fruit and FRUIT are two different variables.

    String fruit = "apple";
    String FRUIT = "kiwi";
    
    System.out.println(fruit);  // prints apple
    System.out.println(fruit);  // prints kiwi
    
  • Variables in Java must start with either a letter or an underscore _, or a dollar $ sign. For example,

    String fruit;  // valid name and good practice
    String _fruit;  // valid but bad practice
    String $fruit;  // valid but bad practice
    
  • Variables names cannot start with numbers. For example,

    String 1fruit;  // invalid variables
    
  • Variables names cannot use whitespace. For example,

    String my fruit; // invalid variables
    

    To use variable names with more than one word, we can use all lowercase letters for the first word and capitalize the first letter of each subsequent word. For example,

     String myFruit;  // valid name and good practice
    
  • It is highly recommended choosing a name that makes sense when creating variables. For example, message, content, note makes more sense than variable names such as m, c, n.

  • When creating one-world variable names, it is recommended to use all lowercase letters. For example, it is better to use age rather than AGE or aGE.


There are 4 types of variables in Java:

  • Instance Variables (Non-Static Fields)
  • Class Variables (Static Fields)
  • Local Variables
  • Parameters

Java Literals

Any constant value which can be assigned to a variable is called literal / constant. For example,

int x = 15;
float y = 6.2;
chat z = 'B';

Here, 15, 6.2, B are literals / constants.

Here are different types of literals in Java.


1. Boolean Literals

In Java, boolean literals (constants) are used to initialize boolean data types. They allow to store two values: true and false. For example,

boolean flag1 = true;
boolean flag2 = false;

Here true and `false are two boolean literals (constants).


2. Integer Literals

An integer literal (constant) is a numeric value without any fractional or exponential part.

Java has 4 types of integer literals (constants):

  1. binary (base 2)
  2. decimal (base 10)
  3. octal (base 8)
  4. hexadecimal (base 16)

Let us have an example:

// binary 
int binaryNumber = 0b110101

// octal
int octalNumber = 037

// decimal 
int decimalNumber = 49

// hexadeciaml
int hexNumber = 0x7D // 0x represents hexadecimal

// binary
int binaryNumber = 0b110101 // 0b represents bunary 

Note: In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts with 0x.


3. Floating-point Literals

A floating-point literal (constant) is a numeric literal with either a fractional or exponential form. For example,

public class Main {
    public static void main(String[] args) {
        
    double myDouble = 7.3;
    float myFloat = 7.3F;

        // 5.26*10^2
    double myScientific = 5.26e2;

    System.out.println(myDouble);  // prints 7.3
    System.out.println(myFloat);  // prints 7.3
    System.out.println(myScientific);  // prints 526.0 
    }
}

Output

7.3
7.3
526.0

Note: The floating-point literals are used to initialize double and float type variables.


4. Character Literals

Character literals (constants) are Unicode characters enclosed inside single quotes. For example,

char letter = 'b';

Here, b is the character literal.

Escape sequences can be used with character literals. For example, \n (new line), \t (tab), \b (backspace).


5. String Literals

A string literal (constant) is a sequence of characters enclosed inside double quotes. For example,

String str1 = "Hello World";
String str2 = "ExpectoCode";

Here, Hello World and ExpectoCode are two string literals.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.