JavaSE

Li

Li Wei

January 10, 202611 min read

Title: JavaSE

Basics

Data

Variable Types
Category Definition Location Initialization Value Invocation Storage Location Lifetime Alias
Member variable Inside a class, outside methods Has default initialization value Object invocation Heap Lives as long as the object exists Instance variable
Local variable Inside a method or as a method parameter No default value; must be assigned before use Stack Lives as long as the method executes
Static variable Inside a class, outside methods Has default initialization value Object invocation or class‑name invocation Method area (moved to heap after JDK 8) Lives as long as the class exists Class variable, static member variable

Static variables exist as a single copy; member variables belong to each instance; local variables exist only within a method.

Data Types

Java provides eight primitive types: six numeric types (four integer types, two floating‑point types), one character type, and one boolean type.

Data Type Keyword Memory (bytes) Value Range
Integer byte 1 –2⁷ ~ 2⁷‑1 (‑128 ~ 127)
short 2 –2¹⁵ ~ 2¹⁵‑1 (‑32 768 ~ 32 767)
int 4 –2³¹ ~ 2³¹‑1
long 8 –2⁶³ ~ 2⁶³‑1
Floating‑point float 4 1.401298e‑45 ~ 3.402823e+38
double 8 4.9e‑324 ~ 1.797693e+308
Character char 2 0 ~ 65 535
Boolean boolean 1 true, false

Upcasting and Downcasting
Java can implicitly upcast, but it cannot implicitly downcast because that may lose precision. To downcast, you must use an explicit cast.

Literals such as 1 are of type int, which has higher precision than short; therefore they cannot be implicitly downcast to short. Using += or ++ triggers a conversion.

Reference Types

Reference data types include classes, interfaces, and arrays—also called wrapper classes.

Roles of wrapper classes:

  • As classes, they inherit methods from Object.
  • As reference‑type variables, they can store null.

Java adds special capabilities to wrapper classes, mainly:

  • Converting a primitive value to a String

    • Call toString()
    • Use Integer.toString(primitiveValue)
    • Concatenate the primitive with an empty string (recommended)
  • Converting a String to the corresponding primitive value (important)

    • Xxx.parseXxx("string")Integer.parseInt(numStr)
    • Xxx.valueOf("string")Integer.valueOf(numStr) (recommended)
Code Demo

(code omitted)

Why Both Primitive and Reference Types?
  • Reference types encapsulate data and the operations on that data (e.g., Integer.parseInt(String) converts a String to an int). Most Java classes and methods, including generics and collections, work with reference types.

  • Primitive types are more memory‑efficient and faster. Objects carry extra header information, so using primitives improves performance. Hence both coexist.

  • Collections cannot store primitives because they are not subclasses of Object. Generics would otherwise require many overloaded methods for each primitive type.

  • ==

    • For primitives: compares actual values.
    • For reference types: compares object addresses.
Autoboxing and Unboxing
  • Autoboxing: Directly assign a primitive value or variable to a wrapper class. The compiler inserts a call to Integer.valueOf().
  • Unboxing: Directly assign a wrapper object to a primitive variable. The compiler inserts a call to java.lang.Integer#intValue.
Cache Pool

new Integer(123) vs. Integer.valueOf(123):

  • new Integer(123): creates a new object each time.
  • Integer.valueOf(123): reuses an object from the cache pool; repeated calls may return the same reference.

valueOf() first checks whether the value is in the cache; if so, it returns the cached instance. The compiler uses valueOf() during autoboxing, so identical values within the cache range share the same object.

Cache pools for primitive wrappers:

  • Boolean values true and false
  • All byte values
  • short values from –128 to 127
  • long values from –128 to 127
  • int values from –128 to 127
  • char values from \u0000 to \u007F (0 to 127)

In JDK 8, the Integer cache (IntegerCache) is special: its lower bound is –128, the upper bound defaults to 127 but can be changed at JVM startup with AutoBoxCacheMax=<size>. This option sets the system property java.lang.Integer.IntegerCache, which the cache reads to determine its upper limit.

Parameters

Formal vs. Actual Parameters
  • Formal parameter: defined in a method signature; must be a variable. Memory is allocated only when the method is invoked and released after the call finishes.
  • Actual parameter: the data passed when calling a method; can be a constant or a variable.
Varargs

Varargs allow a method to accept multiple arguments; internally they are treated as an array.

Syntax: DataType... parameterName

Benefits: flexible argument passing—none, one, or an array.

Rules:

  • Only one varargs parameter is allowed per method signature.
  • It must be the last parameter.

Methods

Overview

A method groups a block of code that performs a specific function.

  • A method must be defined before it can be used (method definition).
  • After definition, it must be invoked manually (method call).

Local variables are defined inside a method; they cannot be static or have access modifiers (protected, private, public). Local variables reside on the stack, while static variables reside in the method area (in the heap after JDK 8). Because stack memory is reclaimed when the method ends, static cannot be applied to local variables. Static variables are class variables.

Definition & Invocation

Definition syntax:

returnType methodName(parameterList) {
    // method body
}

Invocation syntax:

returnType variableName = methodName(arguments);
  • Method name: identifier used when calling.
  • Parameters: type and name, separated by commas.
  • Method body: code that performs the function.
  • return: supplies a value to the caller if needed.

If the method returns void, you can call it without assigning the result. Non‑void methods are usually called with a variable to capture the return value.

Each method call creates a new stack frame with its own memory; after execution, the frame is popped.

Notes
  • Methods cannot be defined inside other methods.
  • void means no return value; you may omit return or write return; without a value.
Method Overloading

Overloading occurs when multiple methods in the same class share the same name but differ in parameter lists (type or number). Overloading is about the method definition only; return type does not participate in overload resolution.

