GFG Day 2: Variables, Data Types, Keywords, and Literals

sri parthusri parthu
13 min read

Java Variables

  • In Java, variables are containers used to store data in memory. They play a very important role in defining how to store, access, and manipulate the data.

Key components in Java

  • In Java, variables have three components:

    • Data Type: It defines the data to be stored, like int, String, float, etc.

    • Variable name: A unique identifier following Java naming conventions

    • Value: Data assigned to the variable

How to declare a Java variable?

  • To declare the Java variable first, we have to write data type and variable name
int givenNumber;
  • Here int is the data type that holds the variable

  • givenNumber is the variable name follows the naming convention (e.g., camelCase)

Note: Like this we can declare the variable in Java

How to initialize a Java variable?

  • To initialize a Java variable, we have 3 components: data type, variable name, and assigned value.
int givenNumber = 20;
  • int is the data type that holds the variable

  • givenNumber is the variable name that follows the naming convention (e.g., camelCase)

  • 20 is the value that is reserved in memory for the variable

Let's declare and initialize variables of different data types like float, int, double, char, and String.

// fileName: variables.java

public class variables{
    public static void main(String[] args){
        // Declare and initalizing variables

        // Integer variable
        int age = 15;

        // String variable
        String favName = "Core Java";

        // Double variable
        double salary = 15000.60;

        // Float variable
        float pi = 3.1415f;

        // Character variable
        char var = 'p';

        //Displaying the values of the varibale
        System.out.println("Age: " + age);
        System.out.println("Favourite name: " + favName);
        System.out.println("Double: " + salary);
        System.out.println("Float: " + pi);
        System.out.println("Character: " + var);
    }
}

Output

Age: 15
Favourite name: Core Java
Double: 15000.6
Float: 3.1415
Character: p

Types of Java Variables

  • In Java there are 3 types of variables, such as local variables, instance variables, and Static variables
  1. Local variable:

    • A local variable defined and accessed only within a block, method, or constructor is called a local variable.

    • A local variable is created in a method or block at the time of declaration and destroyed when the execution is completed.

    • No default values are initialized before use.

Example showing how to declare a local variable inside and access it in the method and block where it is declared, and it can't be used outside the block

// localVariable.java

public class LocalVariable{
    public static void main(String[]  args){
        // num is local variable
        int num = 15;
        System.out.println(num);

        // message is local variable
        String message = "This is Advance Java";
        System.out.println(message);

        // Conditional statment 
        if (num >= 15) { 
          // age is local variable
            String age = "Eligible to vote";
            System.out.println(age);
        }

        // Loop
        for(int i = 0; i < 3; i++){
        //loopMessage is local variable
        String loopMessage = "Iteration " + i;
        System.out.println(loopMessage);
        }
    }
}

Output

15
This is Advance Java
Eligible to vote
Iteration 0
Iteration 1
Iteration 2
  1. Instance variable:

    • An instance variable is also known as a non-static variable and is declared inside the class, outside of any method, block, or constructor.

    • An instance variable is accessible through the class using this.variableName.

    • An instance variable can be accessed only by creating an object and initializing the variable in the constructor while creating an object.

    • An instance variable can be initialized with default values like 0, false, null, etc.

Example of using instance variables, which are declared within a class and initialized in the constructor, with default values for uninitialized primitive types.

// InstanceVariable.java

public class InstanceVariable{
    // Declaring Instance variable
    public String message;
    public int num;
    public Integer num1;
    public InstanceVariable(){
        // Default constructor
        // Initilizing Instance variable
        this.message = "This is Advance Java";
    }

    // Main Method
    public static void main(String[] args){
    // Object creation
    InstanceVariable msg = new InstanceVariable();

    // Displaying O/P
    System.out.println("The message is " + msg.message);
    System.out.println("The num is " + msg.num);
    System.out.println("The integer is " + msg.num1);    
}

Output

The message is This is Advance Java
The num is 0
The integer is null
  1. Static variable:

    • Static variables are also known as class variables.

    • They are declared inside the class using the static keyword, outside of the constructor, methods, or blocks.

    • They are accessible throughout the class and can be accessed using the class name (ClassName.variableName).

    • Default values are the same as instance variables.

Example demonstrates the use of static variables, which belong to the class and can be accessed without creating an object of the class.

// StaticVariable.java

public class StaticVariable {

    // Declared static variable
    public static String message = "This is advance Java";

    public static void main(String[] args)
    {

        // geek variable can be accessed without object
        // creation Displaying O/P StaticVariable.StaticVariable --> using the
        // static variable
        System.out.println("My Message is: " + StaticVariable.message);

        // static int num = 0;
        // above line, when uncommented,
        // will throw an error as static variables cannot be
        // declared locally.
    }
}

Output:

My Message is: This is advance Java

Instance variables Vs static variables

Instance VariableStatic variable
→ An instance variable belongs to an object of a class.→ A static variable is not specific to an object but belongs to the class itself.
→ An instance variable can be accessed in the method of the class using this.variableName→ A static variable can be accessed using className.varibleName
→ An instance variable will be allocated when you create an object using the new keyword.→ A static variable will be also allocate memory when the class is loaded by the JVM

The example demonstrates the use of instance and static variables, which belong to the object and class and can be accessed without creating an object of the class and with creating an object of the class.

// fileName: InstanceStatic.java
public class InstanceStatic{
    public static int num = 14; // Static variable
    public String message; // Instance variable

