Skip to content

Lesson 2: Variables and Data Types

Lesson 2: Variables and Data Types

Overview:

In Lesson 2, we dive into the world of variables and data types in Java. Variables act as containers for storing data, and understanding the various data types is crucial for efficient programming. We’ll cover how to declare and use variables, and explore fundamental data types such as int, double, char, and boolean.

Key Concepts:

  1. Declaring and Using Variables:
    • Declaration: Variables are declared by specifying the data type followed by the variable name. For example, int myAge; declares an integer variable named myAge.
    • Initialization: Variables can be assigned initial values using the assignment operator (=). For instance, myAge = 25; assigns the value 25 to the variable myAge.
    • Usage: Variables can be used in expressions and statements to perform operations or output values.
int myAge;       // Declaration
myAge = 25;      // Initialization
System.out.println("My age is: " + myAge);  // Usage

Understanding Data Types:

  • int: Represents integer numbers (e.g., 5, -10, 1000).
  • double: Represents floating-point numbers (e.g., 3.14, -0.5, 2.0).
  • char: Represents a single character enclosed in single quotes (e.g., 'A', '5', '%').
  • boolean: Represents true or false values (e.g., true, false).
int myNumber = 42;         // int data type
double pi = 3.14;          // double data type
char grade = 'A';          // char data type
boolean isJavaFun = true;  // boolean data type

Type Inference (var in Java 10 and later):

  • Java 10 introduced local variable type inference using the var keyword. The compiler infers the type based on the assigned value.
var age = 25;              // Compiler infers int type
var price = 19.99;         // Compiler infers double type

Example:

Let’s create a simple Java program that demonstrates the concepts of declaring and using variables with different data types:

public class VariableExample {

    public static void main(String[] args) {

        // Declare and Initialize Variables
        int myAge = 25;
        double myHeight = 5.9;
        char myGrade = 'A';
        boolean isJavaFun = true;

        // Output Values
        System.out.println("My age is: " + myAge);
        System.out.println("My height is: " + myHeight + " feet");
        System.out.println("My grade is: " + myGrade);
        System.out.println("Is Java fun? " + isJavaFun);

        // Type Inference Example
        var mySalary = 50000.0;  // Compiler infers double type
        System.out.println("My salary is: $" + mySalary);
    }
}

This example illustrates the declaration and usage of variables with different data types in Java.