You are viewing a preview of this lesson. Sign in to start learning
Back to Java

Java Fundamentals & Setup

Establish your development environment and grasp the core concepts that form the foundation of Java programming

Java Fundamentals & Setup

Master Java programming with free flashcards and hands-on practice as you build a strong foundation in this powerful, versatile language. This lesson covers the Java Development Kit (JDK) installation, understanding the Java Virtual Machine (JVM), writing your first program, and essential syntax fundamentalsโ€”everything you need to start your Java journey.

Welcome to Java! โ˜•

Java is one of the world's most popular programming languages, powering everything from Android apps to enterprise systems, web servers, and embedded devices. Created by James Gosling at Sun Microsystems in 1995, Java was designed with a revolutionary principle: "Write Once, Run Anywhere" (WORA). This means Java code can run on any platform that has a Java Virtual Machine, making it incredibly portable and versatile.

๐Ÿ’ก Did you know? Java was originally called "Oak" after a tree outside Gosling's office, then "Green," before finally becoming "Java" after the coffee from Indonesia that the development team loved!

Why Java? ๐ŸŒ

Java remains dominant in professional software development for several compelling reasons:

  • Platform Independence: Java bytecode runs on the JVM, which exists for virtually every operating system
  • Object-Oriented: Organizes code into reusable, modular components
  • Robust & Secure: Strong memory management, exception handling, and security features
  • Rich Ecosystem: Massive library collection (Java API) and frameworks like Spring, Hibernate, and Android
  • Strong Community: Decades of development, extensive documentation, and millions of developers worldwide
  • Enterprise Ready: Scalable, reliable, and battle-tested in mission-critical applications

Core Concepts ๐Ÿ’ป

Understanding the Java Platform Architecture

Java's architecture is fundamentally different from languages like C++ that compile directly to machine code. Here's how it works:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚              JAVA COMPILATION & EXECUTION               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

    ๐Ÿ“ Source Code                  ๐Ÿ’ป Execution
    (MyProgram.java)               (Any Platform)
           โ”‚                              โ†‘
           โ†“                              โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                      โ”‚
    โ”‚   javac      โ”‚                      โ”‚
    โ”‚  (Compiler)  โ”‚                      โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                      โ”‚
           โ”‚                              โ”‚
           โ†“                              โ”‚
    โš™๏ธ Bytecode                           โ”‚
    (MyProgram.class)                     โ”‚
           โ”‚                              โ”‚
           โ†“                              โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
    โ”‚  Java Virtual Machine (JVM)      โ”‚โ”€โ”€โ”˜
    โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
    โ”‚  โ”‚   Just-In-Time Compiler    โ”‚  โ”‚
    โ”‚  โ”‚   (JIT - optimizes code)   โ”‚  โ”‚
    โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
    โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
    โ”‚  โ”‚   Garbage Collector        โ”‚  โ”‚
    โ”‚  โ”‚   (automatic memory mgmt)  โ”‚  โ”‚
    โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
           โ”‚
           โ†“
    โœ… Machine Code (OS-specific)

Key Players:

  1. JDK (Java Development Kit): The complete toolkit for Java developers, including:

    • javac: The compiler that converts .java source files into .class bytecode files
    • java: The launcher that starts the JVM and runs your program
    • javadoc: Generates HTML documentation from code comments
    • jar: Archives multiple class files into a single Java Archive file
    • Standard libraries and development tools
  2. JRE (Java Runtime Environment): Subset of JDK needed only to run Java programs (JVM + libraries, no development tools)

  3. JVM (Java Virtual Machine): The engine that executes Java bytecode, providing platform independence

๐Ÿง  Memory Device - JDK vs JRE vs JVM: Think of it like a kitchen:

  • JVM = The oven (executes/cooks)
  • JRE = Kitchen with oven + utensils (can prepare and cook food)
  • JDK = Full kitchen with oven, utensils, AND recipe creation tools (can create new recipes, not just follow existing ones)

Installing Java - Step by Step ๐Ÿ”ง

Option 1: Oracle JDK (Official)

  1. Visit Oracle's Java Downloads
  2. Choose your platform (Windows, macOS, Linux)
  3. Download the latest LTS (Long-Term Support) version - currently Java 17 or 21
  4. Run the installer and follow prompts
  5. Verify installation:
java -version
javac -version

You should see version information displayed for both commands.

Option 2: OpenJDK (Open Source)

For a free, open-source alternative:

  • Windows/macOS/Linux: Download from Adoptium (Eclipse Temurin)
  • macOS with Homebrew: brew install openjdk
  • Ubuntu/Debian: sudo apt install default-jdk
  • Fedora/RHEL: sudo dnf install java-latest-openjdk-devel

