Java Day 2: Variables and Data Types

Goal of this Day

Today you will learn:

By the end, you will be able to store and use data in Java programs.

Step 1: Primitive Data Types

Primitive types are basic data types in Java.

Step 2: Strings

Strings are used to store text.


String name = "Alice";

Strings are not primitive types, but they are used very often.

Step 3: Declaring and Initializing Variables

To create a variable, you specify its type and name.


int age = 20;
double height = 1.75;
boolean isStudent = true;
char grade = 'A';
String name = "Alice";

Explanation:

Step 4: Using Variables

You can use variables to display information.


System.out.println(name + " is " + age + " years old.");

This combines text and variables into one output.

Step 5: Type Conversion and Casting

Sometimes you need to convert one data type into another.

Example:


double price = 9.99;
int roundedPrice = (int) price;

Explanation:

Practice


int age = 20;
double height = 1.75;
boolean isStudent = true;
char grade = 'A';
String name = "Alice";

System.out.println(name + " is " + age + " years old.");

Exercise

Create a program that calculates the area of a rectangle.

Steps:

Example:


public class Rectangle {
    public static void main(String[] args) {
        double width = 5.0;
        double height = 3.0;

        double area = width * height;

        System.out.println("Area: " + area);
    }
}