Skip to main content

02 - Data Types and Flow Control

Java primitive types (int, long, double, boolean, char), variables and constants, operators, if/switch/for/while control structures and casting.

What do you think about this article?

At a Glance

Java primitive types (int, long, double, boolean, char), variables and constants, operators, if/switch/for/while control structures and casting.

Data Types in Java

Java is a strongly typed language: every variable must have a declared type and the compiler verifies that operations are compatible with that type. This prevents many runtime errors.

What You Will Learn

  • Primitive types and their ranges
  • Variables, constants and scope
  • Arithmetic, logical and relational operators
  • Control structures: if, switch, for, while
  • Casting and type conversions

Primitive Types

Java has 8 primitive types, divided into 4 categories: integers, decimals, characters and booleans.

Integer Types

Integer Types with Range
// byte: 8 bit, from -128 to 127
byte studentAge = 16;
byte maxGrade = 127;

// short: 16 bit, from -32,768 to 32,767
short birthYear = 2008;
short daysInYear = 365;

// int: 32 bit, from -2^31 to 2^31 - 1 (about 2 billion)
int classPopulation = 25;
int studentId = 123456789;

// long: 64 bit, for very large numbers
long worldPopulation = 8_000_000_000L; // note the L suffix
long foundationMilliseconds = 1704067200000L;

Summary Table

Type Bits Range Typical Use
byte 8 -128 to 127 Grades, age
short 16 -32,768 to 32,767 Years, days
int 32 about ±2 billion Counters, IDs
long 64 very large numbers Timestamps, population

Decimal Types (Floating Point)

float and double
// float: 32 bit, single precision (6-7 digits)
float gradeAverage = 7.5f; // note the f suffix
float temperature = 36.6f;

// double: 64 bit, double precision (15-16 digits)
double pi = 3.141592653589793;
double mathAverage = 8.25;
double passPercentage = 87.5;

When to use float vs double

  • double: Default for decimals, more precise
  • float: Only when memory savings needed (graphics, games)
  • Never for money: Use BigDecimal for financial calculations

Characters and Booleans

char and boolean
// char: 16 bit, a single Unicode character
char initial = 'M';
char letterGrade = 'A';
char symbol = '€';
char unicode = '\u0041'; // 'A' in Unicode

// boolean: true or false
boolean isPassing = true;
boolean hasDebts = false;
boolean isAdult = studentAge >= 18;

Variables and Constants

Declaration and Initialization

Variables
// Declaration
int grade;

// Initialization
grade = 8;

// Declaration and initialization together
int anotherGrade = 9;

// Multiple declarations
int italian = 7, math = 8, history = 6;

// var (Java 10+): type inference
var studentName = "John Smith"; // infers String
var classAverage = 7.5;         // infers double

Constants with final

Constants
// Constants: immutable value
final int MAX_GRADE = 10;
final int MIN_GRADE = 1;
final double PASSING_THRESHOLD = 6.0;
final String SCHOOL_NAME = "Einstein High School";

// Attempting to modify a constant causes compilation error
// MAX_GRADE = 11; // ERROR!

Variable Scope

Variable Visibility
public class ClassRegistry {
    // Instance variable (visible throughout the class)
    private int studentCount = 25;

    public void printStatistics() {
        // Local variable (visible only in the method)
        int sumOfGrades = 0;

        for (int i = 0; i < studentCount; i++) {
            // Block variable (visible only in the for loop)
            int currentGrade = getGrade(i);
            sumOfGrades += currentGrade;
        }

        // currentGrade is no longer accessible here!
        double average = (double) sumOfGrades / studentCount;
        System.out.println("Average: " + average);
    }
}

Operators

Arithmetic Operators

Mathematical Operations
int a = 10, b = 3;

int sum = a + b;         // 13
int difference = a - b;  // 7
int product = a * b;     // 30
int quotient = a / b;    // 3 (integer division!)
int remainder = a % b;   // 1 (modulo)

// Decimal division
double realQuotient = (double) a / b; // 3.333...

// Increment and decrement
int grade = 7;
grade++;       // 8 (post-increment)
++grade;       // 9 (pre-increment)
grade--;       // 8 (post-decrement)

