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.

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).

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.

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 bits (binary digits).
A bit represents an electronic switch that is either off () or on ().
Each individual byte is assigned a unique numerical memory address.

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 (s and s). 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
.javafile extension.Standard compilers convert source code into executable files containing CPU-specific machine language.
The Java compiler (
javac) converts.javasource code into an intermediate format called byte code instructions, stored in files with a.classextension.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.

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 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.javacompiles the source file intoPayroll.classbyte code. - Executing:
java Payrollinvokes the JVM to runPayroll.class(the.classextension is omitted in the execution command). - Single-Command Execution (Java 11+):
java Payroll.javacompiles the program in memory and executes it immediately without generating a physical.classfile 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.

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

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.

Java Fundamentals and Syntax
Anatomy of a Java Program:
- A Java source file contains one or more classes. If a file contains a
publicclass, the filename must match that class name exactly (e.g.,public class Simplemust reside inSimple.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
;.
- A Java source file contains one or more classes. If a file contains a
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.
- Console execution uses standard output (
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;.
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).
- The
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).
- Identifier rules: May contain letters (
Primitive Data Types:
- Built-in types categorized into integer, floating-point, boolean, and character sets:
byte: byte. Integer range to .short: bytes. Integer range to .int: bytes. Integer range to .long: bytes. Integer range to .float: bytes. Floating-point range to ( decimal digits precision).double: bytes. Floating-point range to ( decimal digits precision).boolean: Logical valuestrueorfalse.char: bytes. Holds single characters encoded in Unicode.
Floating-Point Literals and Notation:
- Embedded floating-point literals default to the
doubledata type. - Assigning a literal decimal to a
floatvariable causes a compilation error unless explicitly postfixed withForf(e.g.,float number = 23.5F;). - Floating-point literals cannot contain commas or currency symbols.
- Scientific and E-Notation conversions:
- Embedded floating-point literals default to the
Unicode Character System:
- Characters are mapped internally to numbers. Java uses Unicode, a 16-bit encoding scheme capable of representing unique characters.
- The first Unicode entries correspond directly to ASCII (American Standard Code for Information Interchange).
charliterals use single quotation marks ('A'), whereasStringliterals use double quotation marks ("A").
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 (
varkeyword): Java 10+ permits local variable type inference:var amount = 100;(infersint),var interestRate = 12.0;(infersdouble),var stockCode = "D465U";(infersString),var limit = 1000L;(inferslong). varrestrictions: Applies only to local variables inside methods; requires an immediate initialization value; cannot declare multiple variables in a single statement.
- Assignment uses equal sign
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., ).
- 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 .x = -4 + 4 % 3 * 13 + 2;evaluates to .x = 6 + 3 - 4 + 6 * 3;evaluates to .
- Parentheses override standard operator precedence; innermost groups process first.
- Binary operators:
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).
- Command-line REPL tool launched via
Combined Assignment Operators:
- Shortcut operations combining arithmetic with assignment:
+=,-=,*=,/=,%=(e.g.,x += 5translates tox = x + 5).
- Shortcut operations combining arithmetic with assignment:
Constants (
finalKeyword):- Modifying variable declarations with
finallocks 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.
- Modifying variable declarations with
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.

Stringobjects 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 thejavadocutility 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().
- Requires importing utility package:
Decision Structures and Logic
The
ifStatement and Relational Operators:Evaluates a boolean condition to conditionally execute a single statement or enclosed block.

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
booleanvariable holdingtrueorfalseto monitor program state. - Characters can be compared directly with relational operators based on their underlying Unicode numerical values (e.g.,
'A' < 'Z'evaluates totrue).
- A flag is a
The
if-elseand Nested Decision Structures:if-elsedefines mutually exclusive execution paths for true and false conditions.
Nested
ifstatements test secondary conditions only if primary outer conditions evaluate totrue.elseblocks align automatically with the nearest unmatched precedingifstatement unless overridden by block curly braces.
The
if-else-ifChain:- Simplifies multi-branch decision structures without deep nesting clutter.