    public InstanceStatic(){
        // Default constructor
        // Initilizing Instance variable
        this.message = "This is advance java";
    }

    public static void main(String[] args){
        // Static variable accessing without object
        int IncNum = ++num;
        System.out.println("The static increment value is " + IncNum);

        // Instance variable accessing with object
        InstanceStatic obj = new InstanceStatic();
        System.out.println("The instance variable message is: " + obj.message);

    }
}

Output

The static increment value is 15
The instance variable message is: This is advance java

Java Data Types

  • Data types specify the different sizes and values that can be stored in the variable, and they are mainly used to inform the compiler what kind of data we are assigning to the variable. They are primitive datatypes and non-primitive datatypes.

Why do data types matter in Java?

  • Data types matter in Java for choosing the right type (byte Vs int) to save memory, to perform well by reducing errors, and for explicit type casting to make the code more readable.

Java Data Type categories

  • Java has two categories of data types: primitive and non-primitive data types.

data_types_in_java

  1. Primitive data types: It is a basic building block that stores simple values directly in memory and stores only single values. They are 8:
Data TypeUsageDefault SizeValues
→ booleanrepresent the logical value true and false1 bytestrue or false
→ charused to store single character using single quote2 bytes‘a’, ‘c’, ‘g’, ‘f’, ‘g’, etc.
→ byteused to store integer value1 bytesmin value = -128 max value = 127
→ shortused to store integer value2 bytesmin value = -32,768 max value = 32,767
→ intused to store integer value4 bytesmin value = -214,483,648 max value = 2,147,483,647
→ longused to store a range of numeric value8 bytes (458795635L)min value = -9223,372,036,854,775,808 max value = 9223,372,036,854,775,807
→ floatused to store decimal value4 bytes (45.5F)stores 6 to 7 decimal digits
→ doubleused to store decimal value8 bytesstore 15 to 16 decimal digits

The example demonstrates the use of primitive data types.

 // fileName: datatypes.java

public class datatypes{
    public static void main(String[] args){
        //Boolean
        boolean isFollow = false;
        boolean isUnFollow = true;

        //char
        char name = 'F';

        //byte
        byte num1 = 10;

        //short
        short num2 = 1000;

        //int
        int num3 = 555;

        //long
        long num4 = 45879L;

        //float
        float num5 = 89.5F;

        //double
        double num6 = 5623147.33;

        //Displaying output
        System.out.println("The value of boolean isFollow: " + isFollow);
        System.out.println("The value of boolean isUnFollow: " + isUnFollow);
        System.out.println("The value of char name: " + name);
        System.out.println("The value of byte num1: " + num1);
        System.out.println("The value of short num2: " + num2);
        System.out.println("The value of int num3: " + num3);
        System.out.println("The value of long num4: " + num4);
        System.out.println("The value of float num5: " + num5);
        System.out.println("The value of double num6: " + num6);
    }
}

Output

The value of boolean isFollow: false
The value of boolean isUnFollow: true
The value of char name: F
The value of byte num1: 10
The value of short num2: 1000
The value of int num3: 555
The value of long num4: 45879
The value of float num5: 89.5
The value of double num6: 5623147.33
  1. non-primitive data type: It is a reference type that doesn’t store the variable value directly in memory but contains the address of the variable value. They include strings, arrays, classes, and interfaces.

    1. String: A string is mainly used to assign more than one character value to a variable.

Syntax:

    <String-type> <string-variable> = "<sequence of character>";

Example demonstrates how to use string variables to store and display text values.

    // fileName: string.java

    public class string{
        public static void main(String[] args){
           String greet = "Hello World!";
           String message = "This is advance Java";

            System.out.println("The value of string greet: " + greet);
            System.out.println("The value of string message: " + message);
        }
    }

Output

    The value of string greet: Hello World!
    The value of string message: This is advance Java

Note: We have some more classes that we will learn later on coming blogs


Java Keywords

  • Keywords are reserved words with predefined meanings in Java that are used by the compiler to describe predefined actions or internal processes. These words cannot be used as identifiers such as variable names, method names, class names, or object names.

Example demonstrates how to use keywords

//fileName: keywords.java
// Java Program to demonstrate Keywords
public class keywords {

    public static void main(String[] args)
    {
          // Using final and int keyword
        final int x = 10;

          // Using if and else keywords
          if(x > 10){
           System.out.println("Failed");
        }
          else {
           System.out.println("Successful demonstration"
                              +" of keywords.");
        }
    }
}

Output

Successful demonstration of keywords.

List of Java Keywords (Highlights)