โš ๏ธ Common Setup Mistake: Forgetting to set JAVA_HOME environment variable! Many tools need this:

  • Windows: Set JAVA_HOME to C:\Program Files\Java\jdk-17 (or your install path)
  • macOS/Linux: Add to ~/.bashrc or ~/.zshrc: export JAVA_HOME=/path/to/jdk

Setting Up Your Development Environment ๐Ÿ› ๏ธ

While you can write Java in any text editor and compile from the command line, an Integrated Development Environment (IDE) dramatically improves productivity:

Popular Java IDEs:

IDE Best For Key Features
IntelliJ IDEA Professional development Intelligent code completion, refactoring, debugging tools
Eclipse Enterprise & plugins Extensive plugin ecosystem, free and open-source
Visual Studio Code Lightweight, multi-language Fast, customizable, great for beginners with Extension Pack for Java
NetBeans Beginners, GUI development Easy to use, excellent visual design tools

๐Ÿ’ก Recommendation for Beginners: Start with Visual Studio Code + Java Extension Pack, or IntelliJ IDEA Community Edition (free). Both offer excellent learning experiences.

Your First Java Program - "Hello, World!" ๐ŸŽ‰

Let's break down the classic first program:

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

Line-by-Line Analysis:

  1. public class HelloWorld:

    • public: Access modifier - this class can be accessed from anywhere
    • class: Keyword declaring a class (template for objects)
    • HelloWorld: Class name - MUST match the filename (HelloWorld.java)
    • Java is case-sensitive: helloworld โ‰  HelloWorld
  2. Opening brace {: Begins the class body - everything inside belongs to this class

  3. public static void main(String[] args): The entry point where program execution begins

    • public: Method accessible from outside the class
    • static: Method belongs to the class itself, not to instances (objects)
    • void: Method returns no value
    • main: Special method name that JVM looks for to start execution
    • String[] args: Parameter - array of strings for command-line arguments
  4. System.out.println("Hello, World!");: Prints text to console

    • System: Built-in class for system-level operations
    • out: Static field in System class representing standard output stream
    • println: Method that prints text and adds a newline
    • "Hello, World!": String literal - text in double quotes
    • ;: Statement terminator - required at end of every statement
  5. Closing braces }: Close the method body and class body

๐Ÿ”ง Try this: Create HelloWorld.java, compile and run:

javac HelloWorld.java    # Compiles to HelloWorld.class
java HelloWorld          # Runs the program (no .class extension!)

Output:

Hello, World!

Essential Java Syntax Fundamentals ๐Ÿ“

Comments - Documenting Your Code

// Single-line comment - ignored by compiler

/* Multi-line comment
   spans multiple lines
   useful for longer explanations */

/** JavaDoc comment
  * Used to generate documentation
  * @param describes parameters
  * @return describes return value
  */

Variables and Data Types

Java is statically-typed: you must declare the type of every variable.

Primitive Types (built into the language):

Type Size Range/Values Example
byte 8 bits -128 to 127 byte age = 25;
short 16 bits -32,768 to 32,767 short year = 2024;
int 32 bits ~-2.1B to 2.1B int count = 1000;
long 64 bits Very large numbers long distance = 1000000L;
float 32 bits Decimal numbers float price = 19.99f;
double 64 bits Precise decimals double pi = 3.14159;
boolean 1 bit true or false boolean isActive = true;
char 16 bits Single character char grade = 'A';

Reference Types (objects):

String name = "Java";              // String is a class
int[] numbers = {1, 2, 3, 4, 5};   // Array is a reference type
Scanner input = new Scanner(System.in);  // Custom object

๐Ÿง  Memory Device - Primitives vs References:

  • Primitive = The actual value (like writing "5" on paper)
  • Reference = An address pointing to the value (like writing "stored in box #42")

Naming Conventions

// Classes: PascalCase (capitalize each word)
public class BankAccount { }

// Methods and variables: camelCase (first word lowercase)
int accountBalance = 1000;
public void calculateInterest() { }

// Constants: UPPER_SNAKE_CASE
final double MAX_INTEREST_RATE = 0.05;

// Packages: all lowercase
package com.mycompany.banking;

Basic Input/Output

import java.util.Scanner;  // Import Scanner class

public class InputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");  // print without newline
        String name = scanner.nextLine();        // Read full line
        
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();             // Read integer
        
        System.out.println("Hello, " + name + "! You are " + age + " years old.");
        
        scanner.close();  // Good practice: close resources
    }
}