- Simplifies multi-branch decision structures without deep nesting clutter.
Logical Operators and Truth Mechanics:
&&(Logical AND): Binary operator. Returnstrueif and only if both expressions evaluate totrue.||(Logical OR): Binary operator. Returnstrueif either or both expressions evaluate totrue.!(Logical NOT): Unary operator. Reverses the logical boolean state of an expression.- Short-Circuit Evaluation:
&&immediately terminates evaluation and returnsfalseif its first operand isfalse.||immediately terminates evaluation and returnstrueif its first operand istrue.
Operator Precedence Matrix:
- Unary Negation (
-), Logical NOT (!) - Multiplicative (
*,/,%) - Additive (
+,-) - Relational (
<,>,<=,>=) - Equality (
==,!=) - Logical AND (
&&) - Logical OR (
||) - Assignment / Combined Assignment (
=,+=,-=,*=,/=,%=)
- Unary Negation (
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 if equal, a negative integer if the calling string precedes the argument alphabetically, or a positive integer if it follows.
- Relational
The Conditional Operator (Ternary):
- Compact decision format:
BooleanExpression ? Value1 : Value2;(e.g.,z = x > y ? 10 : 5;).
- Compact decision format:
The
switchStatement and Modern Extensions:- Branches program flow based on ordinal values (
char,byte,short,int, orString). - Traditional
switch: Usescase CaseExpression:labels, ending blocks with explicitbreak;statements to prevent falling through to subsequent cases, and an optionaldefault: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{}. switchExpressions (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"; }; - Must be exhaustive (must cover all potential inputs, usually via a
defaultbranch). - If multi-statement blocks are used within switch expression branches, the
yieldkeyword yields the value (e.g.,yield "OK";).
- Branches program flow based on ordinal values (
Formatted Console Output (
printfandString.format):Method signature:
System.out.printf(FormatString, ArgList);.
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(formats5874.127as5,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()mirrorsprintfsyntax 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 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.
- Unary operators
The
whileLoop:Pre-test loop. Evaluates boolean condition prior to executing body statements.

Executes 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-whileLoop:Post-test loop. Executes body statements first, then evaluates condition at loop bottom.

Always executes at least once. Syntactically terminated with a semicolon after the test condition:
while (condition);.
The
forLoop:Pre-test counting loop organizing initialization, test, and update in one header:
for (initialization; test; update).
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 used to aggregate running totals across loop iterations.
- A sentinel value is a designated dummy value (such as 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 (
PrintWriterandFileWriter):Writing text files uses
PrintWriter:PrintWriter outputFile = new PrintWriter("StudentData.txt");.
File I/O classes require file package import:
import java.io.*;.Instantiating
PrintWriterdirectly overwrites existing files. Appending to existing files requires wrappingFileWriter: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 (
FileandScanner):File reading combines
FileandScannerobjects:Scanner inputFile = new Scanner(new File("Customers.txt"));.
Iterating through files uses
hasNext()loop checks:while (inputFile.hasNext()).
Exception Handling for File Operations:
- Instantiate
PrintWriterorScannerwith file streams can throw anIOException. Methods calling file constructors must declare exceptions using method header clauses:public static void main(String[] args) throws IOException.
- Instantiate
Automated Resource Management (
try-with-resources):- Automatically closes file streams upon block exit:
java try (PrintWriter outputFile = new PrintWriter("myfile.txt")) { outputFile.println("Hello"); } - Multiple resources are separated by semicolons within the
tryblock header.
- Automatically closes file streams upon block exit:
Generating Random Numbers (
RandomClass):- Utility class imported from package:
import java.util.Random;. - Instantiated as generator object:
Random rand = new Random();. - Key methods:
nextInt(): Returns random integer across entireintrange ( to ).nextInt(int n): Returns random integer from up to ().nextDouble(): Returns randomdoublebetween and .nextFloat(): Returns randomfloatbetween and .
- Utility class imported from package:
Method Design and Modularization
Fundamentals of Methods:
- Methods break programs into small, manageable components (functional decomposition / divide-and-conquer) and enable code reuse.
voidMethods: 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.

Header Breakdown:

Modifiers:
public(method accessible outside class) andstatic(method belongs to class rather than an instantiated object).Return Type:
voidor 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)).
Data type compatibility enforces widening conversions automatically; narrowing conversions (e.g., passing a
doubleargument into anintparameter) 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.

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.
- Documenting parameter 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
returnstatement.
The returned expression data type must be compatible with the method header return type.
Methods can return
booleanvalues to construct custom validation routines.Methods can construct and return object references (such as
Stringreferences 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 identicalthrows IOExceptionclause in its own header.
- If a method calls another sub-method throwing a checked exception (such as