// Compound operators
grade += 2;    // equivalent to: grade = grade + 2
grade *= 2;    // equivalent to: grade = grade * 2

Relational Operators

Comparisons
int grade = 7;
int passingGrade = 6;

boolean greater = grade > passingGrade;      // true
boolean less = grade < passingGrade;         // false
boolean equal = grade == passingGrade;       // false
boolean notEqual = grade != passingGrade;    // true
boolean greaterOrEqual = grade >= passingGrade; // true
boolean lessOrEqual = grade <= passingGrade;    // false

Logical Operators

Boolean Logic
boolean passing = grade >= 6;
boolean excellent = grade >= 9;
boolean present = true;

// Logical AND (both must be true)
boolean promotable = passing && present; // true

// Logical OR (at least one must be true)
boolean awarded = excellent || present; // true

// Logical NOT (inverts the value)
boolean absent = !present; // false

// Short-circuit evaluation
// If the first condition is false, the second is not evaluated
boolean result = false && expensiveMethod(); // expensiveMethod() not executed

Flow Control

if / else

Conditions
int grade = 7;

// Simple if
if (grade >= 6) {
    System.out.println("Passed");
}

// if-else
if (grade >= 6) {
    System.out.println("Passed");
} else {
    System.out.println("Failed");
}

// if-else if-else (school grade evaluation)
if (grade >= 9) {
    System.out.println("Excellent");
} else if (grade >= 7) {
    System.out.println("Good");
} else if (grade >= 6) {
    System.out.println("Satisfactory");
} else {
    System.out.println("Insufficient");
}

// Ternary operator (compact if)
String outcome = grade >= 6 ? "Passed" : "Failed";

switch

Classic Switch
int month = 9;
String monthName;

switch (month) {
    case 1:
        monthName = "January";
        break;
    case 2:
        monthName = "February";
        break;
    case 9:
        monthName = "September - School starts!";
        break;
    case 6:
    case 7:
    case 8:
        monthName = "Summer vacation";
        break;
    default:
        monthName = "Other month";
}
Switch Expression (Java 14+)
// Modern syntax with arrow
String assessment = switch (grade) {
    case 10 -> "Outstanding";
    case 9 -> "Excellent";
    case 8 -> "Good";
    case 7 -> "Fair";
    case 6 -> "Satisfactory";
    default -> "Insufficient";
};

// With blocks
String description = switch (grade) {
    case 10, 9 -> {
        System.out.println("Congratulations!");
        yield "Excellence";
    }
    case 8, 7 -> "Good performance";
    default -> "Needs improvement";
};

for Loop

for Loops
// Classic for
System.out.println("Student list:");
for (int i = 1; i <= 5; i++) {
    System.out.println("Student " + i);
}

// Descending for
System.out.println("Countdown:");
for (int i = 10; i >= 1; i--) {
    System.out.println(i);
}

// for-each (enhanced for)
int[] grades = {7, 8, 6, 9, 8};
int sum = 0;
for (int g : grades) {
    sum += g;
}
System.out.println("Sum of grades: " + sum);

while and do-while Loops

While
// while: checks BEFORE executing
int attempts = 0;
int minimumGrade = 6;
int obtainedGrade = 4;

while (obtainedGrade < minimumGrade && attempts < 3) {
    System.out.println("Attempt " + (attempts + 1));
    obtainedGrade++; // simulate improvement
    attempts++;
}

// do-while: executes AT LEAST ONCE
int response;
do {
    System.out.println("Menu: 1=Grades, 2=Average, 0=Exit");
    response = readInput();
} while (response != 0);

break and continue

Flow Control in Loops
// break: exits the loop
int[] grades = {7, 8, 3, 9, 8};
for (int grade : grades) {
    if (grade < 4) {
        System.out.println("Found severely insufficient grade!");
        break; // exits the loop
    }
}

// continue: skips to next iteration
for (int grade : grades) {
    if (grade < 6) {
        continue; // skip insufficient grades
    }
    System.out.println("Passing grade: " + grade);
}

Casting and Conversions