Operators

// Arithmetic: + - * / % (modulus/remainder)
int result = 10 % 3;  // result = 1 (remainder)

// Comparison: == != < > <= >=
boolean isEqual = (5 == 5);  // true

// Logical: && (AND), || (OR), ! (NOT)
boolean canVote = (age >= 18) && (isCitizen == true);

// Assignment: = += -= *= /= %=
count += 5;  // Same as: count = count + 5

// Increment/Decrement: ++ --
count++;     // count = count + 1

Examples with Detailed Explanations ๐Ÿ”

Example 1: Temperature Converter ๏ธ๐ŸŒก๏ธ

import java.util.Scanner;

public class TemperatureConverter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter temperature in Celsius: ");
        double celsius = scanner.nextDouble();
        
        // Formula: F = (C ร— 9/5) + 32
        double fahrenheit = (celsius * 9.0 / 5.0) + 32;
        
        System.out.println(celsius + "ยฐC = " + fahrenheit + "ยฐF");
        
        scanner.close();
    }
}

Key Points:

  • Uses double for decimal temperature values
  • 9.0 / 5.0 ensures floating-point division (not integer division)
  • String concatenation with + combines text and numbers
  • Always close Scanner to prevent resource leaks

Sample Run:

Enter temperature in Celsius: 25
25.0ยฐC = 77.0ยฐF

Example 2: Simple Calculator with Methods ๐Ÿงฎ

public class Calculator {
    
    // Method to add two numbers
    public static int add(int a, int b) {
        return a + b;
    }
    
    // Method to subtract
    public static int subtract(int a, int b) {
        return a - b;
    }
    
    // Method to multiply
    public static int multiply(int a, int b) {
        return a * b;
    }
    
    // Method to divide
    public static double divide(int a, int b) {
        if (b == 0) {
            System.out.println("Error: Division by zero!");
            return 0;
        }
        return (double) a / b;  // Cast to double for precise division
    }
    
    public static void main(String[] args) {
        int x = 10, y = 3;
        
        System.out.println("Addition: " + add(x, y));        // 13
        System.out.println("Subtraction: " + subtract(x, y)); // 7
        System.out.println("Multiplication: " + multiply(x, y)); // 30
        System.out.println("Division: " + divide(x, y));      // 3.333...
    }
}

Key Points:

  • Methods break code into reusable pieces (modular design)
  • static methods belong to the class, can be called without creating objects
  • Type casting (double) converts int to double for precise division
  • Error handling: Check for division by zero before dividing
  • Return type (int, double, void) must match what method returns

Example 3: Grade Evaluator with Conditionals ๐Ÿ“Š

import java.util.Scanner;

public class GradeEvaluator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your score (0-100): ");
        int score = scanner.nextInt();
        
        String grade;
        String message;
        
        // if-else chain for grade determination
        if (score >= 90) {
            grade = "A";
            message = "Excellent work!";
        } else if (score >= 80) {
            grade = "B";
            message = "Good job!";
        } else if (score >= 70) {
            grade = "C";
            message = "Satisfactory.";
        } else if (score >= 60) {
            grade = "D";
            message = "Needs improvement.";
        } else {
            grade = "F";
            message = "Please see instructor.";
        }
        
        System.out.println("Grade: " + grade);
        System.out.println(message);
        
        // Ternary operator example (compact if-else)
        String status = (score >= 60) ? "PASS" : "FAIL";
        System.out.println("Status: " + status);
        
        scanner.close();
    }
}

Key Points:

  • if-else chain: Conditions evaluated in order, first true condition executes
  • Ternary operator condition ? valueIfTrue : valueIfFalse - compact conditional
  • Variable scope: grade and message declared outside if-else so they're accessible after
  • Order matters: Check highest values first (90 before 80 before 70...)

Example 4: Array Operations and Loops ๐Ÿ”„

public class ArrayDemo {
    public static void main(String[] args) {
        // Initialize array with values
        int[] numbers = {15, 23, 8, 42, 16, 4, 35};
        
        // Calculate sum and find maximum
        int sum = 0;
        int max = numbers[0];  // Start with first element
        
        // Enhanced for loop (for-each)
        System.out.print("Array elements: ");
        for (int num : numbers) {
            System.out.print(num + " ");
            sum += num;
            if (num > max) {
                max = num;
            }
        }
        System.out.println();
        
        // Calculate average
        double average = (double) sum / numbers.length;
        
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + average);
        System.out.println("Maximum: " + max);
        
