Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Java Fundamentals: Types, Operators, OOP, APIs, and Modern Features

Tech 1
public class Demo {
    public static void main(String[] args) {
        // Single-line comment

        /*
         * Multi-line comment
         */

        /**
         * Documentation comment
         */
        System.out.println("Starting comments");
    }
}

Literals

Literals represent fixed values in source code:

  • Integer: 42, -100
  • Floating-point: 3.14, -0.5
  • Boolean: true, false
  • Character: 'A', '中' (single quotes)
  • String: "Hello", "世界" (double quotes)

Identifiers

Names for classes, variables, methods, etc., must:

  • Start with letter, _, or $
  • Not begin with digit
  • Avoid Java keywords
  • Be case-sensitive

Example:

int 数字 = 100;
System.out.println(数字);

Variables

Variables store mutable data in memory. Without variables, repeated literals would occupy separate memory locations.

Data Types

Primitive types: byte, short, int, long, float, double, boolean, char
Reference types: Arrays, classes, interfaces (store memory addresses)

Type Conversion

Implicit (widening): Smaller types automatically convert to larger types:

byte b = 10;
int i = b; // Valid

In expressions, byte, short, and char promote to int.

Explicit (narrowing): Requires casting and may lose data:

int i = 257;
byte b = (byte) i; // Results in 1 (data loss)

Operators

  • Arithmetic: +, -, *, /, %; + concatenates strings
  • Assignment: =, +=, -= (includes implicit casting)
  • Relational: ==, !=, <, >, etc.
  • Logical: &&, ||, !; & and | always evaluate both operands
  • Ternary: condition ? value1 : value2

Input Handling

import java.util.Scanner;

Scanner input = new Scanner(System.in);
int age = input.nextInt();
String name = input.next();

Control Flow

Selection: if-else, switch (supports byte, short, int, char, String, enums)
Loops: for, while, do-while
Jump statements: break (exits loop/switch), continue (skips current iteration)

Arrays

Fixed-size containers storing homogeneous elements.

Declaration and initialization:

// Static
int[] nums = {1, 2, 3};

// Dynamic
int[] values = new int[5]; // Default: 0

Multidimensional arrays:

int[][] matrix = new int[3][4];
matrix[0][0] = 10;

Methods

Reusable code blocks that encapsulate logic. Parameters use pass-by-value semantics.

Method overloading: Same name, different parameter lists (count, type, or order).

Object-Oriented Programming

Core principles: Encapsulation, Inheritance, Polymorphism.

Class members: Fields, methods, constructors, nested classes, blocks.

Constructors: Initialize objects. If none defined, compiler prvoides default no-arg constructor.

this keyword: Refers to current instance; resolves naming conflicts.

Encapsulation: Restrict direct access to fields via private modifiers; expose via getters/setters.

static members:

  • Belong to class, not instances
  • Initialized once at class loading
  • Cannot access instance members directly

Code blocks:

  • Static block: Runs once during class loading
  • Instance block: Runs before constructor on each object creation

Singleton pattern:

// Eager initialization
public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() { return INSTANCE; }
}

Inheritance (extends):

  • Java supports single inheritance
  • Object is root superclass
  • Child classes inherit non-private members

Method overriding:

  • Subclass provides specific implementation
  • Must match signature; access modifier ≥ parent's
  • Use @Override annotation

Polymorphism:

Animal pet = new Dog(); // Parent reference, child object
pet.speak(); // Calls Dog's overridden method
  • Member variables are not polymorphic (resolved at compile time)
  • Downcasting requires instanceof check:
if (pet instanceof Dog) {
    Dog d = (Dog) pet;
}

final keyword:

  • Class: Cannot be subclassed
  • Method: Cannot be overridden
  • Variable: Initialized once (reference can't change, but object state can)

Abstract classes:

  • May contain abstract methods (no body)
  • Cannot be instantiated
  • Subclasses must implement all abstract methods or be abstract

Interfaces (interface):

  • Define contracts with abstract methods
  • Support multiple implementation
  • JDK 8+ features:
    • default methods (provide implementation)
    • static methods
    • private helper methods (JDK 9+)

Nested classes:

  • Member inner class: Associated with outer class instance
  • Static nested class: Independent of outer instance
  • Anonymous inner class: Inline subclass or interface implementation

Enums: Special classes representing fixed sets of constants:

enum Color { RED, GREEN, BLUE; }

Can include fields, methods, and constructors.

Generics

Enable type-safe collections and methods:

List<String> names = new ArrayList<>();
public <T> void print(T item) { ... }
  • Compile-time type checking
  • Type erasure at runtime
  • Do not support primitives (use wrapper classes)

Common APIs

java.lang.String:

  • Immutable sequence of characters
  • String pool optimizes memory for literals
  • Key methods: length(), charAt(), substring(), equals(), split()

ArrayList: Resizable array implementation:

List<String> list = new ArrayList<>();
list.add("item");
list.remove(0);

Wrapper classes: Convert primitives to objects (Integer, Double, etc.) with auto-boxing/unboxing.

StringBuilder: Mutable string for efficient concatenation:

StringBuilder sb = new StringBuilder();
sb.append("text").append(123);

Date-Time APIs:

  • Legacy: Date, Calendar, SimpleDateFormat (not thread-safe)
  • Modern (JDK 8+):
    • LocalDateTime, ZonedDateTime
    • DateTimeFormatter (thread-safe)
    • Period, Duration for time intervals

Utility classes:

  • Math: Mathematical operations
  • System: System-level operations (currentTimeMillis())
  • Arrays: Array manipulation (sort(), binarySearch())
  • BigDecimal: Precise decimal arithmetic

JDK 8+ Features

Lambda expressions: Concise syntax for functional interfaces:

Runnable task = () -> System.out.println("Running");

Method references: Further simplify lambdas:

  • Static: Math::max
  • Instance: str::length
  • Constructor: ArrayList::new

Streams: Process sequences of elements:

List<String> result = names.stream()
    .filter(s -> s.startsWith("A"))
    .map(String::toUpperCase)
    .collect(Collectors.toList());

Regular Expressions

Validate and extract text patterns:

String emailPattern = "\\w+@\\w+\\.\\w+";
boolean valid = email.matches(emailPattern);

// Find matches
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("Price: 100 dollars");
while (m.find()) {
    System.out.println(m.group()); // "100"
}

Common constructs:

  • [abc]: Character class
  • ^: Negation in character class
  • (?i): Case-insensitive matching
Tags: JavaOOP

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.