SE 109 - Lecture 3: Introduction to Java
Outline of Lecture 3
- Introduction of Java
- Brief Description of Java
- History of Java
- Java Environment & Architecture
- Basic Java Program Elements & Structure
- Compiling and Running Java Programs
Introduction to Java
- Java is related to C++, which is a descendant of C. Much of Java's syntax is derived from C/C++.
- Many of Java's object-oriented features were influenced by C++.
- Java was initially created not primarily for the internet, but for platform-independent software embedded in electronic devices (like microwaves, remote controls). The need arose partly from limitations in C/C++.
- Java was designed to solve a set of problems encountered with C++ (like memory management, portability) rather than replace it entirely.
Definition: Java is a class-based, general-purpose, object-oriented programming language designed to have minimal implementation dependencies.
Core Principle: WORA (Write Once, Run Anywhere) - Compiled Java code (bytecode) can run on any platform with a compatible Java Virtual Machine (JVM) without recompilation.
It is widely used and particularly designed for internet applications.
(Slides 4, 5, 6, 7 showed Java's prevalence: standard for development, mobile apps, enterprise software, cloud platform, 9+ million developers, 3 billion phones).
History of Java
- Started by "The Green Team" at Sun Microsystems, led by James Gosling (often called the "Father of Java").
- Originally called "Oak". Aimed at creating a platform-independent language for consumer electronic devices with different CPUs.
- Initial concept faced challenges with consumer device adoption.
- The rise of the World Wide Web provided a new market. The Oak language was well-suited for web multimedia components (Applets).
- Renamed to "Java" in 1995.
(Slide 8 showed a picture of James Gosling. Slide 9 discussed the initial concept and shift to web focus).
Why Java was created?
- Troubles with C/C++ (memory management, portability issues).
- C/C++ are not inherently portable or platform-independent.
- Emergence of the WWW demanded portable programs (Applets).
- Need for improved Portability and Security.
Timeline Highlights:
Year | Development |
1990 | Sun Microsystems team (Gosling) developed software for electronic devices. |
1991 | New language "Oak" introduced, using C++. |
1993 | WWW emerged, transforming the internet. |
1994 | Sun developed "HotJava" web browser to run applet programs. |
1995 | Oak was renamed to Java. |
1996 | Java established as an Object-Oriented Programming Language (OOPL). |
1996 | JDK 1.0 released. |
1997 | JDK 1.1 released. |
1998 | JDK 1.2 (Beginning of J2SE, J2EE, J2ME naming). |
... | Subsequent versions released (JDK 1.4, 5, 6, 7, 8, 9...). |
2010 | Oracle acquires Sun Microsystems. |
(Slide 12 showed a detailed version history with specific release years for JDK versions, indicating Sun Microsystems origin and later Oracle acquisition).
Java Editions
Java technology comes in different editions tailored for specific types of development:
- Java SE (Standard Edition): (Formerly J2SE) For developing desktop applications, console applications, and applets. This is the core platform.
(Slide 14 showed desktop/laptop computers).
- Java ME (Micro Edition): (Formerly J2ME) For developing applications for devices with limited resources, like mobile phones (older feature phones), set-top boxes, embedded devices, smart cards, Raspberry Pi.
(Slide 15 showed mobile phones and a set-top box).
- Java EE (Enterprise Edition): (Formerly J2EE, now Jakarta EE) Builds on Java SE. Used for developing large-scale, multi-tiered, reliable, and secure enterprise applications, often server-side and distributed. Includes APIs for web services, servlets, JavaServer Pages (JSP), etc.
(Slide 16 showed server hardware and a web browser interface).
How Java is Different from C++
- Pointers: Java does not support explicit pointers, reducing complexity and memory errors. It uses references managed by the JVM.
- Data Structures: Java doesn't include C++'s `struct`, `union`, or `enum` (though Java has its own `enum` type introduced later, which is more object-oriented).
- Operator Overloading: Java does not allow user-defined operator overloading (except for `+` for String concatenation).
- Global Variables: Java doesn't support global variables; all variables and methods must be declared within a class.
- Object Passing: Java passes object references by value. This means the method receives a copy of the reference, allowing modification of the object's state, but not changing which object the original variable refers to. C++ allows passing by value, reference, or pointer.
- Compilation Target: C++ compiles directly to native executable code for a specific platform. Java compiles to platform-independent Bytecode (`.class` file), which is then interpreted or JIT-compiled by the JVM on the target platform.
(Slide 19 showed a comparison diagram: `MyProg.java` -> `javac` -> `MyProg.class` (Bytecode) -> JVM -> OS, versus `MyProg.cpp` -> `gcc` -> `myprog.exe` (Executable) -> OS).
New Features Added in Java (Compared to C/C++)
- Multithreading: Built-in support for concurrent execution of different parts of a program.
- Packages: Mechanism for organizing related classes and interfaces, managing namespaces.
- Interfaces: Define contracts for classes, enabling a form of multiple inheritance of type.
- Automatic Garbage Collection: JVM automatically manages memory deallocation, preventing memory leaks common in C/C++.
- Boolean Data Type: Native `boolean` type (`true`/`false`).
- Exception Handling: Robust mechanism (similar to C++'s `try`/`catch`) for handling runtime errors.
Java Applications
Java is used in a wide variety of applications:
- Web-based applications and web development (e.g., backend systems for LinkedIn, Amazon, using frameworks like Spring).
- Big Data technology (e.g., Apache Hadoop framework is written in Java).
- Internet of Things (IoT) devices.
- Android Apps (Java is an official language for Android development, alongside Kotlin).
- Desktop Applications (using libraries like Swing or JavaFX).
- Computer games (e.g., Minecraft).
- Enterprise applications, scientific computing, financial trading platforms, etc.
Characteristics of Java (Summary)
- Simple: Familiar C/C++ syntax, automatic memory management (garbage collection).
- Object-Oriented: Everything (except primitives) is an object; programs structured around classes.
- Distributed: Designed for network environments (supports TCP/IP, RMI, etc.).
- Robust: Strong compile-time error checking, strict runtime checking, exception handling, garbage collection reduce errors.
- Secure: Security features (Security Manager, bytecode verification, sandboxing for applets) prevent destructive actions.
- Platform Independent (Architecture Neutral): Achieved through bytecode and JVM. WORA.
- Portable: Platform independence plus standard library definitions ensure code runs similarly everywhere.
- Interpreted: JVM interprets bytecode at runtime (though JIT compilation makes it fast).
- High Performance: JIT compilers translate bytecode into native machine code for near-native speed.
- Multithreaded: Built-in support for concurrent programming.
- Dynamic: Classes loaded on demand; supports reflection.
Compiled and Interpreted Nature
Java uses a two-stage process:
- Compilation: The Java compiler (
javac
) translates human-readable source code (`.java` file) into platform-independent Bytecode (`.class` file). The compiler performs syntax checking.
- Interpretation/Execution: The Java Virtual Machine (JVM) on the target computer reads the Bytecode.
- It may interpret the bytecode line by line, translating it into native machine instructions.
- More commonly, it uses a Just-In-Time (JIT) compiler to translate frequently executed sections of bytecode into native machine code *during* runtime for much better performance.
The Bytecode itself is platform-independent, but the JVM is platform-specific (there are different JVMs for Windows, Linux, macOS, etc.). This is how Java achieves "Write Once, Run Anywhere".
(Slide 28 showed a diagram: Java Code -> JAVAC Compiler -> Byte Code -> JVM (Windows/Linux/Mac) -> Execution).
Note: The Java compiler is typically written in Java, while the JVM (including the interpreter/JIT) is often written in C/C++ for performance.
Java Environment
The Java development and runtime environment consists of several key components:
- JDK (Java Development Kit): Essential for *developing* Java applications. Includes tools like the compiler (
javac
), archiver (jar
), debugger, documentation generator (javadoc
), and the JRE.
- JRE (Java Runtime Environment): Required for *running* Java applications. Includes the JVM and the Java Class Libraries (APIs). Users who only want to run Java apps need the JRE, not the full JDK.
- JVM (Java Virtual Machine): The core component that executes Java bytecode. It's an abstract machine specification, with concrete implementations provided for different platforms.
- Java API (Application Programming Interface): A vast collection of pre-written classes and interfaces grouped into packages (e.g.,
java.lang
, java.util
, java.io
) that provide standard functionality (like I/O, networking, data structures, GUI components).
(Slides 40, 41, 42, 43 showed diagrams illustrating the relationship between JDK, JRE, JVM, and how Java programs run on different OS via their respective JRE/JVM).
JVM Components
- Class Loader: Dynamically loads `.class` files (bytecode) from disk or network into memory when needed.
- Bytecode Verifier: Checks the loaded bytecode for validity and security issues (e.g., proper format, no stack overflows, valid type conversions) before execution.
- Execution Engine: Executes the verified bytecode. This can be done via:
- Interpreter: Reads and executes bytecode instructions one by one. Slower but starts faster.
- Just-In-Time (JIT) Compiler: Compiles frequently used bytecode into native machine code during runtime for faster execution. There's an initial compilation delay, but subsequent calls are much faster.
- Garbage Collector: Automatically reclaims memory occupied by objects that are no longer referenced by the program.
- Other components: Runtime data areas (heap, stack, method area), native method interface, etc.
Java Program Types
- Application: A standalone program that runs directly on the host operating system using the JRE/JVM (like programs written in C/C++).
- Applet: (Largely obsolete now) A small Java program designed to be embedded within an HTML page and executed by a web browser's JVM plugin. Applets ran in a restricted "sandbox" environment for security.
Fundamental Language Elements
- Reserved Words (Keywords): Words with special meaning to the compiler (e.g.,
class
, public
, static
, void
, int
, if
, for
). Cannot be used as identifiers. (Over 40 in Java).
- Identifiers: Names given by the programmer to classes, methods, variables, objects, etc. Must follow specific rules (e.g., start with letter, $, or _; contain letters, digits, $, _).
- Curly Braces
{}
: Define blocks of code (e.g., class bodies, method bodies, loop bodies). Always come in pairs.
- White Space: Spaces, tabs, newlines. Mostly ignored by the compiler but crucial for human readability. Required to separate identifiers and keywords. Indentation is used to show program structure.
- Comments: Ignored by the compiler, used for human explanation.
// Single-line comment
/* Multi-line comment */
/** Javadoc comment */
(Used by the javadoc
tool to generate documentation).
The Simple Structure of a Method
Methods define the behavior of objects. They have:
- Header: Includes access modifiers (e.g.,
public
), other modifiers (e.g., static
), return type (e.g., void
, int
), method name, and parameter list in parentheses ()
.
- Body: Enclosed in curly braces
{}
. Contains declarations (local variables) and statements (code to be executed).
The main
Method
- The special starting point for a Java application.
- Signature:
public static void main(String[] args)
public
: Accessible from anywhere.
static
: Can be called without creating an object of the class. Belongs to the class itself.
void
: Does not return any value.
main
: The specific name the JVM looks for.
String[] args
: Parameter list - an array of Strings to receive command-line arguments.
Compiling and Running a Simple Program
File: Hello.java
// A program to print "hello, world".
class Hello {
// main method - program execution begins here
public static void main(String[] args) {
// Print the text "hello, world" to the console
System.out.println("hello, world");
}
}
The Edit-Compile-Run Cycle:
- Edit: Create/save the source code in a file named `Hello.java` (the filename must match the public class name).
- Compile: Use the Java compiler:
javac Hello.java
This generates the bytecode file `Hello.class`. If there are errors, edit the code and recompile.
- Run: Use the Java Virtual Machine (interpreter):
java Hello
(Note: Do not include the `.class` extension when running). The JVM loads `Hello.class`, finds the `main` method, and executes it.
Bytecode Files (`.class`)
- The Java compiler creates one `.class` file for each class defined in the source code.
- This file contains platform-independent bytecode.
- The same `.class` file can be run on any machine with a compatible JVM.
Simple Java Application Example Walkthrough
Let's re-examine the example from the slides:
File: TestGreeting.java
// code1 The TestGreeting.java Application
// Sample “Hello World” Application
public class TestGreeting { // Class name matches filename
public static void main (String [] args) { // Main method entry point
// 1. Create an object (instance) of the Greeting class
// 'new Greeting()' calls the constructor and allocates memory
// 'hello' is a variable holding the reference (address) to the object
Greeting hello = new Greeting();
// 2. Send a message (call the greet() method) to the object
// referred to by the 'hello' variable
hello.greet();
} // end main
} // end class TestGreeting
File: Greeting.java
// Code 2-2 The Greeting.java class
public class Greeting { // Another class definition
// Method definition for the greet behavior
// 'public' means it can be called from other classes (like TestGreeting)
// 'void' means it doesn't return any value
public void greet() { // Between the parentheses, don’t write void
// Use the System class's 'out' object (standard output stream)
// and call its 'println' method to print text to the console
System.out.println("Hello ALL");
} // end greet method
} // end class Greeting
Explanation Notes:
public class TestGreeting
: Declares the class. Filename must be `TestGreeting.java`. Compilation creates `TestGreeting.class`.
public static void main (String [] args)
: The entry point. The JVM starts execution here. The class containing `main` must have the same name as the `.java` file.
Greeting hello = new Greeting();
: Creates an object of the `Greeting` class. The `new` operator allocates memory and returns a reference, which is stored in the variable `hello`.
hello.greet();
: Calls the `greet()` method *on the specific `Greeting` object* that `hello` refers to.
System.out.println("...")
: Prints the string literal to the standard output console.
System
: A built-in class in the java.lang
package (imported automatically).
out
: A `static` member variable of the `System` class. It's an object of type `PrintStream` representing the standard output. Being static, it's accessed via the class name (`System.out`).
println(...)
: A method of the `PrintStream` class (the object `out`) that prints the argument followed by a newline.
- Compilation: When you compile `TestGreeting.java` (e.g., `javac TestGreeting.java`), the compiler sees that it uses the `Greeting` class. If `Greeting.java` is in the same directory (or accessible via the classpath), it will also be compiled automatically, creating `Greeting.class`.
- Running: When you run `java TestGreeting`, the JVM loads `TestGreeting.class`, finds `main`, creates the `Greeting` object, and calls its `greet` method, resulting in "Hello ALL" being printed.
Working with Java Tools (Command Line)
- Setting the Path: To run `javac` and `java` from any directory, you need to add the JDK's `bin` directory (e.g., `C:\Program Files\Java\jdk-17\bin`) to your system's PATH environment variable.
- Compiling with Path: If not in the directory, you can specify the full path: `javac C:\path\to\your\code\TestGreeting.java`.
- Viewing Bytecode: `javap -c ClassName` (e.g., `javap -c TestGreeting`) disassembles the `.class` file and shows the bytecode instructions.
- Generating Documentation: `javadoc FileName.java` or `javadoc *.java` uses the `/** ... */` comments to generate HTML documentation for your code.