  • Here are some commonly used Java keywords and their purposes:
KeywordDescription
abstractIndicates an abstract class or method
booleanData type for true/false values
breakExits a loop or switch block
byteData type for 8-bit integers
caseDefines a branch in switch statements
catchHandles exceptions from a try block
charData type for single 16-bit Unicode characters
classDeclares a class
continueSkips to the next loop iteration
defaultSpecifies default block in switch, or default interface method
doStarts a do-while loop
doubleData type for 64-bit floating-point numbers
elseDefines alternative path in if statement
enumDeclares an enumerated type
extendsIndicates inheritance
finalSets a value as constant, or prevents override/inheritance
finallyExecutes block after try-catch, regardless of outcome
floatData type for 32-bit floating-point numbers
forStarts a for loop
ifStarts a conditional block
implementsImplements an interface
importImports a class or package
instanceofChecks object type
intData type for 32-bit integers
interfaceDeclares an interface
longData type for 64-bit integers
nativeIndicates method is implemented in platform-specific code
newCreates new objects
nullReference indicating no object
packageDeclares a Java package
privateAccess modifier: only within class
protectedAccess modifier: package & subclasses
publicAccess modifier: accessible everywhere
returnExits a method and optionally returns a value
shortData type for 16-bit integers
staticBelongs to class, not instance
strictfpRestricts floating-point calculation portability
superRefers to superclass
switchMulti-branch decision block
synchronizedRestricts multi-threaded access
thisRefers to current object
throwThrows an exception
throwsDeclares exceptions a method may throw
transientField not serialized
tryStarts exception handling block
voidIndicates absence of return value
volatileMarks variable as possibly modified by multiple threads
whileStarts a while loop
  • Reserved but unused: const, goto, Literals (not keywords): true, false, null

Usage Note

  • Keywords are case-sensitive and always in lowercase.

  • You cannot use keywords as variable, class, or method names.

Using a keyword as a variable name would give error as shown below.

// Java Program to illustrate what if
// we use the keywords as the variable name
// fileName: KeywordsError.java
public class KeywordsError 
{
    public static void main(String[] args)
    {
        // Note "this" is a reserved
        // word in java
        String this = "Hello World!";
        System.out.println(this);
    }
}

Output

KeywordsError.java:10: error: not a statement
        String this = "Hello World!";
        ^
KeywordsError.java:10: error: ';' expected
        String this = "Hello World!";
              ^
2 errors

Literals in Java

  • In Java, literals are fixed values that appear directly in the code and are assigned to variables. They represent constant values of different data types and cannot be changed during program execution.

Types of Literals in Java

Literal TypeDescriptionExample
Integer (Integral)Whole numbers (decimal, octal, hexadecimal, binary bases)int x = 100;, int y = 0x1A;, int z = 0b1010;
Floating-PointNumbers with decimal or exponential notation (float/double)double d = 3.14;, float f = 6.2f;, double e = 1.2e3;
CharacterSingle character in single quotes, including Unicode/escapeschar c = 'A';, char n = '\n';, char u = '\u0041';
StringSequence of characters inside double quotesString s = "Hello, Java!";, String empty = "";
BooleanOnly two possible values: true or falseboolean b = true;, boolean c = false;
NullRepresents the absence of a reference for objectsString s = null;

Details and Examples

1. Integer Literals

  • Decimal: Base 10 (digits 0–9) — int a = 123;

  • Octal: Base 8 (digits 0–7, prefix 0) — int b = 0123;

  • Hexadecimal: Base 16 (digits 0–9 and a–f/A–F, prefix 0x/0X) — int c = 0x7B;

  • Binary: Base 2 (digits 0–1, prefix 0b/0B; Java 7+) — int d = 0b1010;

2. Floating-Point Literals

  • Numbers with decimals or in scientific notation.

  • Default type is double; must append F/f for float.

    • double d = 5.67;

    • float f = 5.67f;

    • double exp = 1.5e2;

3. Character Literals

  • Single character, enclosed in single quotes.

    • char ch = 'Z';

    • Escape sequences (like '\n', '\t')

    • Unicode (e.g., '\u0041' for 'A')

4. String Literals

  • Enclosed in double quotes.

    • String message = "Welcome!";

    • Supports text, whitespace, escape sequences, etc.

5. Boolean Literals

  • Only true and false.

    • boolean isActive = false;

6. Null Literal

  • Only for reference types; means "no object".

    • String text = null;

Summary:

  • Literals allow you to assign constant, in-code values to variables of various types, including numbers, characters, text, and booleans, improving readability and reliability in Java programs.

Happy Learning

Thanks For Reading! :)

SriParthu 💝💥

0
Subscribe to my newsletter

Read articles from sri parthu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sri parthu
sri parthu

Hello! I'm Sri Parthu! 🌟 I'm aiming to be a DevOps & Cloud enthusiast 🚀 Currently, I'm studying for a BA at Dr. Ambedkar Open University 📚 I really love changing how IT works to make it better 💡 Let's connect and learn together! 🌈👋