        // Traditional for loop with index
        System.out.println("\nReversed array:");
        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.print(numbers[i] + " ");
        }
    }
}

Output:

Array elements: 15 23 8 42 16 4 35 
Sum: 143
Average: 20.428571428571427
Maximum: 42

Reversed array:
35 4 16 42 8 23 15

Key Points:

  • Array declaration: type[] name = {values}; or type[] name = new type[size];
  • Array indexing: Zero-based (numbers[0] is first element)
  • Enhanced for loop (for-each): for (type variable : array) - cleaner when you don't need index
  • Traditional for loop: Better when you need index position or reverse iteration
  • array.length property gives number of elements (no parentheses - it's a field, not a method)

Common Mistakes โš ๏ธ

1. Filename Doesn't Match Public Class Name

โŒ Wrong:

// File: MyCode.java
public class MyProgram {  // Class name doesn't match filename!
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

Error: MyCode.java:1: error: class MyProgram is public, should be declared in a file named MyProgram.java

โœ… Correct: Either rename file to MyProgram.java OR make class non-public:

// File: MyCode.java
class MyProgram {  // Not public - now it's okay
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

2. Forgetting Semicolons

โŒ Wrong:

int count = 10  // Missing semicolon!
System.out.println(count)

Error: ';' expected

โœ… Correct:

int count = 10;  // Statement terminator required
System.out.println(count);

3. Using = Instead of == in Conditions

โŒ Wrong:

if (age = 18) {  // Assignment, not comparison!
    System.out.println("Adult");
}

Error: incompatible types: int cannot be converted to boolean

โœ… Correct:

if (age == 18) {  // Double equals for comparison
    System.out.println("Adult");
}

4. String Comparison with ==

โŒ Wrong:

String name1 = "Java";
String name2 = new String("Java");

if (name1 == name2) {  // Compares references, not content!
    System.out.println("Same");
} else {
    System.out.println("Different");  // This prints!
}

โœ… Correct:

if (name1.equals(name2)) {  // Use .equals() for content comparison
    System.out.println("Same");  // Now this prints!
}

5. Array Index Out of Bounds

โŒ Wrong:

int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[5]);  // Array has indices 0-4 only!

Error: ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

โœ… Correct:

int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[4]);  // Last element at index length-1
// Or loop safely:
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

6. Not Closing Scanner/Resources

โŒ Wrong:

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
// Forgot to close - resource leak!

โœ… Correct:

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
scanner.close();  // Always close resources

// Or use try-with-resources (advanced):
try (Scanner scanner = new Scanner(System.in)) {
    String input = scanner.nextLine();
}  // Automatically closes

7. Integer Division Surprise

โŒ Wrong (unintended):

int a = 5, b = 2;
double result = a / b;  // Integer division! result = 2.0 (not 2.5)

โœ… Correct:

int a = 5, b = 2;
double result = (double) a / b;  // Cast one operand to double
// Or: double result = a / (double) b;
// Or: double result = 5.0 / 2;  // Use decimal literal

Key Takeaways ๐ŸŽฏ

โœ… Java Architecture: Source code โ†’ bytecode โ†’ JVM โ†’ platform-specific execution

โœ… JDK Components: Complete development kit with compiler (javac), runtime (java), and tools

โœ… Platform Independence: "Write Once, Run Anywhere" through JVM abstraction

โœ… File Naming: Public class name must match filename exactly (case-sensitive)

โœ… Main Method: public static void main(String[] args) is the program entry point

โœ… Static Typing: Declare variable types explicitly (int count, String name)

โœ… Semicolons Required: Every statement ends with ;

โœ… String Comparison: Use .equals() not == for content comparison

โœ… Array Indexing: Zero-based, last element at array.length - 1

โœ… Resource Management: Always close Scanner and other resources with .close()

๐Ÿ“š Further Study

  1. Oracle Java Tutorials - Official comprehensive guide: https://docs.oracle.com/javase/tutorial/
  2. Java Documentation (JavaDoc) - Complete API reference: https://docs.oracle.com/en/java/javase/17/docs/api/
  3. OpenJDK - Open-source Java platform: https://openjdk.org/

๐Ÿ“‹ Quick Reference Card

Compilejavac FileName.java
Runjava ClassName (no .class extension)
Main methodpublic static void main(String[] args)
PrintSystem.out.println("text");
Variablestype name = value; (e.g., int age = 25;)
String comparisonstr1.equals(str2) NOT str1 == str2
Array lengtharray.length (field, no parentheses)
Single-line comment// comment text
Multi-line comment/* comment */
Input (Scanner)Scanner sc = new Scanner(System.in);