Java Essentials · Месяц 1

Variables & Primitive Types

Goal: store data in variables, know the primitive types and convert between them. Duration: 90 min

1. What is a variable?

A variable is a named box in memory that holds a value. In Java every variable has a type, and the type never changes.

int age = 26;          // type  name = value;
String city = "Baku";
age = 27;              // we can change the value...
// age = "old";        // ...but not the type → compile error

Declaring and assigning separately:

int balance;           // declaration
balance = 1000;        // assignment (initialization)

2. The 8 primitive types

Type Size Example Use for
byte 8 bit byte b = 100; raw data, files
short 16 bit short s = 30000; rarely used
int 32 bit int count = 42; default for whole numbers (±2.1 billion)
long 64 bit long id = 9_000_000_000L; ids, timestamps, big numbers
float 32 bit float f = 3.14f; rarely used
double 64 bit double price = 19.99; default for decimals
boolean — boolean active = true; yes/no
char 16 bit char grade = 'A'; a single character

Notes:

  • long literals end with L, float literals with f.
  • Underscores make big numbers readable: 1_000_000.
  • char uses single quotes, String uses double quotes.
  • String is not primitive; it is a class (lesson 4).

⚠️ Money: double is imprecise (0.1 + 0.2 = 0.30000000000000004). In real banking code we use BigDecimal. For learning, double is fine.

3. Type casting

Widening (automatic, safe)

int i = 100;
long l = i;        // int → long
double d = l;      // long → double

Narrowing (manual, may lose data)

double price = 19.99;
int whole = (int) price;      // 19, decimals are cut, not rounded
long big = 3_000_000_000L;
int broken = (int) big;       // overflow! → -1294967296

Integer division trap

int a = 7, b = 2;
System.out.println(a / b);           // 3   (int / int = int)
System.out.println((double) a / b);  // 3.5

4. var: local type inference

var name = "Anar";     // compiler infers String
var total = 0.0;       // double

Use var only when the type is obvious from the right side.

5. Constants and naming

final double VAT_RATE = 0.18;   // cannot be reassigned
// VAT_RATE = 0.2;              // compile error
Kind Convention Example
variable camelCase totalPrice, isActive
constant UPPER_SNAKE_CASE MAX_ATTEMPTS
class PascalCase BankAccount

Good names explain what the value is: int d ❌, int daysUntilPayment ✅.

6. Step by step: a shopping calculation

public class Checkout {
    public static void main(String[] args) {
        String product = "Mechanical keyboard";
        double price = 120.50;
        int quantity = 2;
        final double DISCOUNT = 0.10;
        final double VAT = 0.18;

        double subtotal = price * quantity;
        double afterDiscount = subtotal * (1 - DISCOUNT);
        double total = afterDiscount * (1 + VAT);

        System.out.println("Product:  " + product);
        System.out.println("Subtotal: " + subtotal);
        System.out.println("Total:    " + total);
    }
}

7. Common mistakes

  • ❌ Using a variable before assigning it: int x; System.out.println(x); → compile error.
  • ❌ long n = 3000000000; → error, add L.
  • ❌ Expecting (int) 9.99 to be 10. It is 9.
  • ❌ char c = "A"; → use single quotes.

8. Exercises

  1. Declare variables for a bank customer: name, age, balance, isVip, initial of surname. Print them.
  2. Convert 37.5 °C to Fahrenheit (F = C * 9 / 5 + 32).
  3. Given int totalMinutes = 135, print 2 h 15 min.
  4. Show the overflow: int max = Integer.MAX_VALUE; max + 1 and explain the result.

9. Homework

Salary calculator: gross salary 2500 AZN, income tax 14%, social insurance 3%, unemployment insurance 0.5%. Print each deduction and the net salary.

10. Self-check

  1. Which type would you use for a customer id in a big bank? Why?
  2. What is printed: System.out.println(5 / 2);?
  3. What is the difference between widening and narrowing?
  4. Is String a primitive type?
Answers
  1. long: int can overflow after 2.1 billion.
  2. 2 (integer division).
  3. Widening goes to a bigger type and is automatic and safe; narrowing needs a cast and may lose data.
  4. No, it is a class (reference type).