Type Conversions
// Widening (implicit): from smaller to larger type
int integerGrade = 8;
double doubleGrade = integerGrade; // 8.0 (automatic)

// Narrowing (explicit): from larger to smaller type
double average = 7.8;
int integerAverage = (int) average; // 7 (truncation, requires cast)

// Watch out for overflow!
int largeNumber = 130;
byte small = (byte) largeNumber; // -126 (overflow!)

// String -> number conversion
String gradeString = "8";
int grade = Integer.parseInt(gradeString);
double averageDouble = Double.parseDouble("7.5");

// Number -> String conversion
String result = String.valueOf(grade);
String other = Integer.toString(grade);
String concatenated = "" + grade; // less efficient

Complete Example: Report Card Calculation

ReportCardCalculation.java
package edu.school.registry;

public class ReportCardCalculation {

    public static void main(String[] args) {
        // Student data
        final String STUDENT_NAME = "John Smith";
        final String CLASS = "3A";

        // Grades by subject
        int english = 7;
        int math = 8;
        int history = 6;
        int spanish = 9;
        int science = 7;

        // Grades array
        int[] grades = {english, math, history, spanish, science};
        String[] subjects = {"English", "Math", "History", "Spanish", "Science"};

        // Calculate statistics
        int sum = 0;
        int maxGrade = grades[0];
        int minGrade = grades[0];
        int passingCount = 0;

        for (int grade : grades) {
            sum += grade;
            if (grade > maxGrade) maxGrade = grade;
            if (grade < minGrade) minGrade = grade;
            if (grade >= 6) passingCount++;
        }

        double average = (double) sum / grades.length;

        // Print report card
        System.out.println("╔════════════════════════════════════╗");
        System.out.println("║           SCHOOL REPORT CARD       ║");
        System.out.println("╠════════════════════════════════════╣");
        System.out.printf("║ Student:  %-24s ║%n", STUDENT_NAME);
        System.out.printf("║ Class:    %-24s ║%n", CLASS);
        System.out.println("╠════════════════════════════════════╣");

        for (int i = 0; i < subjects.length; i++) {
            String assessment = switch (grades[i]) {
                case 10, 9 -> "Excellent";
                case 8 -> "Good";
                case 7 -> "Fair";
                case 6 -> "Satisfactory";
                default -> "Insufficient";
            };
            System.out.printf("║ %-12s: %2d (%s)%n", subjects[i], grades[i], assessment);
        }

        System.out.println("╠════════════════════════════════════╣");
        System.out.printf("║ Average:  %.2f                     ║%n", average);
        System.out.printf("║ Max grade: %d                       ║%n", maxGrade);
        System.out.printf("║ Min grade: %d                       ║%n", minGrade);
        System.out.println("╠════════════════════════════════════╣");

        // Final outcome
        String outcome;
        if (passingCount == grades.length && average >= 6) {
            outcome = "PASSED";
        } else if (passingCount >= grades.length - 1) {
            outcome = "CONDITIONAL";
        } else {
            outcome = "NOT PASSED";
        }

        System.out.printf("║ OUTCOME: %-26s ║%n", outcome);
        System.out.println("╚════════════════════════════════════╝");
    }
}

Conclusion

In this article we covered Java's primitive data types, variables and constants, operators and flow control structures.

In the next article we will dive into methods and basic data structures: how to define reusable functions and work with arrays.

Key Points to Remember

  • 8 primitive types: byte, short, int, long, float, double, char, boolean
  • final: Makes a variable constant
  • Scope: Variables are only visible within their block
  • Switch expression: Java 14+ supports arrow syntax
  • for-each: Preferred when index is not needed
  • Casting: Required for narrowing conversions

Frequently asked questions

What are the main categories of primitive types in Java?

The main categories of primitive types in Java are integers, decimals, characters, and booleans.

How many integer types does Java have?

This information is not provided in the article.

Can variables be initialized without a declared type in Java?

No, every variable must have a declared type in Java.

What will be covered in the next article related to this topic?

The next article will cover methods and basic data structures, including how to define reusable functions and work with arrays.

Sources and further reading

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects