Comprehensive Java Programming & Computer Science Study Notes

Introduction to Computers and Java Programming

  • History and Evolution of Java:

    • Developed originally by the Green Team at Sun Microsystems (now owned by Oracle Corporation) beginning in 1991.
    • Initially created for consumer electronics control, specifically the *7 handheld controller designed to manipulate multiple entertainment systems.
    • The language was originally named Oak, designed specifically to address the need for a language that could execute across diverse hardware architectures.
    • In 1995, Sun World demonstrated HotJava, a web browser built using Java, demonstrating embedded interactive applets. Shortly after, Netscape incorporated Java support into its web browser.
    • Java is engineered as a cross-platform language, enabling applications to run seamlessly across various computer operating systems without modification.
  • Java Program Types:

    • Applications: Stand-alone programs running directly on a computer without a web browser. Applications operate under a relaxed security model because they are launched locally by the user.
    • Applets: Small programs designed to run within a Java-enabled web browser. Applets execute under an enhanced security model to protect users from malicious web code.
  • Foundations of Computer Programming:

    • Computers are versatile tools because they are programmable, allowing them to execute tasks across spreadsheets, databases, word processors, games, and customized software.
    • Programmers design multiple aspects of software: logical instruction flow, mathematical procedures, statement layout, screen interface design, user presentation, user-friendliness, and documentation (manuals and help systems).
    • Software must be analytically correct. Programs rarely execute perfectly on the first draft, requiring programmers to continuously analyze, experiment, correct, and redesign.
    • Programming languages enforce strict syntactic rules (syntax) that must be precisely satisfied.
  • Computer Hardware Components:

    • Hardware represents the physical components of a computer system.      Hardware Components

    • Central Processing Unit (CPU): Consists of two primary sub-components: the Control Unit (which fetches instructions and routes electronic signals) and the Arithmetic Logic Unit (ALU, which performs numeric computations and logical comparisons).      CPU Architecture

    • The Fetch-Decode-Execute Cycle:

    • Fetch: The Control Unit fetches the next encoded numeric instruction from main memory.

    • Decode: The Control Unit decodes the numeric instruction and generates an electronic signal.

    • Execute: The electronic signal is routed to the appropriate hardware component (such as the ALU or a disk drive), causing it to perform an operation.        Fetch Decode Execute Cycle

    • Main Memory (RAM - Random-Access Memory):

    • Volatile storage used to hold currently executing programs and their active data. Contents are erased when power is disconnected.

    • RAM is partitioned into units called bytes. Each byte consists of 88 bits (binary digits).

    • A bit represents an electronic switch that is either off (00) or on (11).

    • Each individual byte is assigned a unique numerical memory address.        Memory Bytes and Bits

    • Secondary Storage Devices:

    • Non-volatile storage designed to hold data permanently across system reboots. Examples include magnetic hard disk drives (HDD), solid-state drives (SSD), external drives, USB flash drives, CD drives, and DVD drives.

    • Input Devices:

    • Hardware that collects data from the external environment. Examples include keyboards, mice, scanners, and digital cameras.

    • Output Devices:

    • Hardware that displays or presents processed data to the external environment. Examples include monitors and printers. Devices performing both roles (such as disk drives) are designated I/O (Input/Output) devices.

  • Computer Software Classifications:

    • Operating Systems (OS): Essential programs managing computer hardware resources and processes. Modern operating systems support multitasking via time-sharing, dividing CPU processing attention and resource allocation among running applications. Examples include Unix, Linux, macOS, and Microsoft Windows.
    • Application Software: Programs providing specialized utilities to make the computer productive for users (e.g., word processors, tax preparation software, spreadsheets, games).
  • Programming Languages and Algorithms:

    • A program is a sequence of structured instructions executed by a computer to accomplish a task or solve a problem. This sequence forms an algorithm (a set of well-defined sequential steps).
    • Machine Language: The lowest-level language understood directly by hardware, consisting entirely of binary streams (00s and 11s). Every CPU architecture (e.g., Intel x86, ARM, Motorola 68000) possesses its own distinct machine language instruction set (e.g., 1011010000000101).
    • Assembly / High-Level Languages:
    • Assembly language was developed to replace numeric binary code with mnemonic short names, though it remains CPU-architecture dependent.
    • High-level languages were created to be CPU-independent and human-readable. Examples include Java, C, C++, C#, Python, BASIC, Go, Rust, PHP, Visual Basic, Ruby, and JavaScript.
    • Common Language Elements: Key words, operators, punctuation, programmer-defined identifiers, and syntactic rules.
  • Compilation and the Java Virtual Machine (JVM):

    • Source code is written in plain text files using a text editor and saved with a .java file extension.

    • Standard compilers convert source code into executable files containing CPU-specific machine language.

    • The Java compiler (javac) converts .java source code into an intermediate format called byte code instructions, stored in files with a .class extension.

    • Byte code is not readable by the physical CPU. Instead, it is executed by the Java Virtual Machine (JVM), an interpreting program that emulates a microprocessor.      Program Development Process

    • Software Portability:

    • Portability means a program can be compiled once and executed across different system architectures without modification.

    • Java achieves portability by supplying host-specific JVM implementations for Windows, macOS, Linux, Unix, BSD, and other platforms.        Java Portability Across JVMs

  • Java Development Environment Commands:

    • The Java Development Kit (JDK) provides software tools required to write and compile Java applications (available commercially via Oracle or open-source via OpenJDK).
    • Compiling: javac Payroll.java compiles the source file into Payroll.class byte code.
    • Executing: java Payroll invokes the JVM to run Payroll.class (the .class extension is omitted in the execution command).
    • Single-Command Execution (Java 11+): java Payroll.java compiles the program in memory and executes it immediately without generating a physical .class file on disk.
  • Software Engineering and Paradigms:

    • Software engineering encompasses designing, writing, testing, debugging, documenting, modifying, and maintaining software programs.

    • Engineers produce program specifications, UI mockups, pseudocode, data-flow diagrams, and test protocols. Large projects are partitioned into modular tasks assigned across programming teams.

    • Procedural Programming: Older paradigm where code is divided into procedures (functions/subroutines) operating on separate, external data items passed between procedures. Data is often global, meaning formatting changes force cascading changes across all dependent procedures.      Procedural Architecture

    • Object-Oriented Programming (OOP): Paradigm centered around creating objects that unify data (attributes) and behavior (methods).      Object Structure

    • Encapsulation & Data Hiding: Objects hide internal raw attribute data from external components (data hiding). External interaction occurs indirectly through public methods, establishing a secure programming interface.      Programming Interface

Java Fundamentals and Syntax

  • Anatomy of a Java Program:

    • A Java source file contains one or more classes. If a file contains a public class, the filename must match that class name exactly (e.g., public class Simple must reside in Simple.java).
    • Class definition headers declare visibility and name (public class Simple).
    • Curly braces {} delineate structural scope boundaries for classes and methods.
    • Application entry point requires an exact method signature: public static void main(String[] args).
    • Java is strictly case-sensitive; keywords (public, class, static, void) are lowercase.
    • Complete instructions that cause the computer to execute an action are Java statements, terminated by a semicolon ;.
  • Special Characters Reference:

    • //: Marks the beginning of a single-line comment.
    • ( ): Encloses parameter lists in method headers or overrides operator precedence.
    • { }: Encloses a block of statements defining class or method bodies.
    • " ": Encloses a sequence of characters forming a string literal.
    • ;: Terminates a complete programming statement.
  • Console Output and Escape Sequences:

    • Console execution uses standard output (System.out).
    • System.out.println() outputs its parameter string and appends an automatic newline character.
    • System.out.print() outputs its parameter string without inserting a newline character, leaving subsequent output on the same line.
    • Escape Sequences (embedded two-character pairs parsed as a single internal character):
    • : Newline. Advances the display cursor to the next line.
    • \t: Tab. Advances cursor to the next tab stop.
    • \b: Backspace. Moves cursor back one position to the left.
    • \r: Carriage Return. Returns cursor to the beginning of the current line.
    • \\: Backslash. Outputs a literal backslash character.
    • \': Single quote. Outputs a literal single quotation mark.
    • \": Double quote. Outputs a literal double quotation mark.
  • Variables and Memory Representation:

    • A variable is a named storage location in RAM. A literal is an explicit value encoded directly into source code.

    • Variable declarations assign a data type and identifier: int value;.

    • Value assignment uses the equal sign operator: value = 5;.      Variable in Memory

    • The JVM dynamically assigns physical memory addresses (e.g., 0x003) mapped symbolic identifier names.

  • String Concatenation:

    • The + operator functions as addition when operating on numbers and as string concatenation when either operand is a string.
    • String literals cannot break across line breaks in code. Multi-line strings must be linked using concatenation +.
    • Numeric calculations inside concatenation statements require explicit grouping parentheses to prevent string conversion prior to computation (e.g., "Result: " + (6 + 4) vs "Result: " + 5 * 6).
  • Identifiers and Reserved Keywords:

    • Identifier rules: May contain letters (a-z, A-Z), digits (0-9), underscores (_), or dollar signs ($). The first character cannot be a numeric digit. Identifiers cannot contain spaces.
    • Reserved Keywords (cannot be used as identifier names):     abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while.
    • Naming Conventions:
    • Variable and Method names: Lower camelCase (e.g., caTaxRate, salesTaxRate).
    • Class names: TitleCase / PascalCase (e.g., BigLittle, Simple).
    • Constants: Upper ALL_CAPS separated by underscores (e.g., CAL_SALES_TAX).
  • Primitive Data Types:

    • Built-in types categorized into integer, floating-point, boolean, and character sets:
    • byte: 11 byte. Integer range −128-128 to +127+127.
    • short: 22 bytes. Integer range −32,768-32,768 to +32,767+32,767.
    • int: 44 bytes. Integer range −2,147,483,648-2,147,483,648 to +2,147,483,647+2,147,483,647.
    • long: 88 bytes. Integer range −9,223,372,036,854,775,808-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807+9,223,372,036,854,775,807.
    • float: 44 bytes. Floating-point range ±3.4×10−38±3.4 \times 10^{-38} to ±3.4×1038±3.4 \times 10^{38} (77 decimal digits precision).
    • double: 88 bytes. Floating-point range ±1.7×10−308±1.7 \times 10^{-308} to ±1.7×10308±1.7 \times 10^{308} (1515 decimal digits precision).
    • boolean: Logical values true or false.
    • char: 22 bytes. Holds single characters encoded in Unicode.
  • Floating-Point Literals and Notation:

    • Embedded floating-point literals default to the double data type.
    • Assigning a literal decimal to a float variable causes a compilation error unless explicitly postfixed with F or f (e.g., float number = 23.5F;).
    • Floating-point literals cannot contain commas or currency symbols.
    • Scientific and E-Notation conversions:
    • 247.91=2.4791×102=2.4791E2247.91 = 2.4791 \times 10^2 = 2.4791\text{E}2
    • 0.00072=7.2×10−4=7.2E−40.00072 = 7.2 \times 10^{-4} = 7.2\text{E}-4
    • 2,900,000=2.9×106=2.9E62,900,000 = 2.9 \times 10^6 = 2.9\text{E}6
    • 47,281.97=4.728197×104=4.728197E447,281.97 = 4.728197 \times 10^4 = 4.728197\text{E}4
  • Unicode Character System:

    • Characters are mapped internally to numbers. Java uses Unicode, a 16-bit encoding scheme capable of representing 65,53665,536 unique characters.
    • The first 256256 Unicode entries correspond directly to ASCII (American Standard Code for Information Interchange).
    • char literals use single quotation marks ('A'), whereas String literals use double quotation marks ("A").      Unicode Storage
  • Variable Assignment and Local Variable Type Inference:

    • Assignment uses equal sign = (left side must be variable identifier; right side must evaluate to a compatible type).
    • Local variables declared inside methods do not receive default values and generate compile errors if evaluated uninitialized.
    • Type Inference (var keyword): Java 10+ permits local variable type inference: var amount = 100; (infers int), var interestRate = 12.0; (infers double), var stockCode = "D465U"; (infers String), var limit = 1000L; (infers long).
    • var restrictions: Applies only to local variables inside methods; requires an immediate initialization value; cannot declare multiple variables in a single statement.
  • Arithmetic Operators, Integer Division, and Precedence:

    • Binary operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus / remainder).
    • Integer Division: When both operands are integers, fractional remainders are truncated, discarding decimals entirely (e.g., 1/2=01 / 2 = 0).
    • Precedence Hierarchy:
    • Unary Negation (-): Right-to-left associativity.
    • Multiplicative (*, /, %): Left-to-right associativity.
    • Additive (+, -): Left-to-right associativity.
    • Worked evaluation examples:
      • x = -4 + 3; evaluates to −1-1.
      • x = -4 + 4 % 3 * 13 + 2; evaluates to 1111.
      • x = 6 + 3 - 4 + 6 * 3; evaluates to 2323.
    • Parentheses override standard operator precedence; innermost groups process first.
  • Interactive Java Shell (JShell):

    • Command-line REPL tool launched via jshell.
    • Evaluates Java statements immediately without wrapping classes or main methods.
    • Utility commands: /vars (displays declared variables), /list (lists session history), /exit (terminates JShell).
  • Combined Assignment Operators:

    • Shortcut operations combining arithmetic with assignment: +=, -=, *=, /=, %= (e.g., x += 5 translates to x = x + 5).
  • Constants (final Keyword):

    • Modifying variable declarations with final locks the identifier against re-assignment: final double CAL_SALES_TAX = 0.725;.
    • Constants must be initialized before use and generate compilation errors if assigned again.
  • Primitive vs. Reference Variables:

    • Primitive variables hold their assigned primitive values directly in assigned memory cells.

    • Reference variables store the memory heap address pointing to an object instance.      String Reference Memory Address

    • String objects can be instantiated via literal shortcuts (String city = "Charleston";) or class creation (String city = new String("Charleston");).

    • Strings are immutable (cannot be altered in place). Object operations like .length() return values; operations altering string structure produce entirely new String instances.

  • Comments and Documentation Generation:

    • //: Single-line comment.
    • /* ... */: Multi-line block comment.
    • /** ... */: Javadoc block comment processed by the javadoc utility command (javadoc Comment3.java) to produce HTML documentation (index.html).
  • Keyboard Input via Scanner:

    • Requires importing utility package: import java.util.Scanner;.
    • Instantiated using System.in: Scanner keyboard = new Scanner(System.in);.
    • Reading methods: nextLine(), nextInt(), nextDouble(), nextByte(), nextShort(), nextLong(), nextFloat(), nextBoolean(), next().

Decision Structures and Logic

  • The if Statement and Relational Operators:

    • Evaluates a boolean condition to conditionally execute a single statement or enclosed block.      If Statement Flowchart

    • Relational Operators: > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to), == (equal to), != (not equal to).

    • Conditionally executed statement blocks must be enclosed within curly braces {}.

  • Flags and Character Comparisons:

    • A flag is a boolean variable holding true or false to monitor program state.
    • Characters can be compared directly with relational operators based on their underlying Unicode numerical values (e.g., 'A' < 'Z' evaluates to true).
  • The if-else and Nested Decision Structures:

    • if-else defines mutually exclusive execution paths for true and false conditions.      If-Else Flowchart

    • Nested if statements test secondary conditions only if primary outer conditions evaluate to true.

    • else blocks align automatically with the nearest unmatched preceding if statement unless overridden by block curly braces.

  • The if-else-if Chain:

    • Simplifies multi-branch decision structures without deep nesting clutter.      If-Else-If Flowchart
  • Logical Operators and Truth Mechanics:

    • && (Logical AND): Binary operator. Returns true if and only if both expressions evaluate to true.
    • || (Logical OR): Binary operator. Returns true if either or both expressions evaluate to true.
    • ! (Logical NOT): Unary operator. Reverses the logical boolean state of an expression.
    • Short-Circuit Evaluation: && immediately terminates evaluation and returns false if its first operand is false. || immediately terminates evaluation and returns true if its first operand is true.
  • Operator Precedence Matrix:

    1. Unary Negation (-), Logical NOT (!)
    2. Multiplicative (*, /, %)
    3. Additive (+, -)
    4. Relational (<, >, <=, >=)
    5. Equality (==, !=)
    6. Logical AND (&&)
    7. Logical OR (||)
    8. Assignment / Combined Assignment (=, +=, -=, *=, /=, %=)
  • String Object Comparisons:

    • Relational == evaluates reference equality (whether two variables store the identical heap address).
    • Content comparison methods: .equals(String second), .equalsIgnoreCase(String second).
    • Order comparison methods: .compareTo(String second) and .compareToIgnoreCase(String second). Returns 00 if equal, a negative integer if the calling string precedes the argument alphabetically, or a positive integer if it follows.
  • The Conditional Operator (Ternary):

    • Compact decision format: BooleanExpression ? Value1 : Value2; (e.g., z = x > y ? 10 : 5;).
  • The switch Statement and Modern Extensions:

    • Branches program flow based on ordinal values (char, byte, short, int, or String).
    • Traditional switch: Uses case CaseExpression: labels, ending blocks with explicit break; statements to prevent falling through to subsequent cases, and an optional default: label.
    • Multi-Value Case Labels (Java 12+): Comma-separated values per case label: case 1, 3, 5, 7, 9:.
    • Arrow Case Syntax (Java 12+): Uses -> arrow syntax (case 1 -> System.out.println("January");). Automatically breaks execution without fall-through. Multiple statements require block braces {}.
    • switch Expressions (Java 12+): Evaluates a switch structure directly as a returnable expression assigned to a variable: java String numstring = switch(number) { case 0 -> "Zero"; case 1 -> "One"; default -> "Unknown"; }; &nbsp;&nbsp;&nbsp;&nbsp;
    • Must be exhaustive (must cover all potential inputs, usually via a default branch).
    • If multi-statement blocks are used within switch expression branches, the yield keyword yields the value (e.g., yield "OK";).
  • Formatted Console Output (printf and String.format):

    • Method signature: System.out.printf(FormatString, ArgList);.      printf Specifier

    • Format Specifiers:

    • %d: Decimal integer (byte, short, int, long).

    • %f: Floating-point (float, double).

    • %s: String reference.

    • Formatting Flags:

    • Precision: %.2f (rounds floating-point values to 2 decimal places).

    • Thousands Comma Separators: %,.2f (formats 5874.127 as 5,874.13).

    • Field Width: %6d (pads output right-aligned across 6 character spaces); %6.2f (pads to field width 6 with 2 decimals precision).

    • String.format() mirrors printf syntax but returns a constructed formatted string reference rather than displaying it to the console.

Loops, File I/O, and Random Numbers

  • Increment and Decrement Operators:

    • Unary operators ++ and -- add or subtract 11 from a variable.
    • Prefix vs Postfix Mechanics:
    • Prefix (++x, --x): Increments/decrements variable before expression evaluation.
    • Postfix (x++, x--): Increments/decrements variable after expression evaluation.
  • The while Loop:

    • Pre-test loop. Evaluates boolean condition prior to executing body statements.      While Loop Flowchart

    • Executes 00 or more times. Omitting loop variable updates creates infinite loops.

    • Used heavily for input validation routines (looping continuously while input values are outside acceptable ranges).

  • The do-while Loop:

    • Post-test loop. Executes body statements first, then evaluates condition at loop bottom.      Do-While Loop Flowchart

    • Always executes at least once. Syntactically terminated with a semicolon after the test condition: while (condition);.

  • The for Loop:

    • Pre-test counting loop organizing initialization, test, and update in one header: for (initialization; test; update).      For Loop Flowchart

    • Variables declared inside the initialization statement have local scope limited strictly to the loop.

    • Multiple initialization/update expressions are comma-separated: for (int i = 5, j = 0; i < 10; i++, j += 2).

    • Omitting test expressions defaults condition to true (creating an infinite loop: for (;;)).

  • Accumulators and Sentinel Values:

    • An accumulator is a variable initialized to 00 used to aggregate running totals across loop iterations.
    • A sentinel value is a designated dummy value (such as −1-1 or -99) entered by users to signal input termination.
  • Nested Loops and Control Alteration:

    • Inner loops execute completely through all iterations for every single outer loop iteration.
    • break: Abruptly terminates loop completely.
    • continue: Abruptly skips remaining statements in current iteration, advancing to loop update/test phase.
  • Text File Output (PrintWriter and FileWriter):

    • Writing text files uses PrintWriter: PrintWriter outputFile = new PrintWriter("StudentData.txt");.      PrintWriter Structure

    • File I/O classes require file package import: import java.io.*;.

    • Instantiating PrintWriter directly overwrites existing files. Appending to existing files requires wrapping FileWriter: PrintWriter fw = new PrintWriter(new FileWriter("names.txt", true));.

    • File paths must handle backslashes correctly in string literals (e.g., "D:\\PriceList.txt") or use Unix-style forward slashes ("/home/user/names.txt").

    • Files must be closed explicitly (outputFile.close()) to flush buffered buffer data to disk.

  • Text File Input (File and Scanner):

    • File reading combines File and Scanner objects: Scanner inputFile = new Scanner(new File("Customers.txt"));.      Scanner File Object

    • Iterating through files uses hasNext() loop checks: while (inputFile.hasNext()).

  • Exception Handling for File Operations:

    • Instantiate PrintWriter or Scanner with file streams can throw an IOException. Methods calling file constructors must declare exceptions using method header clauses: public static void main(String[] args) throws IOException.
  • Automated Resource Management (try-with-resources):

    • Automatically closes file streams upon block exit: java try (PrintWriter outputFile = new PrintWriter("myfile.txt")) { outputFile.println("Hello"); } &nbsp;&nbsp;&nbsp;&nbsp;
    • Multiple resources are separated by semicolons within the try block header.
  • Generating Random Numbers (Random Class):

    • Utility class imported from package: import java.util.Random;.
    • Instantiated as generator object: Random rand = new Random();.
    • Key methods:
    • nextInt(): Returns random integer across entire int range (−2,147,483,648-2,147,483,648 to +2,147,483,648+2,147,483,648).
    • nextInt(int n): Returns random integer from 00 up to nn (0≤value≤n0 \le \text{value} \le n).
    • nextDouble(): Returns random double between 0.00.0 and 1.01.0.
    • nextFloat(): Returns random float between 0.00.0 and 1.01.0.

