Introduction to Java Programming
Java is a high-level, class-based, object-oriented programming language originally developed at Sun Microsystems and released publicly in 1995. It is designed to be portable across different platforms through the Java Virtual Machine (JVM).
What is Java?
Java allows developers to write programs that are compiled into platform-independent bytecode. This bytecode can be executed on different operating systems using a compatible Java Virtual Machine.
History of Java
- 1991: The Green Project began at Sun Microsystems, led by James Gosling and others.
- 1995: Java was publicly released.
- 2006: Sun began releasing Java technologies as open source.
- 2010: Oracle completed its acquisition of Sun Microsystems.
- 2014: Java 8 introduced important features such as lambda expressions and the Stream API.
- 2018: Java 11 was released as a Long-Term Support (LTS) version.
First Java Program
The main() method is the conventional entry point of a standalone Java application. The System.out.println() statement displays text on the console.
Features of Java
Java provides several features that make it suitable for developing desktop applications, web applications, enterprise systems, Android-related software, and many other types of applications.
Key Features of Java
- Platform Independent: Java source code is compiled into bytecode that can run on different platforms using a JVM.
- Object-Oriented: Java supports classes, objects, encapsulation, inheritance, polymorphism, and abstraction.
- Simple: Java was designed with a relatively simple syntax compared with several older programming languages.
- Secure: Java provides features such as bytecode verification, strong type checking, and controlled memory access.
- Robust: Automatic memory management, exception handling, and type checking help create reliable applications.
- Multithreaded: Java provides built-in support for concurrent execution using threads and concurrency APIs.
- Portable: Java bytecode is designed to behave consistently across supported platforms.
- High Performance: Modern JVMs use techniques such as Just-In-Time (JIT) compilation to improve execution performance.
Java Virtual Machine (JVM)
The Java Virtual Machine (JVM) is the runtime environment that executes Java bytecode. It is an important component responsible for Java's platform-independent execution model.
Major JVM Components
- Class Loader: Loads Java class files into memory when required.
- Runtime Data Areas: Includes areas such as the heap, JVM stacks, method area, and program counter registers.
- Heap: Stores objects and arrays created during program execution.
- JVM Stack: Contains stack frames used during method execution.
- PC Register: Keeps track of the current instruction for each thread.
- Native Method Stack: Supports execution of native methods.
- Execution Engine: Executes bytecode using interpretation and JIT compilation.
Java Program Execution Process
- A programmer writes Java source code in a .java file.
- The Java compiler (javac) compiles the source code.
- The compiler produces bytecode in a .class file.
- The JVM loads the required classes using the Class Loader.
- The JVM verifies and executes the bytecode.
- The execution engine may interpret bytecode or compile frequently executed code using JIT compilation.
JDK vs JRE vs JVM
| Component | Meaning | Main Purpose |
|---|---|---|
| JVM | Java Virtual Machine | Executes Java bytecode |
| JRE | Java Runtime Environment | Provides the runtime environment for Java applications |
| JDK | Java Development Kit | Provides tools required to develop Java applications |
Data Types and Variables in Java
Java is a statically and strongly typed language. Every variable has a declared type that determines what kind of value it can hold.
Primitive Data Types
| Data Type | Size | Typical Value Range |
|---|---|---|
| byte | 8 bits | -128 to 127 |
| short | 16 bits | -32,768 to 32,767 |
| int | 32 bits | -231 to 231-1 |
| long | 64 bits | -263 to 263-1 |
| float | 32 bits | Approximately ±3.4 × 1038 |
| double | 64 bits | Approximately ±1.7 × 10308 |
| char | 16 bits | 0 to 65,535 |
| boolean | Not specified by Java language | true or false |
Variable Declaration and Initialization
In addition to primitive types, Java provides reference types such as classes, interfaces, arrays, enums, and records.
Operators in Java
Operators are symbols used to perform operations on values and variables.
Types of Java Operators
| Operator Type | Examples | Purpose |
|---|---|---|
| Arithmetic | +, -, *, /, % | Mathematical calculations |
| Relational | ==, !=, >, <, >=, <= | Compare values |
| Logical | &&, ||, ! | Combine boolean conditions |
| Assignment | =, +=, -=, *=, /= | Assign values |
| Unary | ++, --, +, -, ! | Operate on a single operand |
| Bitwise | &, |, ^, ~, <<, >>, >>> | Perform operations on individual bits |
| Ternary | ? : | Short conditional expression |
Control Statements in Java
Control statements determine the order in which statements are executed in a Java program.
Decision-Making Statements
- if: Executes a block when a condition is true.
- if-else: Selects between two alternatives.
- else-if: Tests multiple conditions.
- switch: Selects among multiple possible cases.
Looping Statements
- for: Useful when the number of iterations is known or controlled by a loop expression.
- while: Repeats while a condition remains true.
- do-while: Executes the body at least once before checking the condition.
- enhanced for: Iterates conveniently over arrays and collections.
Object-Oriented Programming in Java
Java is a class-based object-oriented programming language. It provides mechanisms for organizing programs using classes, objects, inheritance, interfaces, and other object-oriented concepts.
Four Commonly Discussed Principles of OOP
- Encapsulation: Combining data and related behavior while controlling access to internal state.
- Inheritance: Creating a class based on another class.
- Polymorphism: Allowing the same interface or method call to work with different object implementations.
- Abstraction: Exposing essential behavior while hiding unnecessary implementation details.
Class and Object
A class defines the structure and behavior of objects. An object is an instance of a class.
Inheritance in Java
Inheritance allows a class to acquire accessible fields and methods from another class. The class being inherited from is commonly called the superclass, while the inheriting class is called the subclass.
Common Forms of Class Inheritance
- Single Inheritance: One subclass extends one superclass.
- Multilevel Inheritance: A class extends another subclass, forming a chain.
- Hierarchical Inheritance: Multiple subclasses extend the same superclass.
Java does not allow a class to directly extend multiple classes. However, a class can implement multiple interfaces.
Polymorphism in Java
Polymorphism means that a common interface or method name can represent different behavior depending on the context.
Method Overloading
Method overloading occurs when a class has multiple methods with the same name but different parameter lists.
Method Overriding
Method overriding occurs when a subclass provides its own implementation of an inherited instance method.
Abstraction in Java
Abstraction focuses on exposing the essential behavior of an object while hiding implementation details.
Abstract Classes
- An abstract class cannot be directly instantiated.
- It can contain abstract methods.
- It can also contain concrete methods and fields.
- A concrete subclass generally provides implementations for inherited abstract methods.
Interfaces
An interface defines a contract that implementing classes agree to follow. Modern Java interfaces can contain abstract methods, default methods, static methods, and other supported interface members.
Encapsulation in Java
Encapsulation is the practice of controlling access to an object's internal state and exposing operations through a suitable public interface.
Java Access Modifiers
| Modifier | Same Class | Same Package | Subclass in Other Package | Other Classes |
|---|---|---|---|---|
| private | Yes | No | No | No |
| default / package-private | Yes | Yes | No | No |
| protected | Yes | Yes | Yes, under inheritance access rules | No |
| public | Yes | Yes | Yes | Yes |
Exception Handling in Java
Exception handling provides a structured way to detect and handle exceptional conditions that occur during program execution.
Exception Hierarchy
- Throwable: Root type for exceptions and errors that can be thrown.
- Error: Represents serious conditions generally not intended to be handled by application code.
- Exception: Represents conditions that applications may handle.
- RuntimeException: Base class for many unchecked exceptions.
Exception Handling Keywords
- try: Contains code that may produce an exception.
- catch: Handles a matching exception.
- finally: Contains cleanup code that normally executes after try/catch processing.
- throw: Explicitly throws an exception.
- throws: Declares exceptions that a method may propagate.
Multithreading in Java
Multithreading allows a Java application to perform multiple tasks concurrently. Java provides threads and higher-level concurrency utilities for managing concurrent work.
Common Ways to Create Threads
- Extending the Thread class.
- Implementing the Runnable interface.
- Using higher-level concurrency APIs such as executors.
Important Thread States
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
Java Collections Framework
The Java Collections Framework provides interfaces and classes for storing and manipulating groups of objects.
Main Collection Interfaces
- List: Ordered collection that generally permits duplicate elements.
- Set: Collection that does not permit duplicate elements.
- Queue: Collection designed for holding elements before processing.
- Map: Stores key-value associations. Keys are unique within a map.
Common Collection Classes
| Interface | Common Implementations | Characteristics |
|---|---|---|
| List | ArrayList, LinkedList, Vector | Ordered collection; duplicates are allowed |
| Set | HashSet, LinkedHashSet, TreeSet | Does not allow duplicate elements |
| Queue | PriorityQueue, LinkedList | Useful for processing elements in a defined queue order |
| Map | HashMap, LinkedHashMap, TreeMap | Stores key-value pairs with unique keys |
Java Programming Summary
Java combines object-oriented programming, automatic memory management, exception handling, concurrency support, and a platform-independent runtime environment. Understanding the fundamentals below provides a strong foundation for learning advanced Java development.
| Topic | What to Remember |
|---|---|
| Java | Class-based, object-oriented, strongly typed programming language |
| JVM | Executes Java bytecode |
| JDK | Provides tools for Java development |
| Data Types | Eight primitive types plus reference types |
| OOP | Encapsulation, inheritance, polymorphism, abstraction |
| Exception Handling | try, catch, finally, throw, throws |
| Collections | List, Set, Queue and Map |
| Multithreading | Supports concurrent execution and concurrency APIs |