Selection Process (three phases):

  1. Phase 1 – No autoboxing/unboxing, no varargs.
  2. Phase 2 – Autoboxing/unboxing allowed, still no varargs.
  3. Phase 3 – Autoboxing/unboxing and varargs allowed.

If multiple candidates remain in a phase, the most specific one is chosen, usually the one whose parameter types are subclasses of the others. Overloading with varargs is discouraged.

Inheritance Overloading
A subclass can overload a non‑private method inherited from its superclass by providing a method with the same name but different parameter types.

  • If both methods are static, the subclass method hides the superclass method.
  • If both are instance methods, the subclass method overrides the superclass method (polymorphism).
Parameter Passing

Java uses pass‑by‑value:

  • Primitive types: the method receives a copy; changes to the parameter do not affect the original argument.
  • Reference types: the method receives a copy of the reference (i.e., the object’s address). Both the caller and callee refer to the same object, so modifications affect the original object.

Enums

Enums are a special Java type used for defining a fixed set of constants.

Enum definition syntax:

public enum Color {
    RED, GREEN, BLUE;
}

Characteristics:

  • Declared final; cannot be subclassed.
  • Implicitly extends java.lang.Enum.
  • The first line lists the constant names.
  • Implements a multiton pattern; each constant is a static instance.

Common methods:

Method Description
String name() Returns the constant’s name.
int ordinal() Returns the constant’s position in the enum declaration.
int compareTo(E o) Compares two constants by their ordinal values.
String toString() Returns the constant’s name.
static T valueOf(Class<T> type, String name) Retrieves the enum constant of the specified name.
static T[] values() Returns an array of all constants.
Source Code Analysis & API Usage

(omitted)

Debugging

Debugging tools let programmers step through code, inspect execution flow, and track variables.

Typical workflow: set breakpoints → start Debug → step through → watch the Debugger window → view the Console.

Object‑Oriented Programming

Overview

Java is an object‑oriented high‑level language. Its three core OOP features are encapsulation, inheritance, and polymorphism.

Two fundamental concepts:

  • Class: a blueprint describing common attributes and behaviors; it exists only conceptually.
  • Object: a concrete instance of a class; an object is an instantiated class.

Thus, classes enable us to model the world, and objects are the actual entities we manipulate.

Classes

Definition

Syntax:

public class ClassName {
    // fields, constructors, methods, etc.
}

Guidelines:

  • Class names should start with an uppercase letter and follow CamelCase (e.g., StudentNameCode).
  • A Java source file can contain multiple classes, but by convention one public class per file.
  • Only one class may be declared public, and its name must match the file name.
Constructors

Constructor syntax:

public ClassName() { ... }          // no‑arg constructor
public ClassName(Type arg) { ... }  // parameterized constructor
  • Purpose: initialize a new object.
  • If no constructor is defined, Java provides a default no‑arg constructor.
  • Defining any constructor removes the default; you must explicitly write a no‑arg constructor if needed.

Object creation:

ClassName obj = new ClassName();          // no‑arg
ClassName obj = new ClassName(argValue);  // with arguments

Packages

A package groups related classes for better organization, reuse, and readability.

Package declaration syntax: package packageName; (must appear before any class declarations).

Import syntax: import 包名.类名 import packageName.ClassName;

Classes in the same package can access each other directly; classes in different packages require an import.

Encapsulation

Philosophy: hide what’s unnecessary, expose what’s needed.

Goal: improve security, reusability, and modularity.

Steps:

  • Declare member variables private.
  • Provide corresponding getter and setter methods to access and modify them.

Using private protects data from unauthorized modification.

this

The this keyword refers to the current object:

  • Inside a method: this denotes the object that invoked the method.
  • Inside a constructor: this refers to the object being constructed.
  • It distinguishes between member variables and local variables with the same name.

static

Basic Introduction

Whether a member is static determines if it belongs to the class or to instances.

  • Static members (class variables/methods): belong to the class itself; loaded once with the class; accessed via the class name.
  • Instance members: belong to each object; loaded with each object; accessed via the object reference.
Usage

Accessing static fields:

  • ClassName.staticField (within the same class, the class name may be omitted).
  • objectReference.staticField (legal but discouraged).

Accessing instance fields:

  • objectReference.instanceField (requires an object).

Calling static methods:

  • ClassName.staticMethod() (class name optional inside the same class).
  • objectReference.staticMethod() (legal but discouraged; see JVM method‑call mechanics).

Calling instance methods:

  • objectReference.instanceMethod().
Common Questions
  • Memory layout

    • Stack: holds the main method and local variables.
    • Heap: stores objects and their fields.
    • Method area: stores class metadata and static variables (moved to heap after JDK 8).
  • Access rules

    • Instance methods can directly access instance fields, static fields, other instance methods, and static methods.
    • Static methods cannot directly access instance fields or instance methods; they must use an object reference.
    • Static methods can access static fields and other static methods.

Inheritance

Basic Introduction

Inheritance expresses an “is‑a” relationship: a subclass derives from a superclass.

  • Superclass (or parent class) is the class being inherited from.
  • Subclass (or child class) inherits the superclass.

Benefits:

  • Code reuse: common code lives in the superclass.
  • Subclass instances inherit fields and methods, then can add or override behavior.

Features:

  • Every subclass constructor implicitly calls the superclass’s no‑arg constructor before executing its own body.
  • Single inheritance: a class can extend only one direct superclass.
  • Multi‑level inheritance forms a hierarchy (family tree).
  • A class may have many subclasses.
  • All classes ultimately inherit from Object (directly or indirectly).

Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.

Keep reading

More related articles from DriftSeas.