Method Design and Modularization

  • Fundamentals of Methods:

    • Methods break programs into small, manageable components (functional decomposition / divide-and-conquer) and enable code reuse.
    • void Methods: Perform a sequence of statements and terminate without returning a value.
    • Value-Returning Methods: Perform operations and return a calculated value back to the calling statement.
  • Method Definition Structure:

    • Consists of Method Header and Method Body.      Method Declaration Header and Body

    • Header Breakdown:      Method Header Components

    • Modifiers: public (method accessible outside class) and static (method belongs to class rather than an instantiated object).

    • Return Type: void or a specific primitive/reference data type.

    • Method Name: Descriptive identifier (lower camelCase).

    • Parameters: Parenthesized list of variable declarations receiving passed argument values.

  • Passing Arguments and Parameters:

    • Arguments are values passed into a method call statement (displayValue(5);). Parameters are local variables declared in method headers receiving those values (public static void displayValue(int num)).      Passing Parameter Value

    • Data type compatibility enforces widening conversions automatically; narrowing conversions (e.g., passing a double argument into an int parameter) produce compilation errors.

    • Argument order in multi-parameter methods must match parameter lists strictly.

  • Pass-by-Value Mechanics:

    • All primitive data type arguments are passed by value in Java. Only a copy of the argument value is passed into parameter variables. Modifying parameter variables inside methods has zero effect on caller variables.
  • Passing Reference Objects and String Immutability:

    • Passing object instances (such as Strings) copies the memory heap address reference into the method parameter variable.      Passing Object Reference

    • Because Strings are immutable, reassigning parameter strings inside methods (str = "Joe";) instantiates a new String object address, leaving the caller's original reference pointing to its original object.

  • Javadoc Method Tags:

    • Documenting parameter descriptions: @param parameterName Description.
    • Documenting return value descriptions: @return Description.
    • Tags are placed inside Javadoc block comments (/** ... */) after main narrative descriptions.
  • Local Variable Lifetime and Scope:

    • Local variables exist strictly while their enclosing method executes. They are destroyed upon method exit, discarding stored values.
    • Different methods can declare local variables using identical identifier names without conflict.
  • Value-Returning Method Mechanics:

    • Must specify explicit return type in method header and include at least one return statement.      Returning Value Breakdown

    • The returned expression data type must be compatible with the method header return type.

    • Methods can return boolean values to construct custom validation routines.

    • Methods can construct and return object references (such as String references constructed via concatenation).

  • Exception Propagation in Methods:

    • If a method calls another sub-method throwing a checked exception (such as IOException), the calling method must either handle the exception locally or declare the identical throws IOException clause in its own header.