Comprehensive Guide to Java Fundamentals: Setup, Syntax, and Core Classes
Environment Setup
JDK Installation and Configuration
Downloading JDK 8
JDK 8 (also known as JDK 1.8) is available from Oracle's official download page. Select the appropriate version for your operating system (e.g., Windows 64-bit).
Installation Steps
- Run the downloaded installer.
- Follow the installation wizard, specifying the installation directory.
- Complete the installation process.
Configuring Environment Variables
Set the following environment variables:
JAVA_HOME: Path to the JDK installation directory.- Add
%JAVA_HOME%\binto thePATHvariable.
Verification
Open a command prompt and execute:
java -version
javac
These commands should display the Java version and compiler information, respectively.
Key Concepts: JDK, JRE, JVM
- JVM (Java Virtual Machine): Executes Java bytecode.
- JRE (Java Runtime Environment): Includes JVM and core libraries for running Java applications.
- JDK (Java Development Kit): Contains JRE plus development tools (e.g., compiler, debugger).
Java 8 Features Overview
- Lambda expressions
- Method references
- Default methods in interfaces
- Stream API
- New date/time API (e.g., LocalDate, DateTimeFormatter)
- HashMap improvements with red-black trees
- ConcurrentHashMap enhancements
- CompletableFuture for asynchronous programming
- Metaspace replaces PermGen for method area implementation
Basic Hello World Example
Create a file named HelloWorld.java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compile and run:
javac HelloWorld.java
java HelloWorld
Integrated Development Environment: IntelliJ IDEA
Installation and Configuration
Download IntelliJ IDEA from JetBrains' website and install it. Configure global settings:
- Set file encoding to UTF-8
- Configure Maven paths (if needed)
- Adjust comment indentation
Essential Plugins
- Chinese Language Pack: To interface localization
- Alibaba Java Coding Guidelines: Code style checks
- Maven Helper: Dependency management
- MybatisX: MyBatis framework support
- RESTfulToolkit-fix: REST API development tools
- LeetCode Editor: Integrated coding practice
Debugging Techniques
Breakpoint Types
- Line breakpoints: Pause at specific code lines
- Method breakpoints: Stop at method entry
- Field breakpoints: Trigger on field access/modification
- Conditional breakpoints: Pause when conditions are met
- Exception breakpoints: Stop on thrown exceptions
Debugging Controls
- Step Over: Execute current line, skip method calls
- Step Into: Enter method implementation
- Step Out: Complete current method and return
- Resume: Continue to next breakpoint
- Evaluate Expression: Test code snippets during debugging
Advanced Debugging Features
- Drop Frame: Return to previous method call
- Force Return: Exit current method immediately
- Stream Debugging: Visualize Stream API operations
- Multithreaded Debugging: Control thread execution
Java Fundamentals
Primitive Data Types
Java has eight primitive types:
- Integer types: byte, short, int, long
- Floating-point: float, double
- Character: char
- Boolean: boolean
Memory Allocation
- byte: 1 byte
- short: 2 bytes
- int: 4 bytes
- long: 8 bytes
- float: 4 bytes
- double: 8 bytes
- char: 2 bytes
- boolean: JVM-dependent
Primitive vs Reference Types
Primitive types store values directly, while reference types store memory addresses. Reference types include classes, arrays, and interfaces.
Arrays
Declaration and Initialization
// Recommended style
int[] numbers;
// Alternative style (not recommended)
int numbers[];
Initialization Methods
// Static initialization
int[] staticArray = {1, 2, 3};
// Dynamic initialization
int[] dynamicArray = new int[5];
Array Operations
// Access elements
int element = numbers[2];
// Iteration
for (int num : numbers) {
System.out.println(num);
}
// Conversion to string
String arrayString = Arrays.toString(numbers);
Control Flow Statements
Conditional Statements
// If-else
if (condition) {
// code block
} else if (anotherCondition) {
// alternative block
} else {
// default block
}
// Switch statement
switch (value) {
case 1:
// case 1 logic
break;
case 2:
// case 2 logic
break;
default:
// default logic
}
Modifiers and Keywords
Access Modifiers
- public: Accessible from any class
- protected: Accessible with in package and subclasses
- default (package-private): Accessible within package
- private: Accessible only within declaring class
Other Modifiers
- static: Class-level members
- final: Immutable variables, non-overridable methods, non-extendable classes
- abstract: Cannot be instantiated, may contain abstract methods
Key Keywords
- this: Reference to current object
- super: Reference to parent class
- this(): Call another constructor in same class
- super(): Call parent class constructor
Object-Oriented Programming
Classes and Objects
Class Definitoin
public class Vehicle {
// Fields
private String brand;
private int year;
// Constructor
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
// Methods
public void displayInfo() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}
Object Creation Methods
- Using new keyword
- Reflection API
- clone() method
- Deserialization
Methods
Method Structure
public returnType methodName(parameters) {
// method body
return value;
}
Method Overloading
Methods with same name but different parameter lists:
public int calculate(int a, int b) { return a + b; }
public double calculate(double a, double b) { return a + b; }
Variable Arguments
public int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
Interfaces and Abstract Classes
Interface Example
public interface Drawable {
void draw();
default void resize() {
System.out.println("Resizing...");
}
}
Abstract Class Example
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
public abstract double area();
public void displayColor() {
System.out.println("Color: " + color);
}
}
OOP Principles
Encapsulation
Hide implementation details using private fields with public getters/setters.
Inheritance
public class Car extends Vehicle {
private int doors;
public Car(String brand, int year, int doors) {
super(brand, year);
this.doors = doors;
}
}
Polymorphism
// Interface reference to implementation
List<String> list = new ArrayList<>();
// Method overriding
@Override
public void draw() {
// Custom implementation
}
Essential Java Classes
String Manipulation
String Creation
// String literal (preferred)
String str1 = "Hello";
// Using constructor
String str2 = new String("World");
String Operations
// Concatenation
String result = str1 + " " + str2;
// Substring
String sub = result.substring(0, 5);
// Comparison
boolean equal = str1.equals(str2);
// Splitting
String[] parts = "a,b,c".split(",");
// Case conversion
String upper = str1.toUpperCase();
String lower = str2.toLowerCase();
StringBuilder
StringBuilder builder = new StringBuilder();
builder.append("Hello")
.append(" ")
.append("World");
String finalString = builder.toString();
Utility Classes
Scanner for Input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.close();
Object Class Methods
- toString(): String representation
- equals(): Object equality
- hashCode(): Hash code generation
- getClass(): Runtime class information
System Class
// Current time in milliseconds
long timestamp = System.currentTimeMillis();
// Array copying
System.arraycopy(source, 0, destination, 0, length);
// System properties
String os = System.getProperty("os.name");
Integer Wrapper Class
// Boxing and unboxing
Integer boxed = 100; // Autoboxing
int primitive = boxed; // Unboxing
// String conversion
int value = Integer.parseInt("123");
String str = Integer.toString(456);
Arrays Utility
// Sorting
Arrays.sort(array);
// Searching
int index = Arrays.binarySearch(sortedArray, key);
// Filling
Arrays.fill(array, value);
// Comparison
boolean same = Arrays.equals(array1, array2);
Date and Time
// Current date/time
Date now = new Date();
// Formatting with SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted = sdf.format(now);
// Java 8 DateTimeFormatter
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted8 = LocalDateTime.now().format(dtf);
Math Operations
// Basic operations
double abs = Math.abs(-5.5);
double max = Math.max(10, 20);
double sqrt = Math.sqrt(25);
// Trigonometric functions
double sin = Math.sin(Math.PI / 2);
// Random numbers
double random = Math.random(); // 0.0 to 1.0
Random Number Generation
Random random = new Random();
// Random integers
int randomInt = random.nextInt(100); // 0-99
// Random doubles
double randomDouble = random.nextDouble(); // 0.0-1.0
// Random booleans
boolean randomBool = random.nextBoolean();