Week 1 - Introduction to Java

What is an Algorithm?

An algorithm is a list of steps for solving a problem. Think of an algorithm like a recipe—it provides clear instructions to accomplish a specific task. For example, baking cookies requires several steps:

  1. Mix the dry ingredients
  2. Cream the butter and sugar
  3. Beat in the eggs
  4. Stir in the dry ingredients
  5. Set the oven temperature
  6. Place the cookies into the oven
  7. Allow the cookies to bake

Java Basics

Java is an object-oriented programming language developed by Sun Microsystems (now acquired by Oracle). Here are some key characteristics:

  • Compiled language: Java code is converted to bytecode before execution
  • Platform-independent: “Write once, run anywhere” due to the Java Virtual Machine (JVM)
  • Case-sensitive: Variables named number and Number would be considered different variables in Java
  • Strongly typed: Variables must be declared with specific data types

Structure of a Java Program

A basic Java program consists of:

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

Let’s break this down:

  1. Class definition: public class HelloWorld { ... }
    • Each Java file should contain one primary class with the same name as the file
    • The filename would be HelloWorld.java
  2. Main method: public static void main(String[] args) { ... }
    • Every Java program needs a main method—this is where execution begins
    • public: The method is accessible from outside the class
    • static: The method belongs to the class itself, not to instances of the class
    • void: The method doesn’t return any value
    • main: The name of the method that JVM looks for to start execution
    • String[] args: Parameter that accepts command-line arguments
  3. Statement: System.out.println("Hello World!");
    • System: A built-in Java class with useful tools
    • out: Refers to the standard output stream (the console)
    • println: A method that prints text and then moves to a new line
    • Note the semicolon (;) at the end - all statements in Java end with semicolons

Printing to the Console

Java offers two primary methods for printing text:

  1. System.out.println("Text here"); - Prints text and moves to a new line
  2. System.out.print("Text here"); - Prints text without moving to a new line

Example:

System.out.println("First line");
System.out.println("Second line");

Output:

First line
Second line

Example with print:

System.out.print("Hello ");
System.out.print("World!");

Output:

Hello World!

Comments in Java

Comments are notes in your code that the compiler ignores. They help make your code more readable for humans.

Java has three types of comments:

  1. Single-line comments:
    // This is a single-line comment
    
  2. Multi-line comments:
    /* This comment can
    span multiple
    lines */
    
  3. JavaDoc comments (used for documentation):
    /**
     * This is a JavaDoc comment
     * Used for generating API documentation
     */
    

Whitespace and Formatting

Java does not interpret whitespace (spaces, tabs, newlines). However, proper indentation and spacing make your code more readable. Compare:

// Hard to read
public class BadFormat{public static void main(String[]args){System.out.println("Hello");System.out.println("World!");}}

// Easy to read
public class GoodFormat {
    public static void main(String[] args) {
        System.out.println("Hello");
        System.out.println("World!");
    }
}

Semicolons

Unlike whitespace, semicolons are very important in Java. They mark the end of a statement (a single instruction). Forgetting a semicolon will result in a compilation error.

System.out.println("This needs a semicolon");

Compilation Process

Java is a compiled language, which means your code goes through several steps before execution:

  1. You write code in a .java file
  2. The Java compiler (javac) converts your code to bytecode (.class files)
  3. The Java Virtual Machine (JVM) executes the bytecode

This process allows Java to catch many errors before your program runs and enables the “write once, run anywhere” capability.

Primitive Data Types

Java has eight primitive data types that store simple values:

Data Type Size Range Example
byte 1 byte -128 to 127 byte score = 100;
short 2 bytes -32,768 to 32,767 short population = 30000;
int 4 bytes -2,147,483,648 to 2,147,483,647 int count = 1000000;
long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long distance = 9876543210L;
float 4 bytes   float gpa = 3.5f;
double 8 bytes   double pi = 3.14159265359;
char 2 bytes Single Unicode character char grade = 'A';
boolean 1 bit true or false boolean isStudent = true;

Notes:

  • For long values, add ‘L’ at the end
  • For float values, add ‘f’ at the end
  • char values are enclosed in single quotes '
  • String is NOT a primitive data type (it’s a class) and uses double quotes "

Self-Assessment Questions

What is the correct file extension for a Java source file?
The correct file extension is .java. For example, a class named HelloWorld should be saved in a file named HelloWorld.java.
What is the difference between System.out.print() and System.out.println()?
System.out.print() prints text without moving to a new line, while System.out.println() prints text and then moves to a new line for subsequent output.
Why must the class name match the filename in Java?
In Java, each public class must be defined in a file with the same name as the class (followed by the .java extension). This naming convention helps the Java compiler locate the class and is enforced by the language.
Write a Java statement that prints your name and your major on separate lines.
System.out.println("Your Name");
System.out.println("Computer Science");
Why is Java considered platform-independent?
Java is considered platform-independent because Java programs are compiled into bytecode, which can run on any device that has a Java Virtual Machine (JVM). This is often summarized as "Write once, run anywhere."
What error would occur if you forget to include a semicolon at the end of a statement in Java?
If you forget to include a semicolon at the end of a statement, you will get a compilation error, typically something like missing semicolon or ';' expected. The program will not compile until the error is fixed.
How would you write a multi-line comment in Java?
A multi-line comment in Java is written using /* to start the comment and */ to end it:
/* This is
   a multi-line
   comment */
Which primitive data type would be most appropriate for storing a person's age? (bonus)
There is no single right answer for this one. According to the New York Times, the oldest person was recorded to die at 122 years old. So, byte could work for typical scenarios since it stores values from -128 to 127, and uses only 1 byte of memory, making it the most memory efficient option.
However, what if someone unexpectedly lives longer than 127 years? In that case, short would be the better choice since it stores values from -32,768 to 32,767, which is more than sufficient for any realistic human lifespan. It only uses 2 bytes of memory, which is still much more efficient than int (4 bytes) or long (8 bytes).
The most appropriate choice depends on how you balance memory efficiency against future-proofing your application.