Introduction

Welcome to your first Java program! In this lecture, we’ll start with the classic “Hello World” and then explore Java’s fundamental building blocks: variables, data types, and basic syntax. By the end, you’ll understand how Java code is structured and be able to create simple programs.

infoMake sure you’ve completed the ‘Setting Up Java Development Environment’ lecture before starting this one. You’ll need Java and Maven installed.

The Classic Hello World

Creating Your First Java Program

Let’s start with the simplest possible Java program:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Understanding the Structure

Let’s break down what each part means:

public class HelloWorld
  • public: Access modifier - this class can be accessed from anywhere
  • class: Keyword that defines a class (blueprint for objects)
  • HelloWorld: Name of the class (must match the filename: HelloWorld.java)
public static void main(String[] args)
  • public: Method can be called from anywhere
  • static: Method belongs to the class, not an instance
  • void: Method doesn't return a value
  • main: Special method name - Java looks for this to start the program
  • String[] args: Array of command-line arguments
System.out.println("Hello, World!")
  • System: Built-in class for system-level operations
  • out: Static field representing standard output stream
  • println: Method that prints text and moves to a new line
  • "Hello, World!": String literal to be printed

errorJava is case-sensitive! ‘public’ and ‘Public’ are different. The main method must be exactly ‘main’ (lowercase).

Compiling and Running

Create the File

Save your code in a file named HelloWorld.java (filename must match the class name).

Compile

javac HelloWorld.java

This creates HelloWorld.class (bytecode).

Run

java HelloWorld

Output: Hello, World!

Java Syntax Fundamentals

Statements and Semicolons

Every statement in Java must end with a semicolon (;):

System.out.println("This is a statement");
int x = 5;
String name = "Alice";

Code Blocks and Braces

Code blocks are enclosed in curly braces {}:

public class Example {    // Class block
    public static void main(String[] args) {  // Method block
        if (true) {        // If block
            System.out.println("Inside block");
        }
    }
}

Comments

// Single-line comment

/*
 * Multi-line comment
 * Can span multiple lines
 */

/**
 * Javadoc comment (for documentation)
 * @param args command line arguments
 */
public static void main(String[] args) {
    // Code here
}

Variables in Java

Variables are containers for storing data values. In Java, every variable must have a type.

Variable Declaration

// Declare a variable
int age;

// Declare and initialize
int age = 25;

// Declare multiple variables
int x, y, z;
int a = 5, b = 10, c = 15;

Variable Naming Rules

Must follow:

Best practices:

// Good variable names
int studentAge;
String firstName;
double accountBalance;
boolean isActive;

// Avoid
int a;  // Too short, unclear
int student_age;  // Use camelCase instead of snake_case
int 2fast;  // Cannot start with digit

Data Types in Java

Java is a strongly-typed language, meaning every variable must have a declared type. Java has two categories of data types:

Primitive Data Types

Primitive types are the most basic data types built into Java.

Integer Types

Type Size Range Example
byte 8 bits -128 to 127 byte age = 25;
short 16 bits -32,768 to 32,767 short year = 2025;
int 32 bits -2³¹ to 2³¹-1 int population = 1000000;
long 64 bits -2⁶³ to 2⁶³-1 long distance = 123456789L;
byte smallNumber = 100;
short mediumNumber = 10000;
int regularNumber = 1000000;
long bigNumber = 9876543210L;  // Note the 'L' suffix

info_outlineUse ‘int’ for most integer calculations unless you have a specific reason to use a different type.

Floating-Point Types

Type Size Precision Example
float 32 bits ~7 decimal digits float price = 19.99f;
double 64 bits ~15 decimal digits double pi = 3.14159;
float temperature = 98.6f;  // Note the 'f' suffix
double preciseValue = 3.141592653589793;

Character Type

char letter = 'A';
char symbol = '$';
char unicode = '\u0041';  // Unicode for 'A'

Boolean Type

boolean isJavaFun = true;
boolean isRaining = false;

Reference Data Types

Reference types refer to objects. The most common reference type is String.

Strings

String message = "Hello, Java!";
String name = "Alice";
String empty = "";

// String methods
int length = message.length();           // 12
String upper = message.toUpperCase();    // "HELLO, JAVA!"
String lower = message.toLowerCase();    // "hello, java!"
boolean contains = message.contains("Java");  // true

Type Conversion

Implicit Conversion (Widening)

Smaller types are automatically converted to larger types:

int myInt = 100;
long myLong = myInt;    // int to long (automatic)
float myFloat = myInt;  // int to float (automatic)

Explicit Conversion (Narrowing)

Larger types must be explicitly cast to smaller types:

double myDouble = 9.78;
int myInt = (int) myDouble;  // 9 (loses decimal part)

long bigNum = 1000000L;
int smallNum = (int) bigNum;  // Works if value fits in int range

Putting It Together: A Real Example

Let’s create a program that demonstrates variables and data types:

public class PersonInfo {
    public static void main(String[] args) {
        // Personal information variables
        String firstName = "John";
        String lastName = "Doe";
        int age = 25;
        double height = 5.9;  // in feet
        boolean isStudent = true;
        char grade = 'A';
        
        // Display the information
        System.out.println("=== Personal Information ===");
        System.out.println("Name: " + firstName + " " + lastName);
        System.out.println("Age: " + age + " years old");
        System.out.println("Height: " + height + " feet");
        System.out.println("Student Status: " + isStudent);
        System.out.println("Grade: " + grade);
        
        // Perform calculations
        int ageInMonths = age * 12;
        double heightInInches = height * 12;
        
        System.out.println("\n=== Calculations ===");
        System.out.println("Age in months: " + ageInMonths);
        System.out.println("Height in inches: " + heightInInches);
        
        // String concatenation
        String fullName = firstName + " " + lastName;
        System.out.println("\nFull name: " + fullName);
    }
}

Output:

=== Personal Information ===
Name: John Doe
Age: 25 years old
Height: 5.9 feet
Student Status: true
Grade: A

=== Calculations ===
Age in months: 300
Height in inches: 70.8

Full name: John Doe

Operators in Java

Arithmetic Operators

int a = 10, b = 3;

int sum = a + b;        // 13 (addition)
int diff = a - b;       // 7  (subtraction)
int product = a * b;    // 30 (multiplication)
int quotient = a / b;   // 3  (integer division)
int remainder = a % b;  // 1  (modulus)

// Increment and decrement
int x = 5;
x++;  // x is now 6 (post-increment)
++x;  // x is now 7 (pre-increment)
x--;  // x is now 6 (post-decrement)
--x;  // x is now 5 (pre-decrement)

Assignment Operators

int x = 10;

x += 5;   // x = x + 5;  (15)
x -= 3;   // x = x - 3;  (12)
x *= 2;   // x = x * 2;  (24)
x /= 4;   // x = x / 4;  (6)
x %= 4;   // x = x % 4;  (2)

Comparison Operators

int a = 10, b = 5;

boolean result1 = (a == b);  // false (equal to)
boolean result2 = (a != b);  // true  (not equal to)
boolean result3 = (a > b);   // true  (greater than)
boolean result4 = (a < b);   // false (less than)
boolean result5 = (a >= b);  // true  (greater than or equal to)
boolean result6 = (a <= b);  // false (less than or equal to)

Logical Operators

boolean x = true, y = false;

boolean and = x && y;   // false (logical AND)
boolean or = x || y;    // true  (logical OR)
boolean not = !x;       // false (logical NOT)

Constants

Use the final keyword to create constants (values that cannot be changed):

final double PI = 3.14159;
final int MAX_STUDENTS = 30;
final String APP_NAME = "My Java App";

// This would cause a compiler error:
// PI = 3.14;  // Error: cannot assign a value to final variable

Common Mistakes to Avoid

1. Missing Semicolons

// Wrong
int age = 25
System.out.println(age)

// Correct
int age = 25;
System.out.println(age);

2. Case Sensitivity

// Wrong
INT age = 25;        // 'INT' is not a valid type
System.Out.Println("Hello");  // 'Out' should be 'out'

// Correct
int age = 25;
System.out.println("Hello");

3. Uninitialized Variables

// Wrong - will not compile
int age;
System.out.println(age);  // Error: variable might not have been initialized

// Correct
int age = 0;  // or any default value
System.out.println(age);

4. String Comparison

String name1 = "Alice";
String name2 = "Alice";

// Wrong way (compares references, not content)
if (name1 == name2) {
    // May not work as expected
}

// Correct way (compares content)
if (name1.equals(name2)) {
    System.out.println("Names are equal");
}

5. Integer Division

// Unexpected result
int result = 5 / 2;  // result is 2 (not 2.5!)

// Correct for decimal result
double result = 5.0 / 2.0;  // result is 2.5
// or
double result = (double) 5 / 2;  // result is 2.5

Practice Exercises

Exercise 1: Calculator

Create a program that declares two numbers and performs all arithmetic operations:

public class Calculator {
    public static void main(String[] args) {
        int num1 = 20;
        int num2 = 5;
        
        // TODO: Perform and print:
        // - Addition
        // - Subtraction
        // - Multiplication
        // - Division
        // - Modulus
    }
}

Exercise 2: Temperature Converter

Convert Celsius to Fahrenheit using the formula: F = (C × 9/5) + 32

public class TempConverter {
    public static void main(String[] args) {
        double celsius = 25.0;
        
        // TODO: Calculate and print Fahrenheit
    }
}

Exercise 3: Student Info

Create a program that stores and displays student information:

Summary

Congratulations! You’ve learned the fundamentals of Java programming.

Key takeaways:

What’s Next?

In the next lecture, we’ll learn about:

  1. Maven project structure - organizing code professionally
  2. Creating a multi-class project - working with multiple files
  3. Using dependencies - leveraging external libraries
  4. Build automation - compiling and packaging with Maven

Quick Reference

// Variable declaration and initialization
int age = 25;
double price = 19.99;
boolean isActive = true;
char grade = 'A';
String name = "Alice";

// Arithmetic
int sum = 10 + 5;
int diff = 10 - 5;
int product = 10 * 5;
int quotient = 10 / 5;
int remainder = 10 % 3;

// Printing
System.out.println("Hello");  // With newline
System.out.print("Hello");    // Without newline

// String concatenation
String message = "Hello, " + name + "!";

infoPractice is key! Try modifying the examples, create your own programs, and experiment with different data types and operators.