Skip to content

2.2. Variables and Data Types

Variables

A variable is a fundamental concept in any programming language. Think of it as a named container or a labeled box that holds a value, which can be changed during the execution of the program.

  • Purpose: To store data in the computer's memory so that it can be used and manipulated later in the program.
  • Analogy: A variable is like a mailbox. The variable's name is the address on the mailbox, and the data it holds is the mail inside. You can change the mail inside, but the address remains the same.

Declaration and Initialization

Using a variable in Java is a two-step process (which can be combined).

  1. Declaration: This is where you tell the compiler the variable's name and the type of data it will hold. You reserve the "box" and label it.

    • Syntax: dataType variableName;
    • Example: int age; (Declares a variable named age that will hold an integer)
  2. Initialization: This is the first time you assign a value to the variable. You are putting a value into the "box".

    • Syntax: variableName = value;
    • Example: age = 25; (Puts the value 25 into the variable age)

You can also declare and initialize a variable in a single statement, which is the most common practice.

  • Syntax: dataType variableName = value;
  • Example: int score = 100;

Identifiers

Rules for naming variables (identifiers) in Java are strict:

  • Must begin with a letter (a-z, A-Z), underscore (_), or a dollar sign ($).
  • Subsequent characters can be letters, digits, underscores, or dollar signs.
  • Cannot be a Java keyword (e.g., int, class, public).
  • Case-sensitive (myVar and myvar are different).

Conventions (not rules, but best practices for readable code):

  • Use meaningful names (e.g., userName instead of x).
  • Follow camelCase convention: start with a lowercase letter and capitalize the first letter of each subsequent word (e.g., firstName, totalStudentCount).

Primitive Data Types

Java has eight primitive data types, which are the basic building blocks for storing simple values. They are built into the language.

Data TypeSize (bits)DescriptionRangeExample Literals
byte8Very small integer-128 to 127byte b = 100;
short16Small integer-32,768 to 32,767short s = 5000;
int32Standard integer~-2.1 billion to ~2.1 billionint i = 100000;
long64Large integerVery largelong l = 1234567890L; (Note the 'L')
float32Single-precision decimal~6-7 decimal digitsfloat f = 3.14f; (Note the 'f')
double64Double-precision decimal~15 decimal digitsdouble d = 3.1415926535;
char16Single characterUnicode characterchar grade = 'A'; (Single quotes)
boolean~1Logical valuetrue or falseboolean isJavaFun = true;

Key Points:

  • For whole numbers, int is the most commonly used type. Use long only if the number is very large.
  • For decimal numbers, double is the default and most common choice. Use float only if you need to save memory in large arrays.
  • The char data type uses single quotes (' '), not double quotes.
  • The boolean type can only be true or false; it is not a number (unlike in some other languages).

Reference Data Types

Unlike primitive types, reference types do not store the actual data itself. Instead, they store a reference (like a memory address) to the location where the data is stored.

  • Examples: Strings, Arrays, Classes, Interfaces.
  • The String Class: The most common reference type. It is used to store a sequence of characters (text).
    • Example: String greeting = "Hello World";
    • Note: String literals are enclosed in double quotes (" ").

Key Difference: Primitive types hold values. Reference types hold addresses of objects.

Constants

A constant is a variable whose value cannot be changed once it is assigned. You create a constant using the final keyword.

  • Syntax: final dataType CONSTANT_NAME = value;
  • Example: final double PI = 3.14159;
  • Convention: Constant names are written in UPPERCASE letters with underscores separating words (e.g., MAX_SPEED).

Type Casting

Type casting is converting a value from one data type to another. There are two types:

  1. Widening Casting (Implicit): Happens automatically when converting a smaller type to a larger type. It is safe because there is no risk of data loss.

    • Example: int myInt = 9; double myDouble = myInt; // int -> double
  2. Narrowing Casting (Explicit): Must be done manually by the programmer. Converting a larger type to a smaller type risks data loss, so you must explicitly confirm the cast by placing the target type in parentheses before the value.

    • Syntax: targetType variableName = (targetType) value;
    • Example: double myDouble = 9.78; int myInt = (int) myDouble; // double -> int (myInt becomes 9)

The var Keyword (Java 10+)

Since Java 10, you can use var to declare local variables. The compiler infers the variable's type from the initializer on the right-hand side.

  • Example: var message = "Hello"; // compiler infers message as String
  • var count = 10; // compiler infers count as int
  • Important: var can only be used for local variables inside methods when they are declared and initialized on the same line. The variable still has a strong type; it is not "dynamically typed".

Example Code Snippet

java
public class VariablesExample {
    public static void main(String[] args) {
        // Primitive Types
        int studentCount = 30;
        double averageScore = 85.5;
        char finalGrade = 'A';
        boolean isPassed = true;

        // Reference Type (String)
        String className = "Introduction to Java";

        // Constant
        final int MAX_CLASS_SIZE = 40;

        // Type Casting
        double price = 19.99;
        int discountedPrice = (int) price; // Explicit cast, value becomes 19

        // var keyword
        var instructor = "Dr. Smith"; // Inferred as String

        // Printing variables
        System.out.println("Class: " + className);
        System.out.println("Discounted Price: $" + discountedPrice);
    }
}