Programming with Java

1

What is a Computer?

1.1 What is a Computer?

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Computers are programmable electronic devices that enable users to store, retrieve, and process data through instructions written in programming languages like Java.

๐Ÿ“Œ Key points (3โ€“5)

  • What a computer is: an electronic, programmable device for storing, retrieving, and processing information.
  • What programming does: translates human-written code into instructions that computers can execute to perform specific tasks.
  • Java's role: a popular, platform-independent programming language introduced in 1995 that works across different operating systems.
  • Source code basics: the .java file containing programming statements that compilers transform into executable output.
  • Common confusion: class name vs. file nameโ€”in Java, the source code file name must match the class name (e.g., "SampleClass" โ†’ "SampleClass.java").

๐Ÿ’ป Understanding computers and programming

๐Ÿ’ป What a computer does

A computer is an electronic and programmable device that allows users to store, retrieve, and process information and data.

  • The excerpt emphasizes three core capabilities: store, retrieve, and process.
  • "Programmable" means the computer can be given different instructions to perform different tasks.
  • Computers execute mathematical calculations and logical computations when given appropriate instructions.

๐Ÿ“ What computer programming is

Computer Programming is a process of writing code that can translate into instructions for a computer system.

  • Programming allows programmers to write a set of instructions to perform specific tasks.
  • It acts as a translation layer: human-readable code โ†’ computer-executable instructions.
  • Many programming languages exist (Java, C, C++, C#, Python); different programmers prefer different languages.

โ˜• Java programming language

โ˜• What Java is

  • Java is described as a "popular computer programming language."
  • Platform-independent: works across almost all operating systems (Windows, Linux, OSX, etc.).
  • First introduced in 1995 by Sun Microsystems.
  • Has evolved since introduction; many modern applications are developed using Java.

๐Ÿ“„ Source code and file naming

Programming statements are also known as source code. In Java, programming source code means the .java file where programmers write and save their programming statements.

  • Source code = the .java file containing programming statements.
  • Compilers use source code to generate object codes or output files.
  • Critical rule: the class name and the source code file name must be the same.
  • Example: a class named "SampleClass" must be saved as "SampleClass.java."

๐Ÿ”ง Basic Java program structure

๐Ÿ”ง Key components

The excerpt walks through a simple Java program with these elements:

ComponentWhat it doesLine reference
Class declarationDefines the class name and opens with {Line 1
Main methodEntry point where program execution beginsLines 2-5
Print statementBuilt-in function to display messages on screenLine 4
Closing braceEnds the class definition with }Line 6

๐Ÿ’ฌ Comments in code

  • Single-line comments use // โ€” anything after // is ignored by the compiler.
  • Programmers use comments to explain code without affecting execution.
  • Multi-line comments use /* ... */ (called "block comments").
  • Example from excerpt: // print "Hello Class!!" on the screen when this program runs

๐Ÿ–จ๏ธ Output mechanism

  • System.out.println(); is the built-in function to display output.
  • Whatever appears within the double quotes "" will be displayed on the screen.
  • Example: System.out.println("Hello Class!!"); outputs Hello Class!!
  • Don't confuse: the quotes are part of the syntax, not part of the output.
2

What is Computer Programming?

1.2 What is Computer Programming?

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Computer programming enables humans to write instructions that computers can execute to perform specific tasks, bridging human intent and machine action.

๐Ÿ“Œ Key points (3โ€“5)

  • What programming is: the process of writing code that translates into instructions for a computer system.
  • Purpose: allows programmers to write a set of instructions to perform specific tasks.
  • Language variety: many programming languages exist, and different programmers prefer different ones.
  • Common confusion: programming statements vs. source codeโ€”source code is the .java file where statements are written and saved.
  • From code to execution: compilers use source code to generate object codes or output files.

๐Ÿ’ป Understanding computer programming

๐Ÿ’ป What programming does

Computer Programming: a process of writing code that can translate into instructions for a computer system.

  • Programming is not just "using a computer"; it is creating the instructions the computer will follow.
  • The excerpt emphasizes translation: human-readable code becomes machine-executable instructions.
  • In other words, programming allows programmers to write a set of instructions to perform specific tasks.

๐ŸŒ Language diversity

  • There are many programming languages available.
  • Different programmers like different languagesโ€”no single "best" language for everyone.
  • The excerpt mentions Java, C, C++, C#, and Python as examples of different types of computer programming languages.
  • Example: one programmer might choose Python for data analysis, another might choose Java for cross-platform applications.

๐Ÿ“ Source code and compilation

๐Ÿ“ What is source code

Source code: programming statements; in Java, the .java file where programmers write and save their programming statements.

  • Source code is the human-written text that contains programming instructions.
  • It is not the final executable program; it must be processed first.
  • Example: the SampleClass example in the excerpt is source code saved as "SampleClass.java."

โš™๏ธ From source to execution

  • Compilers use source code to generate object codes or output files.
  • The process: programmer writes source code โ†’ compiler translates it โ†’ computer executes the result.
  • Don't confuse: source code (what you write) vs. object code (what the compiler produces).

๐Ÿ”ง Practical elements

๐Ÿ”ง Comments in code

  • Programmers use "//" to write single-line programming comments.
  • Anything written using "//" will not be checked by the compiler.
  • For multi-line comments, use "/* โ€ฆ */", known as a block comment.
  • Purpose: comments help explain code to other programmers (or yourself later) without affecting how the program runs.

๐Ÿ”ง Assignment concept

  • The excerpt introduces "assigned" as giving a value to a variable or a constant.
  • This is a fundamental operation in programming: storing data for later use.
3

What is Java? History of Java

1.3 What is Java? History of Java

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java is a widely-used, platform-independent programming language introduced in 1995 that has evolved into a foundation for many modern computer applications.

๐Ÿ“Œ Key points (3โ€“5)

  • What Java is: a popular computer programming language that works across different operating systems.
  • Platform independence: Java runs on almost all types of operating systems (Windows, Linux, OSX, etc.).
  • Historical context: first introduced in 1995 by Sun Microsystems and has evolved since then.
  • Current relevance: many computer applications today are developed using Java.

๐ŸŒ Java as a Programming Language

๐Ÿ’ป What Java is

Java is a popular computer programming language.

  • Java is one of many programming languages available to programmers (others mentioned include C, C++, C#, and Python).
  • Different programmers prefer different languages, but Java is commonly used.
  • The excerpt positions Java within the broader context of computer programming, which is "a process of writing code that can translate into instructions for a computer system."

๐Ÿ”„ Platform independence

The defining characteristic emphasized in the excerpt:

  • Platform-independent language: Java works in almost all types of operating systems.
  • Specific operating systems mentioned: Windows, Linux, OSX, and similar systems.
  • This means the same Java code can run on different platforms without modification.

๐Ÿ“œ History and Evolution

๐Ÿ•ฐ๏ธ Introduction and origin

  • When: Java was first introduced in 1995.
  • By whom: Sun Microsystems introduced Java.
  • The excerpt notes this as a starting point for Java's development.

๐Ÿ“ˆ Evolution over time

  • Since its introduction in 1995, Java has evolved.
  • The excerpt does not detail specific versions or changes, but emphasizes continuous development.
  • Current state: Today, many computer applications are developed using Java programming language.
  • This indicates Java's sustained relevance and adoption in the software development industry.
4

A Sample Java Program

1.4 A Sample Java Program

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

A Java program consists of a class containing a main method where executable statements are written, and understanding its structureโ€”including comments, output statements, and naming rulesโ€”is essential for writing valid Java code.

๐Ÿ“Œ Key points (3โ€“5)

  • Basic structure: A Java program requires a class with a main method, enclosed in curly braces, where the class name must match the filename.
  • Output mechanism: The System.out.println() function displays messages on the screen; whatever is inside the double quotes appears as output.
  • Comments: Programmers use // for single-line comments and /* ... */ for multi-line block comments; compilers ignore these.
  • Variables vs constants: Variables hold values that can change during program execution, while constants hold values that cannot change once assigned.
  • Common confusion: Reserved keywords (like public, class, static, void, int, double) cannot be used as variable names; variable names must follow specific declaration rules.

๐Ÿ“ Program structure and anatomy

๐Ÿ“ Class and main method

  • Line 1 declares the class name (e.g., "SampleClass") followed by an opening curly brace {.
  • Line 2 starts the main method: public static void main(String args[]).
  • The main method ends at line 5, and the class closes with } at line 6.
  • Critical rule: The filename must match the class nameโ€”if the class is "SampleClass," the file must be "SampleClass.java."

๐Ÿ’ฌ Output and comments

System.out.println(): A built-in function that prints messages to the screen.

  • Whatever text is placed within the double quotes "" will be displayed as output.
  • Example: System.out.println("Hello Class!!"); outputs Hello Class!! on the screen.

Comment syntax:

  • Single-line: // makes the compiler ignore everything after it on that line.
  • Multi-line (block): /* ... */ allows comments spanning multiple lines.
  • Purpose: Programmers use comments to explain code without affecting compilation.

๐Ÿ”ค Source code and identifiers

๐Ÿ”ค What is source code

Source code: Programming statements written in a .java file.

  • In Java, source code refers to the .java file where programmers write their statements.
  • Compilers use source code to generate object codes or output files.
  • The example program shown is a Java source code.

๐Ÿท๏ธ Identifiers

Identifier: A name that helps identify something uniquely within a program.

  • What can be identifiers: Variable names, class names, packages, methods, and functions.
  • Purpose: Enable unique identification within the program context.
  • Example: A class name identifies the class uniquely; a variable name identifies a memory location that holds a value.
  • Don't confuse: An identifier is the name itself, while a variable is a memory location that holds a value.

๐Ÿ”ข Variables and constants

๐Ÿ”ข Variables

Variable: A data item that holds a value, and the value can change over time.

  • Variables are designed to hold values within memory locations.
  • The value can be changed while a program is running.
  • Different declaration methods depend on the data type: integer, floating point, string, character, etc.

๐Ÿ”’ Constants

Constant: A variable whose value cannot change once assigned.

  • Unlike variables, constants maintain the same value throughout program execution.
  • The excerpt notes that "assigned" means giving a value to a variable or constant using the = operator.

๐Ÿšซ Reserved keywords

The following words are reserved and cannot be used to create variables:

  • public
  • class
  • static
  • void
  • int
  • double

๐Ÿ“‹ Variable declaration rules

๐Ÿ“‹ Five essential rules

  1. Start with type: A variable declaration must begin with a variable type (e.g., int, double, string, char).
  2. Name must start with letter: Variable names must begin with a letter (upper-case or lower-case alphabet), not with a number or digit.
  3. No reserved keywords: Reserved keywords cannot be used as variable names.
  4. No mathematical operators: Mathematical operators cannot be used in variable names.
  5. Unique names: Variable names must be unique within a context.

๐Ÿ“‹ How to declare

To declare or create a variable, a programmer needs:

  1. The type of variable first
  2. The name of the variable
  3. The initial value of the variable (optional but advised)

Example: The excerpt mentions that although the initial value is not required, it is recommended to provide one.

5

What is Source Code?

1.5 What is Source Code?

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Source code is the collection of programming statements written in a .java file that compilers transform into executable object code or output files.

๐Ÿ“Œ Key points (3โ€“5)

  • What source code is: programming statements written and saved in a .java file.
  • How compilers use it: compilers read source code to generate object codes or output files.
  • Assignment operator: the "=" operator is used to give a value to a variable or constant.
  • Variables vs constants: variables hold values that can change over time; constants hold values that cannot change once assigned.
  • Common confusion: reserved keywords (like public, class, static) cannot be used as variable names.

๐Ÿ“ Source code fundamentals

๐Ÿ“ What source code means

Programming statements are also known as source code. In Java, programming source code means the .java file where programmers write and save their programming statements.

  • Source code is not the compiled output; it is the human-written input.
  • The excerpt emphasizes that source code is what programmers write and save.
  • Example: the "SampleClass" code shown earlier (lines 1โ€“6 with public class SampleClass and the main method) is a Java source code.

โš™๏ธ How compilers use source code

  • Compilers take source code as input.
  • They generate object codes or output files from it.
  • The source code must follow Java syntax rules for the compiler to process it correctly.

๐Ÿ”ง Assignment in Java

In Java programming, "assigned" refers to giving a value to a variable or a constant. We use "=" operator to accomplish this.

  • The "=" operator is the assignment operator.
  • It places a value into a variable or constant.
  • Example: int a = 12; assigns the value 12 to variable a.

๐Ÿ—‚๏ธ Variables and constants

๐Ÿ—‚๏ธ Variables

A variable is a data item that holds a value, and the value of a variable can change over time.

  • Variables store data in memory locations.
  • Their values can be updated while a program runs.
  • Variables must be declared with a type (e.g., int, double, string, char).

๐Ÿ”’ Constants

A constant is a variable whose value cannot change once assigned.

  • Once a constant receives a value, that value is fixed.
  • Don't confuse: a constant is still called a "variable" in the excerpt, but its defining feature is immutability after assignment.

๐Ÿšซ Reserved words / keywords

  • Java reserves certain words that cannot be used as variable names.
  • Examples listed in the excerpt: public, class, static, void, int, double.
  • These keywords have special meaning in Java syntax and are off-limits for naming variables.

๐Ÿท๏ธ Identifiers and naming

๐Ÿท๏ธ What an identifier is

The identifier helps to identify something uniquely. For example, within a program, variable names can be identifiers that enable us to identify uniquely the variables within the program.

  • Identifiers are names that uniquely identify program elements.
  • They can name variables, classes, packages, methods, and functions.
  • Example: a class name like "SampleClass" is an identifier; a variable name like a is also an identifier.

๐Ÿท๏ธ Variable names as identifiers

  • A variable name is given to a memory location that holds a value.
  • The name allows the programmer to refer to that memory location uniquely.
  • The excerpt emphasizes that identifiers enable unique identification within the program.

๐Ÿ“‹ Rules for declaring variables

๐Ÿ“‹ Five key rules

The excerpt lists five rules for variable declaration in Java:

RuleDescription
1. Start with a typeDeclaration must begin with a variable type (e.g., int, double, string, char)
2. Name must start with a letterVariable names must begin with an upper-case or lower-case letter, not a number or digit
3. No reserved keywordsReserved keywords cannot be used as variable names
4. No mathematical operatorsMathematical operators cannot be used in variable names
5. Unique namesVariable names must be unique within a context

๐Ÿ“‹ How to declare a variable

The general syntax is:

type variablename = value ;
  • Type comes first (e.g., int).
  • Variable name follows.
  • Initial value is optional but advised; some compilers may warn if a variable is not initialized.
  • Example: int a = 12; declares an integer variable a and assigns it the value 12.
  • Multiple variables of the same type can be declared together: int a = 12, b = 13; (separated by commas).

๐Ÿ“‹ Declaration vs initialization

  • Declaration: stating the type and name (e.g., int a;).
  • Initialization: assigning the first value (e.g., a = 12;).
  • Both can be done in one statement: int a = 12;.
  • The excerpt notes that initialization is not strictly required until the variable is used, but it is recommended to avoid compiler warnings.

๐Ÿ”ข Variable types by value

๐Ÿ”ข Five common types

The excerpt describes five variable types based on the kind of value they store:

TypeWhat it storesExample valuesNotes
intWhole numbers (integers)1, 124, 8080Shortened form of "integer"
stringText data"Hello"Mix of characters and numbers, or just characters/numbers; uses double quotes
floatFloating point numbers199.99, -9.8Numbers with decimals
charSingle characters'a', 'B'Uses single quotes (unlike strings)
booleanTrue or false valuestrue, falseComparison operators also return boolean values

๐Ÿ”ข String vs char

  • String: uses double quotes ("Hello"); can hold multiple characters.
  • Char: uses single quotes ('a'); holds exactly one character.
  • Don't confuse: the quote style and the number of characters differ.

๐Ÿ”ข Boolean values

  • A boolean variable stores either true or false.
  • When printed, it displays true or false on the screen.
  • Comparison operators (not detailed in this excerpt) also return boolean values.
6

Variables and Constants

1.6 Variables and Constants

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Variables and constants are named data items in Java that hold values, with the key difference being that a variable's value can change over time while a constant's value cannot change once assigned.

๐Ÿ“Œ Key points (3โ€“5)

  • What variables and constants are: a variable holds a value that can change; a constant holds a value that cannot change once assigned.
  • How assignment works: the "=" operator is used to give a value to a variable or constant.
  • Identifiers vs variables: identifiers uniquely name things (variables, classes, methods); variable names point to memory locations that hold values.
  • Common confusion: reserved keywords (like public, class, int) cannot be used as variable namesโ€”they are already claimed by Java.
  • Declaration rules: variables must start with a type (e.g., int, double), then a name (starting with a letter, not a digit), and optionally an initial value.

๐Ÿ“ฆ What variables and constants are

๐Ÿ“ฆ Variable definition

A variable is a data item that holds a value, and the value of a variable can change over time.

  • Variables are designed to hold a value within a memory location.
  • That value can be changed while a program is running.
  • Example: you can declare a variable a and assign it 12, then later change it to 13.

๐Ÿ”’ Constant definition

A constant is a variable whose value cannot change once assigned.

  • Once you assign a value to a constant, it is locked in.
  • Don't confuse: a constant is still called a "variable" in the excerpt's wording, but its value is immutable after the first assignment.

๐Ÿ”ง Assignment operator

  • In Java programming, "assigned" refers to giving a value to a variable or a constant.
  • We use the = operator to accomplish this.
  • Example: int a = 12; assigns the value 12 to the variable a.

๐Ÿท๏ธ Identifiers and naming

๐Ÿท๏ธ What an identifier is

The identifier helps to identify something uniquely.

  • Within a program, variable names can be identifiers that enable us to identify uniquely the variables within the program.
  • A class name is an identifier since it helps to identify the class uniquely.
  • Identifiers are often used to name variables, classes, packages, methods, and functions.

๐Ÿ”ค Variable names as identifiers

  • A variable name is given to a memory location that holds a value.
  • The name acts as a unique label so you can refer to that memory location in your code.
  • Don't confuse: the identifier is the name itself; the variable is the memory location that holds the value.

๐Ÿšซ Reserved words and declaration rules

๐Ÿšซ Keywords/Reserved Words

  • There are some words in Java programming that are reserved and cannot be used to create variables.
  • Examples of reserved words include:
    • public
    • class
    • static
    • void
    • int
    • double
  • These words are already claimed by Java for specific purposes, so you cannot name a variable with them.

๐Ÿ“‹ Rules for variable declaration

The following rules should be followed when declaring a variable in Java:

  1. Must begin with a variable type: such as int, double, string, and char.
  2. Variable names must begin with a letter: either upper-case or lower-case alphabet, and not with a number or digit.
  3. Reserved keywords cannot be used: you cannot name a variable int or class, for example.
  4. Mathematical operators cannot be used: operators like +, -, * are not allowed in variable names.
  5. Variable names must be unique within a context: no two variables can have the same name in the same scope.

๐Ÿ› ๏ธ How to declare and initialize variables

๐Ÿ› ๏ธ Declaration syntax

The general pattern for declaring a variable is:

type variablename = value ;
  • Type: the kind of data the variable will hold (e.g., int for integers).
  • Variable name: the identifier you choose (following the rules above).
  • Value: the initial value (optional but advised).

๐Ÿ”ข Declaration and initialization

  • You can declare a variable first, then assign a value later.
  • Or you can declare and initialize at the same time.
  • Example (from the excerpt):
    • Line showing declaration and initialization together: int a = 12;
    • The excerpt notes that initialization is not required until the variable is used, but some compilers may show a warning or error if a variable is not initialized (depending on compiler settings).

๐Ÿ”— Multiple declarations of the same type

  • If you have multiple variables of the same type, you can declare them in one line separated by commas.
  • Example: int a = 12, b = 13;
  • You do not need to repeat the keyword int for each variable; one use of int is enough.
  • Variable declaration must end with a semicolon (;), as all statements must.

๐Ÿ—‚๏ธ Types of variables by value

๐Ÿ—‚๏ธ Overview of variable types

In Java, we use different types of variables to store different types of values:

TypeWhat it storesExample values
intWhole numbers (integers)1, 124, 8080
stringText data (mix of characters and numbers, or just characters, or just numbers)"Hello" (use double quotes)
floatFloating point numbers with decimals199.99, -9.8
charSingle characters'a', 'B' (use single quotes)
booleanTrue or false valuestrue, false

๐Ÿ”ข Integer (int)

  • To store whole numbers, we use an integer type of variable.
  • A shortened form for integer is int.
  • Examples of whole numbers are 1, 124, and 8080.
  • The excerpt references Example 2 to show how an int variable is declared and used in a Java program.

๐Ÿ“ String (string)

  • Stores text data.
  • In general, it can be a mix of characters and numbers, or just characters, or just numbers.
  • We use double quotes to represent string variables, such as "Hello".

๐Ÿ”ข Float (float)

  • Stores floating point numbers, with decimals.
  • Examples: 199.99 or other decimal values.

๐Ÿ”ค Character (char)

  • Stores single characters, such as 'a' or 'B'.
  • Don't confuse: unlike String values, single quotes are used to represent character values (not double quotes).

โœ… Boolean (boolean)

  • Stores true or false values.
  • When printed as a boolean variable, it will show either true or false on the screen.
  • Note that a comparison operator also returns a boolean value (i.e., true or false).
7

Rules for Variable Declaration

1.7 Rules for Variable Declaration

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java variable declaration follows five core rules that govern type specification, naming conventions, and uniqueness to ensure valid and unambiguous code.

๐Ÿ“Œ Key points (3โ€“5)

  • Five mandatory rules: every variable must start with a type, names must begin with a letter, reserved keywords are forbidden, no mathematical operators in names, and names must be unique within their context.
  • Declaration syntax: requires type first, then variable name, optionally followed by an initial value (though initialization is advised).
  • Common confusion: variable type (int, String, float, char, boolean) vs. variable scope (local, instance, static)โ€”the first describes what data it holds, the second describes where it is declared and accessible.
  • Multiple declarations: variables of the same type can be declared together, separated by commas, without repeating the type keyword.
  • Constants vs. variables: constants use the final keyword and cannot be reassigned after initialization, while variables can change value during program execution.

๐Ÿ“œ The Five Core Rules

๐Ÿ“œ Rule 1: Must begin with a variable type

A variable declaration must begin with a variable type, such as int, double, string, and char.

  • The type tells Java what kind of data the variable will hold.
  • Without the type, the compiler cannot allocate the correct memory or enforce type safety.
  • Example: int a declares an integer variable; String name declares a text variable.

๐Ÿ”ค Rule 2: Names must start with a letter

  • Variable names must begin with either an upper-case or lower-case alphabet letter.
  • They cannot start with a number or digit.
  • Example: a1 is valid, but 1a is not.

๐Ÿšซ Rule 3: No reserved keywords

  • Reserved keywords (e.g., public, class, static, void, int, double) cannot be used as variable names.
  • These words have special meaning in Java and are already claimed by the language.
  • Example: you cannot name a variable int or class.

โž— Rule 4: No mathematical operators in names

  • Mathematical operators cannot be used within a variable name.
  • This prevents confusion between variable names and expressions.
  • Example: sum+total is invalid; use sumTotal or sum_total instead.

๐Ÿ†” Rule 5: Names must be unique within a context

  • Each variable name must be unique within its scope (method, class, etc.).
  • Two variables in the same context cannot share the same name.
  • Example: you cannot declare int a twice in the same method.

๐Ÿ› ๏ธ How to Declare Variables

๐Ÿ› ๏ธ Basic declaration syntax

The general pattern is:

type variablename = value;
  • Type: the data type (e.g., int, String, float).
  • Variable name: the identifier you choose.
  • Value: the initial value (optional but advised).
  • Every declaration must end with a semicolon (;).

๐Ÿ”„ Initialization is optional but recommended

  • The excerpt states that the initial value is not required, but it is advised.
  • Some compilers may show a warning or error if a variable is not initializedโ€”this depends on compiler settings.
  • Example: int a; is allowed, but int a = 12; is safer.

๐Ÿ”— Multiple declarations of the same type

  • Variables of the same type can be declared together, separated by commas.
  • You do not need to repeat the type keyword.
  • Example: int a = 12, b = 13; declares both a and b as integers in one statement.

๐Ÿ—‚๏ธ Variable Types by Data They Store

๐Ÿ—‚๏ธ Five common data types

TypeWhat it storesSyntax exampleNotes
intWhole numbersint a = 5;Short for "integer"; examples: 1, 124, 8080
StringText dataString a = "Hello";Mix of characters/numbers or just characters; uses double quotes
floatFloating-point numbersfloat a = 5.3f;Decimals like 199.99; note the f suffix
charSingle characterschar c1 = 'H';Uses single quotes, not double quotes
booleanTrue or false valuesboolean a = true;Prints true or false; comparison operators also return boolean

๐Ÿ” String vs. char confusion

  • String: text of any length, enclosed in double quotes ("Hello").
  • char: exactly one character, enclosed in single quotes ('H').
  • Don't confuse: "H" is a String, 'H' is a char.

๐Ÿ”ข Float notation

  • Float literals require an f suffix: float a = 5.3f;.
  • Without the f, Java treats the number as a double by default.

๐ŸŒ Variable Types by Scope (Where Declared)

๐ŸŒ Three scope categories

TypeWhere declaredScopeExample
Local variableInside a method or functionLimited to that method/functionint a1 = 20; inside display()
Instance variableInside a class, outside methodsAccessible via class instances (objects)public int b = 15; in the class body
Static variableInside a class with static keywordShared among all instances of the classpublic static int a = 10;

๐Ÿ  Local variables

  • Defined within a method or function.
  • Only exist while that method is executing.
  • Example: int a1 = 20; inside display() cannot be accessed outside display().

๐Ÿงฉ Instance variables

  • Defined within a class but outside any method.
  • Each object (instance) of the class has its own copy.
  • Accessed using an object reference: sjc.b where sjc is an object.

๐Ÿ”— Static variables

  • Declared with the static keyword inside a class.
  • Shared among all instancesโ€”only one copy exists for the entire class.
  • Accessed directly via the class name or through any instance.
  • Example: SampleJavaClass.a or sjc.a both refer to the same static variable.

๐Ÿ”„ Reassignment is allowed for variables

  • Variables (local, instance, or static) can have their values changed after initialization.
  • Example: int a1 = 20; a1 = 25; is validโ€”a1 now holds 25.
  • This flexibility distinguishes variables from constants.

๐Ÿ”’ Constants

๐Ÿ”’ What makes a constant

Constants are a type of variable whose values do not change within the program.

  • Declared using the final keyword.
  • Once assigned, the value cannot be changed.
  • Attempting to reassign a constant will cause the compiler to show an error.

๐Ÿ”’ Syntax for constants

final type variablename = value;
  • Example: final double PI = 3.141;
  • The final keyword locks the value.

๐Ÿ”  Naming convention

  • Programmers often use all upper-case letters for constant names.
  • This visual convention separates constants from regular variables.
  • Example: PI, MAX_SIZE, DEFAULT_VALUE.

๐Ÿ”’ Constants vs. variables

  • Variable: value can be reassigned (int a1 = 20; a1 = 25; is valid).
  • Constant: value is fixed after initialization (final int A1 = 20; A1 = 25; causes a compiler error).
  • Don't confuse: both are "variables" in the broad sense (they hold data), but constants are immutable.
8

Constants

1.8 Constants

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Constants are variables whose values cannot change after initialization, enforced by the final keyword, and attempting to reassign them produces a compiler error.

๐Ÿ“Œ Key points (3โ€“5)

  • What constants are: a type of variable whose value remains fixed throughout the program.
  • How to declare: use the final keyword before the type, e.g., final double PI = 3.141;.
  • Scope behavior: even if declared in a different class, the constant's value stays unchanged.
  • Common confusion: constants vs regular variablesโ€”regular variables allow reassignment (e.g., a1 = 25;), but constants do not; the compiler will error if you try.
  • Naming convention: programmers often use all uppercase letters to visually distinguish constants from regular variables.

๐Ÿ”’ What constants are and why they matter

๐Ÿ”’ Definition and immutability

Constants are a type of variable whose values do not change within the program.

  • Unlike regular variables, which can be reassigned (e.g., int a1 = 20; a1 = 25;), constants are locked after their initial value is set.
  • If you attempt to change a constant's value, the compiler will show an error message.
  • This immutability applies even if the constant is declared in a different classโ€”the value remains unchanged across the entire program.

๐Ÿ›ก๏ธ Why use constants

  • They protect values that should never change (e.g., mathematical constants like ฯ€, configuration settings).
  • They make code safer: the compiler catches accidental reassignments.
  • They improve readability: a name like PI is clearer than a "magic number" like 3.141 scattered throughout code.

๐Ÿ“ How to declare and use constants

๐Ÿ“ Syntax

The excerpt provides this syntax:

final type variablename = value;
  • final: the keyword that marks the variable as a constant.
  • type: the data type (e.g., double, int).
  • variablename: the identifier; by convention, often all uppercase.
  • value: the initial (and only) value.

Example from the excerpt:

final double PI = 3.141;

๐Ÿ”ค Naming convention

  • Programmers often use all uppercase letters to define constant variables.
  • This is an attempt to visually separate constants from regular variables.
  • Example: PI (constant) vs radius (regular variable).

๐Ÿ’ก Example walkthrough

The excerpt provides Example 8:

public class CircleClass {
  public static void main(String args[]) {
    // regular double type of variable for the radius
    double radius = 4.2;
    // PI declared as a constant variable
    final double PI = 3.141;
    System.out.println("The area of the circle is: " + (PI*radius*radius));
  }
}

Output:

The area of the circle is: 55.40724000000001
  • radius is a regular variable (can be reassigned).
  • PI is a constant (cannot be reassigned).
  • The program calculates the area using the formula: PI times radius times radius.
  • If you tried to write PI = 3.14159; later in the code, the compiler would error.

๐Ÿ†š Constants vs regular variables

๐Ÿ†š Key differences

AspectRegular variableConstant
Declarationtype variablename = value;final type variablename = value;
ReassignmentAllowed (e.g., a1 = 25;)Not allowedโ€”compiler error
Naming conventionMixed case (e.g., radius)Often all uppercase (e.g., PI)
PurposeValues that may changeValues that must stay fixed

โš ๏ธ Don't confuse

  • Regular variable reassignment (shown in the excerpt):
    int a1 = 20;
    a1 = 25;  // This is allowed
    
  • Constant reassignment attempt:
    final double PI = 3.141;
    PI = 3.14159;  // Compiler error!
    
  • The excerpt explicitly states: "Reassignment would not be possible if a1 was a constant."
9

ASCII Table

1.9 ASCII-Table

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

ASCII encoding provides a standardized way to represent 256 alphabetic, numeric, and special characters as numeric codes (0โ€“255) that computers can process.

๐Ÿ“Œ Key points (3โ€“5)

  • What ASCII is: American Standard Code for Information Interchange, the most widely used character encoding format in computer science.
  • Total character range: 256 characters numbered from 0 to 255, covering alphabetic, numeric, and special characters.
  • Multiple representations: each character can be expressed in decimal (Dec), hexadecimal (Hex), or octal (Oct) notation.
  • Practical use in programming: char variables can be assigned ASCII numeric values directly, and the system will interpret them as the corresponding character.
  • Common confusion: assigning a number to a char variable does not store the number itselfโ€”it stores the character that the ASCII code represents.

๐Ÿ”ข What ASCII encoding is

๐Ÿ”ข Definition and scope

ASCII (American Standard Code for Information Interchange): the most widely used character encoding format in computer science, defining 256 character codes numbered 0 to 255.

  • ASCII assigns a unique numeric code to each character.
  • The 256 codes cover:
    • Control characters (e.g., NUL, TAB, CR, LF)
    • Printable characters: letters (Aโ€“Z, aโ€“z), digits (0โ€“9), punctuation, and symbols
  • This standardization allows different systems to exchange text data reliably.

๐Ÿ”  Character categories in ASCII

The excerpt's tables show three main groups:

Range (Dec)CategoryExamples
0โ€“31Control charactersNUL, TAB, LF, CR, ESC
32โ€“47Space and punctuationSP (space), !, ", #, $, %, &, ', (, ), *, +, comma, -, ., /
48โ€“57Digits0, 1, 2, 3, 4, 5, 6, 7, 8, 9
58โ€“64More punctuation:, ;, <, =, >, ?, @
65โ€“90Uppercase lettersA, B, C, ..., Z
91โ€“96Brackets and symbols[, , ], ^, _, `
97โ€“122Lowercase lettersa, b, c, ..., z
123โ€“127Braces and DEL{, |, }, ~, DEL
  • Control characters (0โ€“31) are non-printable and used for text formatting or communication control.
  • Printable characters start at 32 (space).

๐Ÿงฎ Multiple numeric representations

๐Ÿงฎ Decimal, hexadecimal, and octal

Each ASCII character has three equivalent numeric forms:

  • Decimal (Dec): base-10 numbers (0โ€“255)
  • Hexadecimal (Hex): base-16 numbers (0x00โ€“0xFF)
  • Octal (Oct): base-8 numbers (000โ€“377)

Example from the excerpt:

CharacterDecHexOct
A650x41101
a970x61141
0 (digit)480x30060
!330x21041
  • All three notations refer to the same character.
  • Programmers can use whichever notation is most convenient for their context.

๐Ÿ’ป Using ASCII in programming

๐Ÿ’ป Assigning ASCII codes to char variables

The excerpt provides Example 9, which demonstrates:

char c1 = 72;    // ASCII code for 'H'
char c2 = 105;   // ASCII code for 'i'
char c3 = 33;    // ASCII code for '!'
System.out.println("Output: " + (c1) + (c2) + (c3));

Output: Hi!

  • When you assign a numeric value to a char variable, Java interprets it as the ASCII code and stores the corresponding character.
  • c1 = 72 does not store the number 72; it stores the character 'H'.
  • When printed, the char variables display their character representations, not the numeric codes.

๐Ÿ”„ Why this matters

  • Direct code assignment: you can construct characters by their numeric codes without typing the character itself.
  • Character manipulation: understanding ASCII codes allows you to perform operations like converting between uppercase and lowercase (e.g., 'A' is 65, 'a' is 97; the difference is 32).
  • Don't confuse: assigning char c = 72; is different from assigning int i = 72;โ€”the char will print as 'H', while the int will print as 72.

Example: If you want to output "Hi!" without typing those letters directly, you can use their ASCII codes (72, 105, 33) as shown in the excerpt.

๐Ÿ“š Reference tables

๐Ÿ“š Key ASCII codes to remember

From the excerpt's tables, some commonly used codes:

CharacterDecHexOctNotes
Space (SP)320x20040First printable character
0 (digit)480x30060Start of digit range
9 (digit)570x39071End of digit range
A650x41101Start of uppercase letters
Z900x5A132End of uppercase letters
a970x61141Start of lowercase letters
z1220x7A172End of lowercase letters
TAB90x09011Tab character
LF100x0A012Line feed (newline on Unix)
CR130x0D015Carriage return
DEL1270x7F177Delete character
  • The excerpt emphasizes that the full ASCII table runs from 0 to 255, covering all these ranges.
  • Control characters (0โ€“31, 127) are used for formatting and control, not for displaying text.
10

Widening and Narrowing

1.10 Widening and Narrowing

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Widening and narrowing are type conversions in Java that allow programmers to move values between primitive types of different sizes, with widening happening automatically for smaller-to-larger conversions while narrowing requires explicit casting for larger-to-smaller conversions.

๐Ÿ“Œ Key points (3โ€“5)

  • What widening means: converting a smaller primitive type value to a larger primitive type automatically (also called upcasting).
  • What narrowing means: converting a larger primitive type value to a smaller primitive type using explicit casting (also called downcasting).
  • Key difference: widening is implicit/automatic; narrowing requires explicit cast syntax with parentheses.
  • Common confusion: not all primitive types have the same sizeโ€”byte is smallest (1 byte), long and double are largest (8 bytes), and the order matters for safe conversions.
  • Practical implication: narrowing can lose precision (e.g., 10.5 becomes 10 when narrowed to int).

๐Ÿ“ Primitive type sizes and ranges

๐Ÿ“Š Size hierarchy

The excerpt provides a table showing eight primitive types with their sizes:

Primitive TypeSize in bytesRange
byte1-128 to 127
short2-32,768 to 32,767
int4-2,147,483,648 to 2,147,483,647
long8-9,223,372,036,854,775,808 to 9,223,372,036,854,755,807
float43.4e-038 to 3.4e+038
double81.7e-308 to 1.7e+038
char2u0000 (0) to uffff
boolean1true and false

๐Ÿ”‘ Why size matters

  • The size determines which conversions are "safe" (widening) versus "risky" (narrowing).
  • Smaller types can always fit into larger types without data loss.
  • Larger types may not fit into smaller types, potentially losing information.

โฌ†๏ธ Widening (upcasting)

๐Ÿ”„ What widening does

Widening: when a smaller primitive type value is automatically accommodated in a larger/wider primitive data type.

  • Also known as upcasting.
  • The conversion happens implicitlyโ€”no special syntax required.
  • Java performs this conversion automatically because there is no risk of data loss.

๐Ÿ› ๏ธ How widening works

The excerpt shows a byte value being widened to multiple larger types:

  • A byte value (10) can be assigned directly to short, int, long, float, or double variables.
  • No casting syntax is needed; Java handles the conversion.
  • The value remains the same across all conversions (10 stays 10, or 10.0 for floating-point types).

Example from the excerpt: a byte variable with value 10 is assigned to short, int, long, float, and double variables, and all display the correct value (10 or 10.0).

โœ… When widening occurs

According to the excerpt, widening takes place in two situations:

  1. When a smaller primitive type value is automatically accommodated in a larger/wider primitive data type.
  2. When a reference variable of a subclass is automatically accommodated in a reference variable of its superclass (inheritance context).

โฌ‡๏ธ Narrowing (downcasting)

๐Ÿ”„ What narrowing does

Narrowing: when a larger primitive value is accommodated in a smaller primitive data type using explicit conversion.

  • Also known as downcasting or downgrading.
  • Requires explicit casting with parentheses syntax: (targetType)value.
  • Java does not perform this automatically because data loss or precision loss may occur.

๐Ÿ› ๏ธ How narrowing works

The excerpt demonstrates narrowing a double value (10.5) to smaller types:

  • Syntax: byte b = (byte)d; where d is a double.
  • The cast operator (byte) explicitly tells Java to perform the conversion.
  • Precision loss: the decimal part is truncatedโ€”10.5 becomes 10 for byte, short, int, and long.
  • Float retains the decimal: 10.5 stays 10.5 because float can represent decimals.

โš ๏ธ When narrowing occurs

The excerpt lists two situations:

  1. Narrowing a wider/bigger primitive type value to a smaller primitive value.
  2. Narrowing a superclass reference to a subclass reference during inheritance.

๐Ÿšจ Don't confuse: precision vs. size

  • Narrowing from double to int loses the decimal part (10.5 โ†’ 10).
  • Narrowing from double to float keeps decimals (10.5 โ†’ 10.5) because float is still a floating-point type, even though it's smaller than double.
  • The key risk is data loss, not just size reduction.

๐Ÿ”€ Comparing widening and narrowing

AspectWideningNarrowing
DirectionSmaller โ†’ LargerLarger โ†’ Smaller
Also calledUpcastingDowncasting / Downgrading
SyntaxAutomatic, no cast neededExplicit cast required: (type)
Data safetyNo data lossMay lose precision or data
Examplebyte b=10; int i=b;double d=10.5; int i=(int)d;
11

Type Conversion and Exercise Questions

1.11 Exercise

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java supports two directions of type conversionโ€”widening (automatic conversion from smaller to larger types) and narrowing (explicit conversion from larger to smaller types)โ€”and understanding these conversions is essential for manipulating primitive data types correctly.

๐Ÿ“Œ Key points (3โ€“5)

  • Widening (upcasting): automatically converts a smaller primitive type to a larger one without data loss; no explicit cast needed.
  • Narrowing (downcasting): converts a larger primitive type to a smaller one; requires explicit casting and may lose precision or data.
  • Common confusion: widening is implicit and safe, while narrowing must be explicit because it can lose information (e.g., decimal parts are dropped).
  • Primitive type sizes: Java primitive types have fixed sizes (byte < short < int < long for integers; float < double for decimals), which determine conversion direction.
  • Exercise section: provides practice questions on variables, declarations, and basic Java programs.

๐Ÿ“ Primitive type sizes and ranges

๐Ÿ“ Size hierarchy

The excerpt provides a table showing eight primitive types with their sizes and ranges:

Primitive TypeSize (bytes)Range
byte1-128 to 127
short2-32,768 to 32,767
int4-2,147,483,648 to 2,147,483,647
long8-9,223,372,036,854,775,808 to 9,223,372,036,854,755,807
float43.4e-038 to 3.4e+038
double81.7e-308 to 1.7e+038
char2u0000 (0) to uffff
boolean1true and false

๐Ÿ“ Why size matters

  • Not all primitive types are the same in size and range.
  • The size difference determines which conversions are widening (safe) and which are narrowing (require caution).
  • Larger types can hold all values of smaller types, but the reverse is not true.

โฌ†๏ธ Widening conversion

โฌ†๏ธ What widening means

Widening (also known as upcasting): the conversion that implicitly takes place when a smaller primitive type value is automatically accommodated in a larger/wider primitive data type.

  • Widening happens automaticallyโ€”no explicit cast syntax is needed.
  • The excerpt also mentions widening applies to reference variables (subclass to superclass), but focuses on primitive types here.

โฌ†๏ธ How widening works

  • A smaller type value is assigned to a larger type variable.
  • Java performs the conversion automatically because no data is lost.
  • Example from the excerpt: a byte value (10) is widened to short, int, long, float, and double.

Example scenario:

byte b = 10;
short s = b;   // widening byte to short
int i = b;     // widening byte to int
long l = b;    // widening byte to long
float f = b;   // widening byte to float
double d = b;  // widening byte to double

All outputs preserve the value 10 (or 10.0 for floating-point types).

โฌ†๏ธ Why widening is safe

  • The target type is larger, so it can hold all possible values of the source type.
  • No precision or range is lost.
  • Don't confuse: widening does not require parentheses or explicit casting.

โฌ‡๏ธ Narrowing conversion

โฌ‡๏ธ What narrowing means

Narrowing (also known as downcasting or downgrading): an explicit conversion performed when a larger primitive type value is accommodated in a smaller primitive data type.

  • Narrowing requires an explicit cast because data may be lost.
  • The excerpt also mentions narrowing applies to reference variables (superclass to subclass), but focuses on primitive types here.

โฌ‡๏ธ How narrowing works

  • A larger type value is assigned to a smaller type variable.
  • The programmer must use explicit cast syntax: (targetType) value.
  • Example from the excerpt: a double value (10.5) is narrowed to byte, short, int, long, and float.

Example scenario:

double d = 10.5;
byte b = (byte) d;     // narrowing double to byte โ†’ 10
short s = (short) d;   // narrowing double to short โ†’ 10
int i = (int) d;       // narrowing double to int โ†’ 10
long l = (long) d;     // narrowing double to long โ†’ 10
float f = (float) d;   // narrowing double to float โ†’ 10.5

โฌ‡๏ธ Data loss in narrowing

  • Integer types (byte, short, int, long) drop the decimal part: 10.5 becomes 10.
  • Float retains the decimal: 10.5 stays 10.5.
  • The excerpt shows that narrowing from double to byte, short, int, and long all output 10, while narrowing to float outputs 10.5.
  • Don't confuse: narrowing is not automatic; forgetting the explicit cast will cause a compilation error.

โฌ‡๏ธ When to use narrowing

  • Use narrowing when you are certain the value fits within the smaller type's range.
  • Be aware that out-of-range values may wrap around or lose precision.
  • The excerpt does not detail overflow behavior, but emphasizes that narrowing is explicit.

๐Ÿ“ Exercise questions

๐Ÿ“ Conceptual questions

The excerpt lists ten exercise questions covering:

  1. What is computer programming and source code in Java?
  2. Identifying correct variable declaration syntax.
  3. Declaring and using double variables to display their sum.
  4. How to declare a string type variable.
  5. Different types of variables in Java based on their locations.
  6. Examples of valid and invalid variable declarations.
  7. When to declare a constant variable.

๐Ÿ“ Programming tasks

The excerpt includes three programming exercises:

  • Exercise 8: Write a program that multiplies two double variables and displays the result.
  • Exercise 9: Display "Hello Class!!" using only character variables (one character per variable, e.g., char c1 = 'H';).
  • Exercise 10: Display "Hello Class!!" using character variables with ASCII values instead of characters (e.g., char c1 = 72;).

๐Ÿ“ Purpose of exercises

  • Reinforce understanding of variable declarations, types, and basic operations.
  • Practice explicit character handling and ASCII values.
  • The excerpt does not provide answers, only the questions for self-study.
12

What is a Control Statement?

2.1 What is a Control Statement?

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Control statements allow a program to choose different execution paths at runtime based on the outcome of a condition, rather than executing all code sequentially.

๐Ÿ“Œ Key points (3โ€“5)

  • What a control statement does: evaluates one or more conditions and executes different code blocks depending on whether the condition is true or false.
  • Core mechanism: the condition returns a boolean value (TRUE or FALSE); if true, block-1 executes; if false, block-2 executes.
  • Why it matters: without control statements, code would only run sequentially in the order it appears; control statements let the program decide which path to take during runtime.
  • Common confusion: the decision is made during runtime based on the condition's result, not beforehandโ€”the program "checks" and then "chooses."
  • Two main types in Java: if-else statements and switch-case statements.

๐Ÿงฉ What a control statement is

๐Ÿงฉ Definition and purpose

A control statement is a construct in a computer program where the program needs to decide based on a condition (or a logical test); once the decision is made, the program executes single or multiple action(s) based on that decision.

  • The decision is based on the outcome of a logical test.
  • The outcome is always a boolean value: TRUE or FALSE.
  • Without control statements, code would execute sequentially (line by line in order).
  • Control statements let you control the program/code execution flow based on conditions known during runtime.

๐Ÿ”€ General structure

The excerpt describes a typical control statement structure:

ComponentRole
ConditionAn expression evaluated as true or false
Block-1Code executed if the condition is true
Block-2Code executed if the condition is false
Code outsideCode that runs regardless of the condition outcome
  • The condition is evaluated first.
  • Depending on the result, either block-1 or block-2 executes (not both).
  • After the chosen block finishes, any code outside the condition continues normally.

๐Ÿ  Real-life example: John's morning decision

๐Ÿ  Scenario walkthrough

The excerpt uses a concrete example to illustrate the concept:

Setup: John wakes up at 7:00 AM, has breakfast, and wants to buy groceries. He does not like rain, so he checks the weather first.

Decision logic:

  • Condition: Is it raining today?
  • If true (raining): Clean the house instead (block-1).
  • If false (not raining): Go to the grocery store (block-2).
  • After either action: Have lunch (code outside the condition).

๐Ÿ” Mapping to control statement parts

The excerpt explicitly maps the scenario to the control statement structure:

  • Start = Wake up and have breakfast
  • Condition = Whether it will rain today
  • Block-1 = Clean house
  • Block-2 = Go to the grocery store
  • Code block outside the condition = Have lunch

Key insight: John's decision is made at the moment he checks the weather, not in advance. Similarly, a program evaluates the condition during runtime and then chooses which block to execute.

Don't confuse: The condition itself is a question ("Is it raining?"), not an action. The blocks (clean house / buy groceries) are the actions that follow the decision.

๐Ÿ”ง How control statements work

๐Ÿ”ง The decision process

In a decision structure, the following happens:

  1. A condition is evaluated: The program checks a logical test.
    • Example: John considers whether it is a good day to go grocery shopping by checking the weather.
  2. An operation (or multiple operations) is performed among a set of choices: Based on the condition's result, one path is chosen.
    • Example: John can go grocery shopping or clean the house; he will do the latter only if it rains.

โš™๏ธ Runtime evaluation

  • The condition's result is determined during runtime, not when the code is written.
  • This allows the program to adapt to different situations dynamically.
  • Example: John does not know in advance whether it will rain; he checks the weather at that moment and then decides.

๐Ÿ”„ Sequential vs conditional execution

Execution typeHow it works
SequentialCode runs line by line in the order it appears
ConditionalCode execution path changes based on a condition's result
  • Without control statements, you might think all statements execute sequentially.
  • Control statements break this pattern by allowing the program to "skip" or "choose" blocks of code.

๐Ÿงท Types of control statements in Java

๐Ÿงท Two main types

The excerpt mentions two types of control statements supported by Java:

  1. if-else statements
  2. switch-case statements

(The excerpt does not elaborate on switch-case in this section; it focuses on if-else.)

๐Ÿงท The if-else statement structure

The excerpt introduces the primary form of the if statement:

if (Condition)
    Statement-1;
else
    Statement-2;

How it works:

  • Condition: An expression that returns a boolean value (true or false).
  • If the condition is true: Statement-1 executes.
  • If the condition is false: Statement-2 executes.

๐Ÿ  John's example in if-else syntax

The excerpt rewrites John's scenario using if-else syntax:

boolean isItRaining;
// Activity outside the condition
Wake up and have breakfast

if (isItRaining == TRUE)  // Block-1
    Clean the house.
else  // Block-2
    Go grocery shopping

// Activity outside the condition
Have lunch

Breakdown:

  • isItRaining is a boolean variable (holds TRUE or FALSE).
  • The condition isItRaining == TRUE checks whether it is raining.
  • If true, "Clean the house" executes.
  • If false, "Go grocery shopping" executes.
  • "Wake up and have breakfast" and "Have lunch" happen regardless of the weather.

Example scenario: John wakes up, has breakfast, goes to the window, and pulls back the curtain to see if it is raining. At that moment, he evaluates the condition (checks the weather) and then decides which action to take.

Don't confuse: The == operator tests equality (asks "is this true?"); it does not assign a value. The condition is a question, not a command.

13

If-Else Statement

2.2 If-Else Statement

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

The if-else statement routes program execution along different paths by evaluating boolean conditions at runtime, enabling decisions based on logical tests rather than sequential execution.

๐Ÿ“Œ Key points (3โ€“5)

  • What if-else does: evaluates a condition (returning TRUE or FALSE) and executes one block of code or another based on the result.
  • Multiple operations: curly braces {} allow multiple statements to execute within a single if or else block.
  • Else is optional: an if statement can stand alone without an else clause when no alternative action is needed.
  • Common confusion: assignment operator = vs. equality operator ==โ€”using = inside a condition assigns a value instead of testing equality.
  • Combining conditions: relational operators (e.g., <, ==) and logical operators (e.g., &&, ||) allow testing multiple boolean expressions simultaneously.

๐Ÿ”€ Basic if-else structure

๐Ÿ”€ How the statement works

If-else statement: a control structure that evaluates a condition (boolean expression) and executes statement-1 if the condition is TRUE, otherwise executes statement-2.

Basic syntax:

if (Condition)
  Statement-1;
else
  Statement-2;
  • The condition must return a boolean value (TRUE or FALSE).
  • Program flow is determined at run time, not by the order statements appear in the code.
  • Example: John checks if it is raining; if TRUE, he cleans the house; if FALSE, he goes grocery shopping.

๐Ÿงช Simple examples

Example (even/odd check):

  • A variable var = 47 is tested with var % 2 == 0 (modulus operator checks divisibility by 2).
  • If even: divide by 2.
  • If odd: compute 3 * var + 1.
  • Since 47 is odd, the result is 3 * 47 + 1 = 142.

Don't confuse: The modulus operator % returns the remainder of division, not the quotient.

๐Ÿงฑ Multiple operations and optional else

๐Ÿงฑ Executing multiple statements

  • When more than one operation is needed inside an if or else block, enclose them in curly braces {}.
  • Without braces, only the immediately following statement is controlled by the if/else.

Example (John's extended schedule):

  • If it rains: clean the house and call mom (two operations).
  • If it does not rain: go grocery shopping and meet a friend.
  • Both blocks require curly braces to group the operations.

๐Ÿšซ If without else

  • The else clause is not mandatory.
  • Use a standalone if when no alternative action is required.

Example (drinking water):

  • John reads until noon and has lunch.
  • If he is thirsty, he drinks water; otherwise, he does nothing extra.
  • Code:
    if (isThirsty == TRUE) {
      Drink water.
    }
    Have lunch
    
  • "Have lunch" executes regardless of the condition.

Example (negative to positive):

  • If var = -47 is negative, multiply by -1 to make it positive.
  • No else clause is needed; the updated value is printed afterward.

๐Ÿ”— Combining conditions with operators

๐Ÿ”— Relational operators

Relational operator: evaluates whether a specific relationship between two values is true or false.

OperatorMeaning
>Greater than
>=Greater than or equal to
<Less than
<=Less than or equal to
==Equal to
!=Not equal to
  • Example: var < 0 checks if var is negative.
  • Don't confuse == (equality test) with = (assignment)โ€”using = in a condition will assign a value instead of comparing.

๐Ÿ”— Logical operators

Logical operator: returns a boolean result based on one, two, or more boolean expressions; expressions using them are called "compound expressions."

OperatorMeaningReturns TRUE when
&&Logical ANDAll statements are true
``
!Logical NOTReverses the result

Truth table:

ABA && BA || B!A!B
TRUETRUETRUETRUEFALSEFALSE
TRUEFALSEFALSETRUEFALSETRUE
FALSETRUEFALSETRUETRUEFALSE
FALSEFALSEFALSEFALSETRUETRUE

Example (weather check):

  • if (isItRaining == TRUE OR outsideTemp < 55) โ†’ clean the house.
  • The overall expression is TRUE if either it is raining or the temperature is below 55ยฐF (or both).

Example (office hours):

  • Office is open if: (timeInHour < 17) && (timeInHour > 8) && (currentDay <= 6) && (currentDay > 1).
  • All four conditions must be TRUE (weekday and within working hours).

๐Ÿช† Nested if-else statements

๐Ÿช† What nesting means

  • An if statement can be placed inside another if statement.
  • Useful when a second condition only needs to be checked if the first is true.

Example (office hours revisited):

  • First, check if it is a weekday (currentDay <= 6 && currentDay > 1).
  • If TRUE, then check if the time is within office hours (timeInHour < 17 && timeInHour > 8).
  • If the first condition is FALSE (weekend), skip the time check and print "Office is Closed."

Structure:

if (outer condition) {
  if (inner condition)
    // action if both true
  else
    // action if outer true, inner false
}
else {
  // action if outer false
}

๐Ÿช† Membership level example

  • Membership duration determines status:
    • < 2 years โ†’ Basic
    • >= 2 and < 5 โ†’ Silver
    • >= 5 and < 10 โ†’ Gold
    • >= 10 โ†’ Platinum
  • Nested if-else checks each threshold in sequence.

Don't confuse: Nested if-else can become hard to read; the if-else-if ladder (below) is often simpler.

๐Ÿชœ If-else-if ladder

๐Ÿชœ Structure and flow

  • A series of else if blocks test multiple conditions in sequence.
  • The first TRUE condition executes its block; all remaining blocks are skipped.
  • An optional final else executes if none of the conditions are TRUE.

General format:

if (expression 1) {
  // statements
}
else if (expression 2) {
  // statements
}
else if (expression 3) {
  // statements
}
else {
  // default statements
}

Key rule: Boolean expressions must be unique (non-overlapping).

๐Ÿชœ Membership level with if-else-if

  • Same problem as nested example, but clearer:
    • if (mem_Duration < 2) โ†’ Basic
    • else if (mem_Duration >= 2 && mem_Duration < 5) โ†’ Silver
    • else if (mem_Duration >= 5 && mem_Duration < 10) โ†’ Gold
    • else โ†’ Platinum
  • Once one condition is TRUE, the rest are ignored.

Why it's simpler: Each condition is at the same indentation level, making the logic easier to follow than deeply nested blocks.

๐Ÿชœ Common pitfall: = vs. ==

Example (equality test gone wrong):

  • Code intends to check if firstVar equals secVar.
  • Using if (firstVar = secVar) assigns secVar to firstVar instead of comparing them.
  • This will not produce the intended logic and may cause a compilation error or unexpected behavior.

Remember: = assigns, == compares.

๐Ÿ”€ Switch-case statement (introduction)

๐Ÿ”€ When to use switch-case

  • Like an if-else ladder, but tests one variable against multiple specific values.
  • Clearer than a long if-else-if chain when checking equality against many constants.

Example (month number to name):

  • If-else version:
    if (month == 1)
      print "January";
    else if (month == 2)
      print "February";
    ...
    
  • Switch-case version:
    switch (month) {
      case 1:
        print "January";
        break;
      case 2:
        print "February";
        break;
      ...
    }
    

๐Ÿ”€ Key components of switch-case

  • switch (expression): the variable or expression to test.
  • case value:: each possible value to compare against.
  • Block of code under each case.
  • break;: exits the switch block (typically after each case).
  • Curly braces enclose the entire switch block.

Program flow:

  1. Evaluate the switch expression.
  2. Compare the result to each case value.
  3. When a match is found, execute that case's code block.
  4. The break statement prevents "fall-through" to subsequent cases.

Note: The excerpt ends mid-explanation of switch-case flow; full details on default and fall-through behavior are not provided.

14

Switch-Case Statement

2.3 Switch-Case Statement

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

The switch-case statement provides a cleaner way than if-else ladders to execute one code block from multiple options when testing a single variable against several specific values, though it cannot handle relational comparisons and requires careful use of break statements.

๐Ÿ“Œ Key points (3โ€“5)

  • What switch-case does: executes one statement from multiple options by testing a variable's value against various specific values.
  • How it differs from if-else: more aesthetic when many conditions are joined by logical OR, but cannot express relational operators (<, >, โ‰ค, โ‰ฅ, =).
  • Essential components: switch keyword with expression, case labels with values, code blocks, break statements, and optional default for invalid input.
  • Common confusion: forgetting the break statement causes "fall-through"โ€”the program continues executing subsequent cases even after a match.
  • When to use: best for checking one variable against multiple discrete values; if-else is better for ranges or complex conditions.

๐Ÿ”„ How switch-case works

๐Ÿ”„ Basic structure

The switch-case statement requires several components in order:

  • switch keyword followed by an expression (usually a variable) in parentheses
  • Opening curly brace
  • case keyword with specific values to compare against
  • Code blocks to execute for each case
  • break statement (typically after each case)
  • Closing curly brace

Example: A program that takes a month as an integer (January = 1, February = 2, โ€ฆ December = 12) and prints the month name.

switch (month) {
  case 1:
    System.out.println("January");
    break;
  case 2:
    System.out.println("February");
    break;
  ...
  case 12:
    System.out.println("December");
    break;
}

โš™๏ธ Program flow

  1. The program evaluates the switch expression first
  2. The expression's value is compared with each case value
  3. When a matching case is found, control flow enters that case's code block
  4. The break statement jumps control past the remaining cases (they are ignored)
  5. If no case matches, the program continues past the switch (or executes default if present)

๐ŸŽฏ Handling multiple scenarios

๐ŸŽฏ The default keyword

The default keyword handles scenarios where none of the cases match, similar to the else block in if/else constructs.

  • If the user provides input that doesn't match any case, the default block executes
  • Example: For a month program, any input other than 1โ€“12 (such as text, symbols, or invalid numbers) triggers the default case
switch (month) {
  case 1:
    System.out.println("January");
    break;
  ...
  case 12:
    System.out.println("December");
    break;
  default:
    System.out.println("Invalid Month");
    break;
}

๐Ÿ”— Multiple cases for one action

You can stack multiple case labels without break statements to execute the same code for different values.

Example: Checking if a month is summer (May, June, or July represented as 5, 6, 7):

switch (month) {
  case 5:
  case 6:
  case 7:
    System.out.println("Summer");
    break;
}
  • All three cases (5, 6, 7) execute the same "Summer" output
  • Only one break is needed at the end of the group

โš ๏ธ The critical role of break

โš ๏ธ What happens without break

The break statement is essential because without it, execution "falls through" to subsequent cases even after finding a match.

Example: If the user enters 1 (January) in code without break statements:

  • It prints "January"
  • Then continues to print "February"
  • Then prints "March"
  • Then prints "Invalid Month"

This is almost never the intended behavior.

โš ๏ธ Don't confuse: intentional vs accidental fall-through

  • Intentional fall-through: stacking cases (like the summer example) to share code
  • Accidental fall-through: forgetting break statements, leading to unexpected output
  • The excerpt warns that "missing the break statement may lead to unexpected outcomes" and makes code "error-prone"

๐Ÿ“Š Comparing switch-case to if-else

๐Ÿ“Š Advantages of switch-case

AspectSwitch-caseIf-else equivalent
Multiple OR conditionsMore aesthetic and readableLong, repetitive condition chains
Code clarityCleaner when testing one variable against many valuesVerbose with repeated variable comparisons

Example comparison for checking if a number equals 1, 4, 7, 10, 15, or 21:

Switch-case version (cleaner):

switch (number) {
  case 1:
  case 4:
  case 7:
  case 10:
  case 15:
  case 21:
    System.out.println("Do Something");
}

If-else version (more verbose):

if (number == 1 || number == 4 || number == 7 || number == 10 || 
    number == 15 || number == 21) {
  System.out.println("Do Something");
}

๐Ÿ“Š Limitations of switch-case

  • Cannot express relational operators: cannot use <, >, โ‰ค, โ‰ฅ, = comparisons
  • Only tests equality: can only check if a variable equals specific discrete values
  • Syntax complexity: the required structure (case labels, break statements) makes it error-prone
  • When if-else is better: for range checks, complex conditions, or relational comparisons

Don't confuse: switch-case is for testing one variable against multiple specific values; if-else is more flexible for ranges and complex logical conditions.

15

Loops

2.4 Loops

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Loops allow a set of statements to execute repeatedly until a specified condition is met, eliminating the need to write the same code many times manually.

๐Ÿ“Œ Key points (3โ€“5)

  • Why loops exist: they handle repetitive tasks that would otherwise require writing many identical statements, making code feasible and less time-consuming.
  • Three loop types in Java: while loop, for loop, and do-while loopโ€”all execute statements repeatedly until a condition becomes false, differing mainly in syntax.
  • Four elements of a loop: initialize a control variable, check a boolean condition, update the control variable, and execute the loop body.
  • Common confusion: pretest loops (while, for) check the condition before entering the body, so they may never execute; posttest loops (do-while) check after, so they always execute at least once.
  • Nested loops: a loop inside another loop; the inner loop completes all its iterations for each single iteration of the outer loop.

๐Ÿ”„ Why loops matter

๐Ÿ”„ The repetition problem

  • The excerpt uses a homework punishment example: writing "I will complete my homework on time" 100 times.
  • A single print statement can output the sentence once, but printing it 100 times with separate statements is not useful or feasible.
  • Loops solve this by allowing one set of statements to run many times without duplication.

๐ŸŽฏ What loops provide

Loops allow a set of statements, instructions, or code blocks to execute repeatedly until a particular condition is met.

  • They handle complex execution that would otherwise be very complicated and time-consuming.
  • A variable in the loop governs the loop execution.

๐Ÿงฉ The four elements of every loop

๐Ÿงฉ Initialize a control variable

  • Performed before entering the loop.
  • You set the control variable to an initial value.
  • This initialization executes only once at the beginning.

๐Ÿงฉ Boolean condition (or conditions)

  • The boolean condition (typically involving the control variable) decides whether the control enters the loop body.
  • If the condition is true, the loop body executes.
  • If it is false, the loop terminatesโ€”this is the exit condition.

๐Ÿงฉ Update the control variable

  • Often an increment or decrement statement.
  • Updates the control variable after the loop body executes.
  • Typically moves the control variable closer to making the boolean condition false.

๐Ÿงฉ Loop body

  • Contains one or more statements.
  • These statements execute repeatedly as long as the boolean expression is true.

๐Ÿ” How the loop works (step-by-step)

  1. Initialize a control variable.
  2. Evaluate the boolean expression using
16

2.5 Exercise

2.5 Exercise

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

This exercise set reinforces programming fundamentals by requiring students to apply logical operators, conditionals, loops, and string manipulation to solve a variety of practical problems.

๐Ÿ“Œ Key points (3โ€“5)

  • Logical operators and conditionals: evaluate boolean expressions and implement decision-making logic (if-else structures).
  • Loops and iteration: use while, for, and do-while loops to repeat operations, including infinite loops and nested loops.
  • String and numeric manipulation: process characters, reverse digits, calculate sums/products, and detect patterns like palindromes.
  • Mathematical algorithms: implement GCD, LCM, Fibonacci series, and quadratic equation solvers.
  • Common confusion: distinguishing between different loop types and knowing when to use nested structures vs. sequential logic.

๐Ÿงฎ Logical expressions and conditionals

๐Ÿงฎ Boolean expression evaluation

  • Problem 1 asks you to determine TRUE or FALSE for four expressions given x = 10, y = 8, z = 18.
  • You must evaluate logical operators: || (OR), && (AND), ! (NOT), and comparison operators (>=, <=, ==, !=).
  • Example: (x >= y) || (y <= 10) evaluates each side, then applies OR logic.

๐Ÿ” Input validation and classification

  • Problem 2: check if a rectangle (given length and width) is a square.
  • Problem 3: classify a character as lowercase letter, uppercase letter, or non-letter.
  • Problem 5: determine divisibility by 4, 6, and 10โ€”mention all that apply or none.
  • Problem 8: validate a date string and integer day, then output the season (Spring, Summer, Autumn, Winter) in the northern hemisphere.
  • Don't confuse: validation (is the input legal?) vs. classification (which category does it belong to?).

๐Ÿงฉ Multi-value comparisons

  • Problem 4: take three salaries, find the highest, lowest, and average; if all are equal, print a special message.
  • You must compare multiple values and handle the edge case where all inputs are identical.

๐Ÿ” Loops and iteration

๐Ÿ” Infinite loops

  • Problem 11: write an infinite loop using while, for, and do-while.
  • Each loop type can run forever if the termination condition is never met.
  • Example: while (true) { ... } or for (;;) { ... }.

๐Ÿ”ข Digit and character processing

  • Problem 12: count the frequency of each character in a string.
  • Problem 13: sum and multiply all digits of an integer (e.g., input 5143 โ†’ sum 13, product 60).
  • Problem 14: reverse the digits of an integer (e.g., 51430 โ†’ 3415).
  • These require iterating over each digit or character and accumulating results.

๐Ÿ”„ Nested loops

  • The excerpt mentions a code snippet that uses nested for loops to print a pattern of asterisks (rows and columns).
  • The outer loop controls rows; the inner loop controls columns within each row.
  • Example: for numRows = 5, the pattern grows from 1 star in row 1 to 5 stars in row 5.

๐Ÿงฎ Mathematical algorithms

๐Ÿงฎ Quadratic equations

  • Problem 7: solve a xยฒ + b x + c = 0 given coefficients a, b, c.
  • You must find all roots using the quadratic formula (the excerpt does not provide the formula, but the problem requires implementing it).

๐Ÿ”ข GCD and LCM

  • Problem 16: compute the greatest common divisor (GCD) of two non-zero integers.

    The greatest common divisor (GCD) of two integers is the largest positive integer that divides both.

    • Example: GCD(8, 12) = 4.
  • Problem 17: compute the least common multiple (LCM) of two non-zero integers.

    The LCM of two numbers is the smallest number divisible by both.

    • Example: LCM(12, 8) = 24.
  • Problem 18: extend LCM to three integers.
  • Don't confuse: GCD finds the largest shared divisor; LCM finds the smallest shared multiple.

๐ŸŒ€ Fibonacci series

  • Problem 19: calculate the nth Fibonacci number.

    In the Fibonacci series, each number (after the first two) is the sum of the previous two; the series starts with 0 and 1.

    • Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
  • You must iterate or use recursion to build the sequence up to the nth term.

๐Ÿ”ค String and pattern recognition

๐Ÿ”ค Palindrome detection

  • Problem 15: determine if a sequence of characters reads the same forward and backward.

    A palindrome is a word, number, phrase, or sequence that reads the same backward as forward.

    • Examples: madam, racecar, 1110111.
  • You must compare characters from both ends moving inward, or reverse the string and check equality.

๐Ÿ”ค Character frequency

  • Problem 12: count how many times each character appears in a string.
  • You must iterate over the string and maintain a count for each distinct character.

๐Ÿงพ Real-world applications

๐Ÿงพ Attendance policy

  • Problem 6: calculate attendance percentage and determine if a student may sit for the final exam (threshold: 80%).
  • Input: number of classes held and number attended.
  • Output: percentage and eligibility message.

๐Ÿ’ก Electricity billing

  • Problem 9: calculate a bill based on tiered rates (0โ€“50 units, 51โ€“150, 151โ€“250, 251+) and add a surcharge ($7 if under 251 KWH, $12 otherwise).
  • You must apply conditional logic to select the correct rate tier and surcharge.

๐Ÿงฎ Simple calculator

  • Problem 10: implement a calculator that performs add, subtract, multiply, divide, modulus, and exponent operations.
  • Input format: number1 <operator> number2.
  • Any other format is invalid.
  • You must parse the input, validate the operator, and perform the corresponding operation.
17

What is String?

3.1 What is String?

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Strings in Java are sequences of characters represented by the String class, and they come with built-in methods that allow developers to manipulate, compare, and extract information from text data.

๐Ÿ“Œ Key points (3โ€“5)

  • What a string is: A sequence of characters implemented as an instance of the String class in Java.
  • How to work with strings: Java provides methods like length(), toUpperCase(), toLowerCase(), charAt(), substring(), and indexOf() to manipulate string data.
  • String comparison: Use equals() for exact matching or compareTo() for ordering; case-insensitive versions (equalsIgnoreCase(), compareToIgnoreCase()) are also available.
  • Common confusion: String comparison is case-sensitive by defaultโ€”"S" and "s" are different unless you use case-insensitive methods.
  • Method chaining: Multiple string methods can be called in a single statement, allowing compact and readable code.

๐Ÿ“ String fundamentals

๐Ÿ“ What a string represents

A string is a sequence of characters.

  • In Java, the String class represents character strings.
  • All string literals (text in quotes) are implemented as instances of the String class.
  • Note: The datatype starts with a capital "S" (String), not lowercase "s".

๐Ÿ”ค Declaration and initialization

  • Declare a string variable and assign a value directly:
    • String s1 = "Hello Class!!";
  • The variable holds the sequence of characters as its value.

โŒจ๏ธ Taking string input

  • Use the Scanner class from the java.util package to read user input.
  • Create a Scanner object and call nextLine() to read a full line of text from the keyboard.
  • Example workflow: import java.util.Scanner โ†’ create Scanner object โ†’ call input.nextLine() โ†’ assign to a String variable โ†’ display or process.

๐Ÿ› ๏ธ Core string methods

๐Ÿ“ length() method

Returns the length of a string as an int value.

  • Counts the number of Unicode characters in the string.
  • Example: "Hello Class!!" has length 13 (including spaces and punctuation).

๐Ÿ”  Case conversion methods

MethodWhat it doesExample inputExample output
toUpperCase()Converts all characters to uppercase"Hello""HELLO"
toLowerCase()Converts all characters to lowercase"Hello""hello"
  • These methods return a new string; they do not modify the original.

๐Ÿ” charAt(int index) method

Returns a single character at a specified position (index) in the string.

  • Syntax: public char charAt(int index)
  • Indexing starts at 0 (first character is at index 0).
  • Example: "Hello".charAt(4) returns 'o'; "Hello".charAt(0) returns 'H'.

โœ‚๏ธ substring() method

Extracts a portion of the string using start and optionally end indices.

  • Two forms:
    • substring(int start): from start index to the end of the string.
    • substring(int start, int end): from start index up to (but not including) end index.
  • Example: "Hello class!!".substring(6) returns "class!!".
  • Example: "Hello class!!".substring(0, 5) returns "Hello".

๐Ÿ”Ž indexOf(String str) method

Returns the position (as an integer) of the first occurrence of a specified substring.

  • Syntax: public int indexOf(String str)
  • Returns the index where the substring begins.
  • Example: "Hello class!!, hello class!!".indexOf("class") returns 6.
  • Example: "Hello class!!, hello class!!".indexOf("Hello") returns 0.

๐Ÿ”— String operations

โž• Concatenation with concat()

  • The concat() method joins two strings together.
  • Example: s1 = "Hello"; s2 = " Class!"; s1 = s1.concat(s2); results in s1 holding "Hello Class!".
  • The result is assigned back to a variable (concat does not modify the original string in place).

๐Ÿ”— Method chaining

  • Java allows calling multiple methods on the same object in a single statement.
  • Each method returns an object, which the next method is called on.
  • Example: person.setName("John").setAge(22).getChainingMethodCallExampleDetails();
  • This technique makes code more compact and readable.

โš–๏ธ Comparing strings

โœ… equals() and equalsIgnoreCase()

equals() checks if two strings have exactly the same characters in the same case.

  • Returns true if strings are identical, false otherwise.
  • Java is case-sensitive: "S" and "s" are not equal.
  • Example: "John".equals("John") โ†’ true; "John".equals("john") โ†’ false.

equalsIgnoreCase() ignores case differences when comparing.

  • Example: "John".equalsIgnoreCase("john") โ†’ true.
  • Don't confuse: Use equals() when case matters; use equalsIgnoreCase() when case should be ignored.

๐Ÿ”ข compareTo() and compareToIgnoreCase()

compareTo() compares two strings lexicographically (dictionary order).

  • Returns 0 if the strings are equal.
  • Returns a negative value if the calling string is "less than" the argument string.
  • Returns a positive value if the calling string is "greater than" the argument string.
  • Example: "John".compareTo("John") โ†’ 0; "John".compareTo("Mike") โ†’ -3; "Mike".compareTo("John") โ†’ 3.

compareToIgnoreCase() performs the same comparison but ignores case.

  • Example: "John".compareTo("john") โ†’ -32 (case difference matters).
  • Example: "John".compareToIgnoreCase("john") โ†’ 0 (case ignored).
MethodCase-sensitive?Return value
equals()Yestrue or false
equalsIgnoreCase()Notrue or false
compareTo()Yes0, positive, or negative int
compareToIgnoreCase()No0, positive, or negative int
18

How to Declare String

3.2 How to Declare String

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

String declaration in Java requires using the capital-letter "String" datatype to create variables that hold sequences of characters, and these variables can be initialized directly with values or populated from user input via the Scanner class.

๐Ÿ“Œ Key points (3โ€“5)

  • What a string is: a sequence of characters implemented as instances of the String class in Java.
  • Declaration syntax: use String (capital "S") followed by a variable name and assignment of a character sequence.
  • Common confusion: the datatype must be written as "String" with a capital "S", not lowercase "s".
  • User input method: the Scanner class from java.util package enables reading string input from the keyboard using nextLine().
  • Built-in methods available: Java provides methods like length(), toUpperCase(), toLowerCase(), charAt(), substring(), and indexOf() to manipulate strings.

๐Ÿ“ Basic string declaration

๐Ÿ“ What strings represent in Java

A string is a sequence of characters; in Java programming the String class represents character strings, and all string literals are implemented as instances of the String class.

  • Strings are not primitive types but objects of the String class.
  • Every text value enclosed in quotes becomes a String instance.

โœ๏ธ Declaration syntax

The excerpt shows the basic pattern:

String s1 = "Hello Class!!";

Key requirements:

  • Use String with a capital "S" (not lowercase).
  • Assign a value in double quotes.
  • The variable can then be printed or manipulated.

Example: A program declares s1 with value "Hello Class!!" and prints it, producing the output "Hello Class!!".

๐ŸŽน Reading string input from users

๐ŸŽน Using the Scanner class

The Scanner class (from java.util package) enables keyboard input:

  • Import the package: import java.util.Scanner;
  • Create a Scanner object: Scanner input = new Scanner(System.in);
  • Read a line: String inputString = input.nextLine();

๐Ÿ”„ How input flows

  1. Declare a Scanner object connected to System.in.
  2. Call nextLine() on the Scanner object to wait for user input.
  3. Assign the returned value to a String variable.
  4. The variable now holds whatever the user typed.

Example: The program reads a line from the keyboard, stores it in inputString, and prints it backโ€”if the user types "Hello Class!!", that text is displayed.

๐Ÿ› ๏ธ Common string methods overview

๐Ÿ› ๏ธ Six helpful methods listed

The excerpt introduces these methods without full details:

MethodPurpose (from excerpt)
length()Returns the length of a string as an int value; counts unicode characters
toUpperCase()Converts all characters to uppercase letters
toLowerCase()Converts all characters to lowercase letters
charAt(int index)Returns a character at a specific position/index
substring(int start, int end)(Mentioned but not detailed in this excerpt)
indexOf(String str)(Mentioned but not detailed in this excerpt)

๐Ÿ”ข The length() method

  • Syntax: s1.length()
  • Returns an int representing the count of characters.
  • Example: "Hello Class!!" has length 13 (includes spaces and punctuation).

๐Ÿ”  Case conversion methods

  • toUpperCase(): transforms all letters to capitals.
    • Example: "Hello" becomes "HELLO".
  • toLowerCase(): transforms all letters to lowercase.
    • Example: "Hello" becomes "hello".
  • Both methods return a new string; they do not modify the original variable.

๐ŸŽฏ The charAt() method

  • Syntax: public char charAt(int index)
  • Retrieves a single character at the specified index position.
  • Index counting starts at 0 (first character is index 0).
  • Example: For "Hello", charAt(4) returns 'o' (the 5th character), and charAt(0) returns 'H' (the 1st character).
  • Don't confuse: the index is zero-based, so the first character is at position 0, not 1.

โš ๏ธ Important distinctions

โš ๏ธ Capital "S" requirement

The excerpt explicitly notes:

  • The datatype must be written as String with a capital letter "S".
  • Using lowercase "s" will cause an error.
  • This is a common beginner mistake to avoid.

โš ๏ธ String as a class, not a primitive

  • Strings are objects (instances of the String class), not primitive types like int or char.
  • This means strings have methods (like length(), toUpperCase()) that can be called on them.
  • Example: s1.length() calls a method on the string object s1.
19

String Input

3.3 String Input

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

The Scanner class enables Java programs to read string input from the keyboard by creating a Scanner object and using its nextLine() method to capture user-entered text.

๐Ÿ“Œ Key points (3โ€“5)

  • What Scanner does: reads user input from the keyboard in Java programs.
  • How to use Scanner for strings: import java.util.Scanner, create a Scanner object, and call nextLine() to read a line of text.
  • Where Scanner lives: the Scanner class is part of the java.util package, which must be imported.
  • Common confusion: Scanner is an object that must be instantiated (created) before useโ€”you cannot call nextLine() without first creating a Scanner object.
  • Result handling: nextLine() returns a String that can be assigned to a string variable and then used or displayed.

๐Ÿ“ฆ The Scanner class

๐Ÿ“ฆ What Scanner is and where it comes from

The Scanner class is used in Java to take user input(s). The Scanner class is part of java.util package.

  • Scanner is not built into Java by default; you must import it.
  • The import statement import java.util.Scanner; makes the Scanner class available in your program.
  • Without this import, the compiler will not recognize the Scanner class.

๐Ÿ”ง Creating a Scanner object

  • Before reading input, you must create a Scanner object.
  • Syntax: Scanner input = new Scanner(System.in);
    • input is the name of the object (you can choose any valid variable name).
    • System.in tells the Scanner to read from the keyboard (standard input).
  • This object is then used to call methods that read different types of input.

โŒจ๏ธ Reading string input with nextLine()

โŒจ๏ธ How nextLine() works

  • The method nextLine() is called on the Scanner object to read a full line of text from the keyboard.
  • It waits for the user to type something and press Enter.
  • The entire line (everything the user typed before pressing Enter) is returned as a String.

๐Ÿ“ Assigning and using the input

  • The returned String can be assigned to a string variable: String inputString = input.nextLine();
  • Once assigned, the variable holds the user's input and can be printed, manipulated, or used in further operations.
  • Example: System.out.println(inputString); displays what the user typed.

๐Ÿงช Complete example walkthrough

๐Ÿงช Step-by-step breakdown of Example 2

The excerpt provides a complete example:

import java.util.Scanner;
public class KeyboardInput {
  public static void main (String[] args) {
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();
    System.out.println(inputString);
  }
}
StepWhat happensWhy
Importimport java.util.Scanner;Makes Scanner class available
Create objectScanner input = new Scanner(System.in);Prepares to read from keyboard
Read inputString inputString = input.nextLine();Waits for user to type and press Enter; stores result
DisplaySystem.out.println(inputString);Prints the user's input back to the screen

๐Ÿ–ฅ๏ธ Example output

  • The excerpt shows that when the user types Hello Class!! and presses Enter, the program outputs:
    Hello Class!!
    
  • This demonstrates that nextLine() captured the entire line exactly as typed.

โš ๏ธ Don't confuse with other input methods

  • The excerpt focuses on nextLine(), which reads an entire line of text.
  • Scanner has other methods (e.g., for reading integers or single words), but this section covers only string input via nextLine().
  • Remember: nextLine() reads until the user presses Enter, capturing all characters including spaces.
20

Helpful String Methods

3.4 Helpful String Methods

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java provides six essential String methodsโ€”length(), toUpperCase(), toLowerCase(), charAt(), substring(), and indexOf()โ€”that allow programmers to measure, transform, extract, and search within string variables.

๐Ÿ“Œ Key points (3โ€“5)

  • Six core methods: length() counts characters; toUpperCase()/toLowerCase() change case; charAt() retrieves a single character; substring() extracts portions; indexOf() finds positions.
  • Index-based access: charAt(), substring(), and indexOf() all use zero-based indexing (first character is at index 0).
  • Return types vary: length() and indexOf() return int values; toUpperCase(), toLowerCase(), and substring() return String values; charAt() returns a char.
  • Common confusion: charAt(4) retrieves the fifth character (not the fourth) because indexing starts at 0; substring(start, end) does not include the character at the end index.
  • Method chaining: Java allows calling multiple methods on the same object in a single statement by returning the object itself from each method.

๐Ÿ”ข Measuring and transforming strings

๐Ÿ“ length() method

The length() method returns the length of a string as an int value by counting the number of unicode characters.

  • It does not modify the string; it only reports how many characters exist.
  • Example: "Hello Class!!" has length 13 (includes spaces and punctuation).
  • The method counts all unicode characters, not just letters.

๐Ÿ”  toUpperCase() and toLowerCase() methods

  • toUpperCase() converts all characters in a string variable to uppercase letters.
  • toLowerCase() converts all characters to lowercase letters.
  • Neither method changes the original string variable; they return a new transformed string.
  • Example: "Hello" becomes "HELLO" with toUpperCase() and "hello" with toLowerCase().
MethodInputOutput
toUpperCase()"Hello""HELLO"
toLowerCase()"Hello""hello"

๐ŸŽฏ Accessing characters and substrings

๐Ÿ” charAt(int index) method

The charAt() method returns a character from a string variable using the position or index of the character.

  • Syntax: public char charAt(int index)
  • Returns a char (single character), not a String.
  • Uses zero-based indexing: the first character is at index 0.
  • Example: for String s1 = "Hello", s1.charAt(4) returns 'o' (the fifth character), and s1.charAt(0) returns 'H' (the first character).
  • Don't confuse: charAt(4) is the fifth character, not the fourth.

โœ‚๏ธ substring(int start, int end) method

The substring() method returns a string from a string variable using the beginning index or beginning and ending index.

  • Two forms:
    • public String substring(int start) โ€” from start index to the end of the string
    • public String substring(int start, int end) โ€” from start index up to (but not including) end index
  • Returns a String, not a char.
  • Example: for String s1 = "Hello class!!":
    • s1.substring(6) returns "class!!" (from index 6 to the end)
    • s1.substring(0, 5) returns "Hello" (from index 0 up to but not including index 5)
  • Don't confuse: the end index is exclusiveโ€”the character at that position is not included.

๐Ÿ”Ž Searching within strings

๐Ÿ—บ๏ธ indexOf(String str) method

The indexOf() method returns the position as an integer value of the first occurrence of specified character(s) in a string.

  • Syntax: public int indexOf(String str)
  • Returns an int representing the starting index of the first match.
  • If the substring appears multiple times, only the first occurrence's index is returned.
  • Example: for String s1 = "Hello class!!, hello class!!":
    • s1.indexOf("class") returns 6 (the first "class" starts at index 6)
    • s1.indexOf("Hello") returns 0 (starts at the very beginning)
  • The method is case-sensitive: "Hello" and "hello" are different.

๐Ÿ”— Method chaining

๐Ÿ”— Chaining multiple method calls

Method chaining is the chain of methods being called at the same time; a single object is used to call multiple methods in a single statement.

  • Each method in the chain returns the object itself (using return this;), allowing the next method to be called immediately.
  • Example pattern: person.setName("John").setAge(22).getChainingMethodCallExampleDetails();
  • This technique reduces the need for intermediate variables and makes code more concise.
  • Don't confuse: chaining requires that each method returns the object; methods that return void cannot be chained further.

๐Ÿ”ง String operations

โž• concat() method

The concat() method helps to concatenate (join) strings.

  • Combines two string variables into one.
  • Example: String s1 = "Hello"; String s2 = " Class!"; s1 = s1.concat(s2); results in s1 holding "Hello Class!!".
  • The original strings are not modified; concat() returns a new string that must be assigned to a variable.

โš–๏ธ Comparing strings with equals()

  • Java distinguishes between uppercase and lowercase letters: "S" and "s" are not equal.
  • equals() method compares the actual content of two string variables.
  • Returns a boolean: true if the strings are identical (including case), false otherwise.
  • Example: "S".equals("s") returns false; "John".equals("John") returns true.
  • Don't confuse: equals() checks content; using == on strings checks if they are the same object in memory, which is often not what you want.
ComparisonResultReason
"S".equals("s")falseDifferent case
"John".equals("John")trueIdentical content
21

Chaining Method Call

3.5 Chaining Method Call

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Method chaining in Java allows multiple methods to be called on the same object in a single statement by having each method return the object itself.

๐Ÿ“Œ Key points (3โ€“5)

  • What method chaining is: calling multiple methods on a single object in one statement, forming a "chain" of method calls.
  • How it works: each method in the chain returns this (the current object), enabling the next method to be called immediately.
  • Key mechanism: setter methods return the object (return this;) instead of returning nothing (void).
  • Common confusion: method chaining requires methods to return the object; regular void methods cannot be chained in the middle of a chain.
  • Practical benefit: cleaner, more concise code by avoiding repeated object references.

๐Ÿ”— What method chaining means

๐Ÿ”— Definition and basic concept

Method chaining: the chain of methods being called at the same time on a single object in a single statement.

  • Instead of calling methods on separate lines, you call them one after another using dot notation.
  • The excerpt emphasizes "at the same time" and "single statement," meaning all calls happen in one expression.
  • Example: person.setName("John").setAge(22).getChainingMethodCallExampleDetails(); chains three method calls together.

๐Ÿ”„ How it differs from regular method calls

  • Regular approach: call one method, then call another on a new line.
  • Chaining approach: call one method, immediately call the next on the returned object.
  • Don't confuse: this is not about calling different objects' methods; it's about calling multiple methods on the same object.

โš™๏ธ How method chaining works

โš™๏ธ The return this mechanism

The excerpt shows that each setter method returns the object itself:

public ChainingMethodCallExample setName(String name) {
    this.name = name;
    return this;
}
  • this refers to the current object.
  • By returning this, the method gives back the same object, allowing another method to be called on it immediately.
  • Without return this, the method would return nothing (void) and chaining would break.

๐Ÿ”ง Structure of chainable methods

From the example, chainable methods follow this pattern:

ComponentPurpose
Method parameterAccepts the value to set (e.g., String name)
AssignmentUpdates the object's internal state (this.name = name)
Return statementReturns this to enable chaining
Return typeMust be the class type, not void

๐ŸŽฏ Ending the chain

  • The excerpt shows that the final method getChainingMethodCallExampleDetails() does not need to return this because nothing follows it.
  • This final method performs an action (printing information) rather than setting a value.
  • Example: person.setName("John").setAge(22).getChainingMethodCallExampleDetails(); โ€” the chain ends with a void method that displays output.

๐Ÿ’ก Practical example breakdown

๐Ÿ’ก The complete chaining example

The excerpt provides a working example with these components:

  • Private member variables: name and age store the object's state.
  • Setter methods: setName() and setAge() both return this.
  • Display method: getChainingMethodCallExampleDetails() prints the stored information.
  • Chained call: person.setName("John").setAge(22).getChainingMethodCallExampleDetails();

๐Ÿ“ค Output and behavior

The example produces: Person name is John and 22 years old.

  • The chain sets the name to "John", then sets the age to 22, then displays the information.
  • All three operations happen in one statement without needing to reference person multiple times.
  • Don't confuse: the methods execute left-to-right in sequence, not simultaneously; "at the same time" means "in the same statement."

๐Ÿ” Why this pattern is useful

  • Conciseness: avoids repeating the object name on multiple lines.
  • Readability: groups related operations together visually.
  • Fluent interface: creates a more natural, sentence-like way to configure objects.
22

String Operations

3.6 String Operations

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java provides built-in methods to concatenate and compare strings, with comparison methods offering both case-sensitive and case-insensitive options to determine equality or ordering.

๐Ÿ“Œ Key points (3โ€“5)

  • Concatenation: the concat() method joins two strings together.
  • Case-sensitive comparison: equals() and compareTo() distinguish uppercase from lowercase letters.
  • Case-insensitive comparison: equalsIgnoreCase() and compareToIgnoreCase() ignore letter case when comparing strings.
  • Common confusion: equals() returns true/false, while compareTo() returns 0 for equal strings or a nonzero value (positive/negative) indicating which string is larger.
  • Why it matters: choosing the right comparison method depends on whether case sensitivity is required for the task.

๐Ÿ”— Concatenating strings

๐Ÿ”— The concat() method

The concat() method helps to concatenate strings.

  • What it does: joins two strings together into a single string.
  • How to use it: call concat() on the first string and pass the second string as an argument.
  • Example: if s1 = "Hello" and s2 = " Class!", then s1.concat(s2) produces "Hello Class!".
  • The resulting string can be assigned back to the original variable or stored in a new variable.

Example scenario:

String s1 = "Hello";
String s2 = " Class!";
s1 = s1.concat(s2);
// s1 now holds "Hello Class!"

๐Ÿ” Comparing strings with equals()

๐Ÿ” Case-sensitive equality with equals()

The equals() method compares two strings and returns true if they are identical, false otherwise.

  • Case sensitivity: uppercase and lowercase letters are treated as different characters.
  • Example: "S" and "s" are not equal; equals() returns false.
  • Example: "John" and "John" are equal; equals() returns true.
  • Example: "John" and "john" are not equal; equals() returns false.

Don't confuse:

  • equals() checks exact character-by-character match, including case.
  • If you need to ignore case, use equalsIgnoreCase() instead.

๐Ÿ”ค Case-insensitive equality with equalsIgnoreCase()

The equalsIgnoreCase() method compares two strings while ignoring differences in letter case.

  • When to use: when you want "John" and "john" to be considered equal.
  • Example: "John".equalsIgnoreCase("john") returns true.
  • Example: "John".equals("john") returns false, but "John".equalsIgnoreCase("john") returns true.

Comparison table:

Method"John" vs "John""John" vs "john"
equals()truefalse
equalsIgnoreCase()truetrue

๐Ÿ“Š Comparing strings with compareTo()

๐Ÿ“Š Case-sensitive ordering with compareTo()

The compareTo() method determines if two strings are equal and, if not, which one is larger.

  • Return values:
    • Returns 0 if the strings are equal.
    • Returns a nonzero value (positive or negative) if the strings are different.
    • A negative value means the first string is smaller than the second.
    • A positive value means the first string is larger than the second.

Example scenario:

String s1 = "John";
String s2 = "John";
String s3 = "Mike";
s1.compareTo(s2) โ†’ 0 (equal)
s1.compareTo(s3) โ†’ -3 (s1 is smaller)
s3.compareTo(s1) โ†’ 3 (s3 is larger)
  • Why nonzero values vary: the magnitude depends on the difference between the strings (e.g., alphabetical distance).

๐Ÿ”ค Case-insensitive ordering with compareToIgnoreCase()

The compareToIgnoreCase() method compares strings while ignoring case differences.

  • When to use: when you want to compare strings without caring about uppercase vs lowercase.
  • Example: "John".compareTo("john") returns -32 (case difference), but "John".compareToIgnoreCase("john") returns 0 (equal when ignoring case).

Comparison table:

Method"John" vs "john" result
compareTo()-32 (not equal, case matters)
compareToIgnoreCase()0 (equal, case ignored)

Don't confuse:

  • equals() / equalsIgnoreCase() return boolean (true/false).
  • compareTo() / compareToIgnoreCase() return integer (0 for equal, nonzero for different).

๐Ÿงฉ Choosing the right comparison method

๐Ÿงฉ When to use each method

NeedMethod to use
Check exact equality (case matters)equals()
Check equality ignoring caseequalsIgnoreCase()
Determine ordering (case matters)compareTo()
Determine ordering ignoring casecompareToIgnoreCase()
  • Key distinction: if you only need a yes/no answer about equality, use equals() or equalsIgnoreCase().
  • If you need to know which string comes first (e.g., for sorting), use compareTo() or compareToIgnoreCase().
23

3.7 Exercise

3.7 Exercise

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

This exercise section consolidates string manipulation and introduces methods in Java by providing practice problems on string operations and demonstrating how methods reduce code repetition and improve maintainability.

๐Ÿ“Œ Key points (3โ€“5)

  • String exercises cover: basic operations (concatenation, length, case conversion), comparison methods (equals, compareTo), and advanced tasks (character frequency, password validation, pattern replacement).
  • Methods solve repetition: the tax calculation example shows how extracting repeated logic into a method makes code shorter and easier to maintain.
  • Common confusion: equals() vs equalsIgnoreCase(), and compareTo() vs compareToIgnoreCase()โ€”the "IgnoreCase" variants treat uppercase and lowercase as equivalent.
  • Why methods matter: when logic needs to change (e.g., a friend moves to a different state), you update one method instead of multiple scattered lines.

๐Ÿ“ String exercise topics

๐Ÿ“ Basic string operations (Questions 1โ€“4)

  • What is a string: a sequence of characters in Java; declared with String type.
  • Character vs string: a character is a single letter (declared with char); a string is a sequence of characters (declared with String).
  • Concatenation: combining two strings into one.
  • Length calculation: counting characters in a string, optionally ignoring whitespace.

Example: the excerpt asks to find the length of "Hello Class" and "Hello, My name is John!" while ignoring spaces.

๐Ÿ” Comparison methods (Questions 5โ€“6)

The excerpt provides code demonstrating compareTo and compareToIgnoreCase:

String s1 = "John";
String s2 = "john";
s1.compareTo(s2);              // output: -32
s1.compareToIgnoreCase(s2);    // output: 0
MethodBehaviorExample output
equals()Checks exact match (case-sensitive)"John".equals("john") โ†’ false
equalsIgnoreCase()Checks match ignoring case"John".equalsIgnoreCase("john") โ†’ true
compareTo()Returns difference in ASCII values (case-sensitive)"John".compareTo("john") โ†’ -32
compareToIgnoreCase()Returns 0 if strings are equal ignoring case"John".compareToIgnoreCase("john") โ†’ 0

Don't confuse: compareTo returns a number (negative, zero, or positive) indicating order; equals returns true/false.

๐Ÿ”  Case conversion and search (Questions 7โ€“10)

  • Uppercase/lowercase conversion: transforming all letters in a string to upper or lower case.
  • Substring existence: checking if one string appears inside another and returning TRUE or the index position.

๐Ÿงฉ Advanced string manipulation (Questions 11โ€“15)

  • Character frequency: finding the most common character and its count (e.g., "AliBaba" โ†’ "A:3").
  • Case switching: converting lowercase to uppercase and vice versa without built-in methods.
  • Password validation: checking at least 9 characters, one lowercase, one uppercase, one number, and one non-alphanumeric characterโ€”without using String class methods.
  • Vowel/consonant replacement: replacing vowels with the next consonant and consonants with the next vowel in the alphabet (e.g., "Peninsula" โ†’ "Ufojouvob").
  • Date formatting: converting MM/DD/YYYY to DD First 3 letters of Month, YYYY (e.g., 08/24/2002 โ†’ 24 Aug, 2002) and validating input.

Key constraint: many exercises prohibit built-in String methods, requiring manual character-by-character processing.

๐Ÿ› ๏ธ Introduction to methods

๐Ÿ› ๏ธ What a method is

A method in Java is a collection of instructions or statements that are grouped together to perform a specific task and return the result to the caller.

  • Methods encapsulate logic so you can reuse it without rewriting the same code multiple times.
  • The excerpt describes a method as "a system or a way of doing something."

๐Ÿ” Why write a method: the tax calculation example

Problem without methods: calculating state income tax for four friends in different states requires repetitive code:

  • Four friends (John, Chris, Aby, Mary) move to Michigan, Colorado, Pennsylvania, and Utah with different tax rates (4.25%, 4.55%, 3.07%, 4.95%).
  • The original code repeats the calculation tax = salary * rate / 100.0 four times, then prints four similar lines.
  • If a friend moves to a different state or you add a fifth friend, you must adjust multiple lines and risk errors.

Solution with a method: extract the repeated logic into calc_Tax(name, salary, Rate):

static void calc_Tax(String name, int salary, double Rate){
  double tax = salary * Rate / 100.0;
  System.out.println(name + " pays $" + tax + " per year.");
}

Then call it four times:

calc_Tax(f1, salary_f1, rate_MI);
calc_Tax(f2, salary_f2, rate_CO);
calc_Tax(f3, salary_f3, rate_PA);
calc_Tax(f4, salary_f4, rate_UT);

Benefits:

  • Less repetition: the calculation and print logic appear only once.
  • Easier maintenance: if the tax formula changes, you update one method instead of four scattered lines.
  • Scalability: adding a fifth friend requires only one new method call, not rewriting the entire calculation.

Example: if Chris moves to a different state, you only change the argument in calc_Tax(f2, salary_f2, new_rate).

๐ŸŽฏ Method structure (from the example)

  • Method signature: static void calc_Tax(String name, int salary, double Rate)
    • static: can be called without creating an object.
    • void: does not return a value (it prints directly).
    • Parameters: name, salary, Rateโ€”the method receives these values when called.
  • Method body: performs the calculation and prints the result.
  • Calling the method: calc_Tax(f1, salary_f1, rate_MI); passes specific values to the parameters.

Don't confuse: the method definition (where you write the logic) vs the method call (where you use the method by passing arguments).

24

Why Write a Method

4.1 Why Write a Method

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Methods in Java enable code reusability, better organization, and easier debugging by grouping related statements into a named, reusable block that performs a specific task.

๐Ÿ“Œ Key points (3โ€“5)

  • What a method is: a collection of instructions grouped together to perform a specific task, also called a procedure or subroutine.
  • Why methods matter: they enable code reuse (define once, use many times), create structured/organized code, and make debugging and modification easier.
  • How methods simplify repetition: instead of writing similar code blocks multiple times, you call the same method with different inputs.
  • Common confusion: methods vs. repeated codeโ€”methods abstract the pattern so you don't recalculate or rewrite the same logic; you just call the method with new parameters.
  • Key property: methods can take zero, one, or multiple inputs and can return a value or return nothing (void).

๐Ÿ”„ The problem methods solve

๐Ÿ”„ Repetitive code without methods

The excerpt presents a tax calculation example for four friends moving to different states with different tax rates.

Without methods, the code:

  • Defines separate variables for each friend's tax: tax_f1, tax_f2, tax_f3, tax_f4.
  • Repeats the same calculation pattern four times: salary * rate / 100.0.
  • Requires rechecking and adjusting all calculations if someone moves to a different state.
  • Becomes harder to manage as the number of friends or scenarios grows.

Example scenario from the excerpt:

  • Four friends (John, Chris, Aby, Mary) move to Michigan, Colorado, Pennsylvania, and Utah.
  • Each state has a flat income tax rate (4.25%, 4.55%, 3.07%, 4.95%).
  • The program calculates and prints each friend's tax separately using nearly identical formulas.

โœจ The same code with a method

With a method (calc_Tax), the code:

  • Defines the calculation logic once inside the method body.
  • Calls the method four times with different parameters (name, salary, rate).
  • Easily adapts to changes: if a friend moves to a new state, just call the method with the new tax rateโ€”no need to rewrite the formula.

The excerpt describes the method as "a magic box" or "like a fruit juicer": you put in inputs (parameters) and it produces the output.

Don't confuse: calling a method vs. repeating codeโ€”calling a method reuses the same logic; repeating code duplicates the logic, making maintenance harder.

๐Ÿ”ข Another example: summing ranges

๐Ÿ”ข Summing numbers without methods

The excerpt shows a program that calculates:

  • Sum of numbers from 1 to 100
  • Sum of numbers from 1 to 1000
  • Sum of numbers from 100 to 5000

Without methods, the code:

  • Uses three separate for loops with three separate sum variables (sum_1, sum_2, sum_3).
  • Each loop does almost the same job: add all numbers within a range.
  • Results in repetitive, harder-to-manage code.

๐Ÿ”ข Summing numbers with a method

With a method (calc_Sum), the code:

  • Defines one for loop inside the method that takes a low and high boundary as parameters.
  • Calls the method three times: calc_Sum(1,100), calc_Sum(1,1000), calc_Sum(100,5000).
  • The excerpt concludes: "the code with the method is more manageable and organized."

๐ŸŽฏ Benefits of methods

๐ŸŽฏ Three key advantages

The excerpt lists three main benefits:

BenefitWhat it means
Code reusabilityDefine the logic once, use it several times without rewriting.
Structured and organized codeGroup related statements together; easier to read and understand.
Easy to debug and modifyChanges to the logic happen in one place, not scattered across the program.

๐ŸŽฏ Why reusability matters

  • If you need to add a fifth friend or a new sum range, you simply call the method again with new parameters.
  • If the calculation logic changes (e.g., tax formula adjustment), you modify the method body once, and all calls automatically use the updated logic.

Don't confuse: reusability vs. copying codeโ€”reusability means one definition used many times; copying means multiple definitions that must all be updated separately.

๐Ÿงฉ What a method is in Java

๐Ÿงฉ Definition and properties

A method in Java is a set of statements (or blocks of code) that performs a specific task; also known as a procedure or subroutine.

In Java, a method always belongs to a class and has these properties:

  • It can take zero, one, or multiple inputs (called arguments or parameters).
  • Depending on the return type, it can return an answer or return nothing (void methods).

๐Ÿงฉ Method structure

The excerpt describes the typical structure of a method:

modifier(s) returnType methodName(parameter list) {
  // method body
}

Components:

  • Modifier: optional label identifying specific properties of the method.
  • Return type: specifies if the method returns a value (value-returning method) or nothing (void method).
  • Method name: descriptive name following the same naming rules as variables (e.g., calculateAvg(), avgCalculation()).
  • Input parameter (or arguments): data passed to the method; can be zero, one, or multiple parameters separated by commas; must indicate type and number.
  • Method body: the statements that describe what the method will do.

๐Ÿงฉ Example skeleton from the excerpt

The excerpt provides this example:

public static int returnMax(int var1, int var2) {
  // Method body: return the greater value
  if (var1 >= var2)
    return var1;
  else
    return var2;
}
  • Modifier: public static
  • Return type: int (returns an integer value)
  • Method name: returnMax
  • Parameters: two integers, var1 and var2
  • Body: compares the two values and returns the greater one

Don't confuse: return type vs. parameter typeโ€”return type is what the method gives back; parameter type is what the method takes in.

25

Java Methods

4.2 Java Methods

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Methods in Java enable code reusability, organization, and maintainability by encapsulating blocks of statements that perform specific tasks and can be called multiple times with different inputs.

๐Ÿ“Œ Key points (3โ€“5)

  • Why methods matter: They provide code reuse (define once, use many times), structured organization, and easier debugging/modification.
  • Two main types: void methods (perform tasks without returning values) and value-returning methods (return a result to the caller).
  • Parameters and arguments: Methods can accept zero, one, or multiple inputs; the number and data type of arguments passed must match the parameter list.
  • Common confusionโ€”local scope: Variables declared inside a method are local to that method and invisible to code outside; different methods can have variables with the same name without conflict.
  • Method signature components: modifier(s), return type, method name, parameter list, and method body.

๐Ÿ—๏ธ What methods are and why they exist

๐Ÿ—๏ธ Definition and motivation

A method is a set of statements (or blocks of code) that performs a specific task; it is a reusable portion of a program, also known as a procedure or subroutine.

  • In Java, every method belongs to a class.
  • Example motivation: calculating the sum of numbers in different ranges (1 to 100, 1 to 1000, 100 to 5000) requires nearly identical loops; a method lets you write the logic once and call it with different inputs.
  • Analogy: a fruit juicer takes water and different fruits (inputs/parameters) and produces juice (output).

๐ŸŽฏ Three key benefits

  1. Code reusability: define once, use several times (e.g., call calc_Sum(1,100), calc_Sum(1,1000), calc_Sum(100,5000) without rewriting the loop).
  2. Structured and organized code: separates concerns and groups related logic.
  3. Easy to debug and modify: changes to the logic need to be made in only one place.

๐Ÿงฉ Anatomy of a method

๐Ÿงฉ Method signature and components

A typical method looks like:

modifier(s) returnType methodName(parameter list) {
  // method body
}
ComponentDescription
ModifierOptional label identifying properties (e.g., public, static)
Return TypeSpecifies if the method returns a value (e.g., int, double) or nothing (void)
Method NameDescriptive name following variable naming rules (e.g., calculateAvg(), avgCalculation())
Parameter ListZero, one, or multiple parameters (with type and name) inside (), separated by commas
Method BodyStatements describing what the method does

Example skeleton:

public static int returnMax(int var1, int var2) {
  if (var1 >= var2)
    return var1;
  else
    return var2;
}

๐Ÿ“ž Calling a method

  • The main() method starts automatically; other methods execute only when called.
  • Call syntax: methodName(arguments); (semicolon required; no modifiers or return type in the call).
  • When called, program control jumps to the method, executes the body, then returns to the call site.
  • Example: calc_Sum(1,100); calls the method with arguments 1 and 100.

Don't confuse: Method definition includes modifiers and return type; method call does not.

๐Ÿ“ฅ Passing arguments

  • Arguments (values) passed in a call are copied into the method's parameters.
  • Example: calc_Sum(1,100) copies 1 into low and 100 into high.
  • You can pass variables: printMyInfo(myAge, myWeight) copies the values of myAge and myWeight into age and weight.

Important rule: The number of arguments and their data types must match the parameter list.

๐Ÿ”€ Two types of methods

๐Ÿ”€ Void methods

A void method performs a task and terminates without returning anything to the caller.

  • Signature: public static void methodName(parameter list) { ... }
  • No return statement needed (or return; with no value).
  • Example: welcomeMsg() prints text; presenter(String name, String city) prints name and city.
  • Use case: when you want to perform an action (e.g., print, update state) but don't need a result back.

Example from the excerpt:

static void milesToKM(double miles) {
  double km = 1.61 * miles;
  System.out.println(miles + " miles is equivalent to " + km + " Kilometers");
}

๐Ÿ”„ Value-returning methods

A value-returning method returns a value to the statement from where it was called.

  • Signature: public static int methodName(parameter list) { return value; }
  • Must include a return statement with a value matching the return type.
  • The caller captures the returned value in a variable: int sum = calc_Sum(1,1000);
  • Example: calc_Sum(int low, int high) calculates the sum and returns temp.

Example from the excerpt:

static int calc_Sum(int low, int high) {
  int temp = 0;
  for (int i = low; i <= high; i++) {
    temp = temp + i;
  }
  return temp;
}

Comparison table:

FeatureVoid methodValue-returning method
Return typevoidSpecific type (e.g., int, double, String)
Return statementNot required (or return;)Required with a value
Caller usageJust call: methodName(args);Capture result: var = methodName(args);
PurposePerform actionCompute and return result

๐Ÿ”’ Scope of variables

๐Ÿ”’ Local variables

A variable declared inside a method is local to that method and inaccessible to code outside.

  • Different methods can have local variables with the same name without conflict.
  • Example: Chicago_details() and Atlanta_details() both declare city, population, and area; these are independent.
  • The program "sees" only one set at a time (the one in the currently executing method).

๐Ÿ”„ Parameter passing and scope

  • When you pass a variable to a method, the method receives a copy of the value.
  • Changes inside the method do not affect the original variable in the caller.
  • Example: changeVar(var) doubles var inside the method, but var in main() remains 100.

Don't confuse: Passing a variable does not give the method access to the original variable; it only copies the value.

Example output from the excerpt:

var inside main, before calling changeVar(): 100
var inside changeVar(): 200
var inside main, after calling changeVar(): 100

โš ๏ธ Common mistakes and best practices

โš ๏ธ Syntax and structure errors

  1. No semicolon after method header: public static void myMethod() { ... } (not ...();)
  2. No modifiers/return type in calls: call demoMethod(); not static void demoMethod();
  3. Empty parentheses required: even if no arguments, write demoMethod(); not demoMethod;
  4. Declare parameter types in header: void myMethod(String name) not void myMethod(name)

โš ๏ธ Parameter and return value errors

  1. Pass required arguments: if a method expects parameters, you must provide them.
  2. Return statement for non-void methods: value-returning methods must include return value;
  3. Cannot access local variables from outside: temp declared in demoMethodThree() cannot be used in main().
  4. Variable type must match return type: String msg = demoMethodThree(s2); is correct; int weight = demoMethodThree(s2); causes an error.
  5. Argument type must match parameter type: Java performs widening conversion automatically (e.g., int to double) but not narrowing (e.g., double to int).

โœ… Example demonstrating correct usage

The excerpt provides a complete example (demoMethod(), demoMethodTwo(String str), demoMethodThree(String name)) showing:

  • No semicolons after headers.
  • Correct call syntax without modifiers.
  • Empty parentheses for no-argument methods.
  • Parameter types declared in headers.
  • Return statement in value-returning method.
  • Compatible variable type capturing return value.

Key takeaway: Attempting to access a local variable from outside its method or mismatching types will cause compilation errors.

26

Java Methods and Arrays: Exercise Section

4.3 Exercise

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

This section provides programming exercises that apply method-writing skills to solve problems involving number manipulation, prime numbers, string processing, and introduces arrays as collections of same-type values.

๐Ÿ“Œ Key points (3โ€“5)

  • Exercise focus: practice writing methods with proper signatures, parameters, and return types to solve computational problems.
  • Problem categories: number operations (reversing, GCD/LCM, primes), string manipulation (case switching, vowel/consonant operations), validation (passwords), and basic calculator operations.
  • Array introduction: arrays are static data structures that hold multiple values of the same type, declared with dataType[] arrayName and created with the new keyword.
  • Common confusion: declaring an array reference variable (e.g., int[] numbers;) does not create the array itselfโ€”you must use new to allocate memory.
  • Why arrays matter: they allow efficient storage and manipulation of groups of related values, unlike primitive variables that hold only one value at a time.

๐Ÿ”ข Number manipulation exercises

๐Ÿ”„ Reversing and difference calculation

  • Exercise 1 asks you to write void revNum(int num) that reverses a number between 100 and 9,999,999.
  • The method must print the absolute difference between the original and reversed number (ignore sign).
  • Example: if the difference is -XYZ, print only XYZ.

๐Ÿงฎ GCD and LCM methods

  • Exercise 2 builds on earlier chapter problems to create two methods:
    • int GCD(int num1, int num2) returns the greatest common divisor.
    • int LCM(int num1, int num2) returns the least common multiple.
  • Both methods take two integers as parameters and return an integer result.

๐Ÿ” Prime number exercises

โœ… Prime checking

Prime number: a natural number n greater than 1 that is not a product of any natural numbers other than 1 and itself.

  • Exercise 3: write void primeCheck(int n) to determine if n is prime and print the decision.
  • Example: 11 is prime because its only factors are 1 ร— 11.

๐Ÿ“Š Finding prime ranges

  • Exercise 4: write void findPrimes(int lowLimit, int hiLimit) to print all primes between the limits (inclusive).
  • Constraint: 2 โ‰ค lowLimit < hiLimit โ‰ค 999,999.

๐Ÿ’ฌ String processing exercises

๐Ÿ”ค Case switching

  • Exercise 6: write a method that takes a string and switches letter cases (lowercase โ†” uppercase) without using built-in methods.
  • Example input: hgFh@gbBBT5e54& โ†’ output: HGfH@GBbbt5E54&
  • Non-letter characters remain unchanged.

๐Ÿ”  Vowel and consonant operations

  • Exercise 8: write two methods for strings of 7-16 letters:
    • void countVowel(String str) returns total vowel count.
    • void countConsonants(String str) returns total consonant count.

๐Ÿ”„ Character replacement

  • Exercise 9: write methods that replace characters:
    • void replaceVowel(String str): replace vowels with the next consonant in the alphabet.
    • void removeConsonants(String str): replace consonants with the next vowel; if after "U", wrap to "A" or "a".
  • Example: "Peninsula" โ†’ "Ufojouvob"

๐Ÿ” Password validation

  • Exercise 10: write void passwordChecker(String pwd) to validate passwords.
  • Valid password requirements:
    • At least 9 characters long
    • At least one lowercase and one uppercase letter
    • At least one number
    • At least one alphanumeric character

โŽต Whitespace handling

  • Exercise 11: write two methods:
    • findSpace(String input): print locations of whitespaces.
    • removeSpace(String input): print string with all whitespaces removed.
  • Example: "Have a nice day!" โ†’ positions 4, 6, 11 โ†’ "Haveaniceday!"

๐Ÿงฎ Applied calculation exercises

๐Ÿ’ฐ Compound interest

  • Exercise 5: write datatype calculateInterest(parameters) for a bank offering 3.5% compound interest.
  • Conditions: deposit โ‰ฅ 10,000 USD and no withdrawal before 2 years.
  • Method takes deposit amount and duration, returns compound interest.

๐Ÿ”ข Fibonacci sequence

  • Exercise 7: write int fib(int num) that returns the Fibonacci number at position num.
  • References an earlier chapter problem.

โž• Basic calculator

  • Exercise 13: create methods for binary operations (+, โˆ’, ร—, /, %).
  • Program flow:
    • User provides operator (validate input).
    • Take two numbers as input.
    • Write methods like int minus(input1, input2) that return the result.
    • Display output.

๐Ÿ“ฆ Introduction to arrays

๐Ÿ—๏ธ Array declaration and creation

Array: a collection of related data items of the same type; a static data structure whose length remains fixed once created.

  • Declaration syntax: dataType[] arrayName;
  • Example: int[] numbers; declares an array reference variable.
  • Don't confuse: declaring a reference variable does not create the array itself.

๐Ÿ†• Creating arrays with new

  • Use the new keyword to create the array instance in memory.
  • Complete example: int[] numbers = new int[10];
    • Creates an array of 10 integers.
    • The numbers variable holds the memory address of the array.

๐ŸŽฏ Why use arrays

  • Problem: primitive variables (int, float, double) hold only one value at a time.
  • Solution: arrays store and manipulate groups of related values efficiently.
  • Arrays provide a convenient way to work with collections of the same data type.
27

Introduction to Arrays

5.1 Introduction to Arrays

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Arrays provide a convenient and efficient way to store and manipulate multiple values of the same type under a single variable name, avoiding the need to declare hundreds of separate variables.

๐Ÿ“Œ Key points (3โ€“5)

  • What an array is: a collection of related data items of the same type; a static data structure whose length remains fixed once created.
  • Why arrays matter: they replace the need for dozens or hundreds of individual variables (e.g., 365 separate temperature variables for each day of the year).
  • How to create an array: declare a reference variable, then use the new keyword to create the array instance in memory.
  • Common confusion: declaring an array reference variable does not create the array itselfโ€”you must use new to allocate memory.
  • How to access elements: each element has a unique index starting at 0; the last element's index is (length - 1).

๐Ÿ“ฆ What arrays are and why they exist

๐Ÿ“ฆ Definition and characteristics

Array: a collection of related data items of the same type.

  • An array is a static data structureโ€”once created, its length cannot change.
  • Unlike primitive variables (int, float, double) that hold one value at a time, an array holds multiple values.
  • All values in an array must be the same type (e.g., all int, all String).

๐ŸŽฏ Why use arrays

Without arrays, managing multiple related values becomes impractical:

  • Example: storing temperatures for each day of a month would require 30 separate variables (temperatureDay1, temperatureDay2, ..., temperatureDay30).
  • For a full year, you would need 365 or 366 separate variablesโ€”tedious, repetitive, and error-prone.
  • Performing calculations (e.g., finding maximum, minimum, or average) on individual variables is cumbersome.

With arrays, the task becomes manageable:

  • A single array variable can hold all the temperatures: int[] temperature = new int[30];
  • Operations on the entire array or specific subsets become straightforward.
  • Code repetition is reduced, and the program is easier to maintain.

Example: A student roster for a class of fifty students would require 50 separate String variables (student1, student2, ..., student50) without arrays, but only one array variable with arrays: String[] studentRecord = new String[50];

๐Ÿ”ง Creating and declaring arrays

๐Ÿ”ง Declaration syntax

The syntax to declare an array:

dataType[] arrayName;
  • dataType specifies the type of values the array will hold (e.g., int, String).
  • arrayName is the reference variable that will point to the array.

Example: int[] numbers; declares an array reference variable named numbers that can refer to an array of int values.

โš ๏ธ Declaration vs. creation

Important distinction:

  • Declaring an array reference variable does not create the array itself.
  • You must use the new keyword to create the array instance in memory.

Example of complete creation:

int[] numbers = new int[10];
  • This statement creates an array of 10 integer values using new.
  • The numbers variable then contains the memory address of the newly created array.
  • The array has a length of 10.

Don't confuse: declaring int[] numbers; only creates a reference variable; the array itself is not allocated until you use new.

๐Ÿ”ข Accessing array elements with indices

๐Ÿ”ข What is an index

Index: a unique number assigned to each element in an array, used to access and modify that element.

  • Each element in an array can be accessed as an individual variable using its index.
  • Indices allow you to work with specific elements within the array.

๐Ÿ”ข Index numbering rules

Key rule: In Java, the index always starts at 0.

  • The first element has index 0.
  • The second element has index 1.
  • The last element has index (N - 1), where N is the total number of elements.

Example: An array with 30 elements has indices ranging from 0 to 29.

Element positionIndex
First element0
Second element1
Last element (Nth)N - 1

๐Ÿ”ข Accessing and modifying elements

You access or modify elements using the syntax arrayName[index]:

Temperature example:

temperatures[0] = 25;  // 1st day temperature
temperatures[1] = 28;  // 2nd day temperature
temperatures[29] = 28; // Last day temperature (30th day)

Student roster example:

studentRecord[0] = "Alice";
studentRecord[1] = "Bob";

๐Ÿ”ข Array length property

  • Every array has a length property that returns the total number of elements.
  • Syntax: arrayName.length
  • The last valid index is always arrayName.length - 1.

Example: If numbers is an array with 10 elements, numbers.length returns 10, and the last index is 9.

Don't confuse: array length (the total count of elements) with the last index (which is length - 1).

28

Array Manipulation

5.3 Array Manipulation

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Array manipulation encompasses performing calculations over array elements (such as finding averages, maxima, and minima), copying arrays correctly to avoid unintended reference sharing, and applying algorithms like sorting and duplicate removal.

๐Ÿ“Œ Key points (3โ€“5)

  • What array manipulation includes: calculations over elements (average, max, min, standard deviation), copying arrays, and applying algorithms (sorting, removing duplicates).
  • How to calculate statistics: use loops to accumulate sums, compare elements to find extremes, and apply formulas for derived metrics.
  • Common confusion: assigning one array variable to another (destinationArray = sourceArray) does not copy elementsโ€”it creates a reference to the same memory location, so changes to one affect the other.
  • How to copy correctly: iterate through the source array and assign each element individually to the corresponding index in the destination array to ensure separate memory locations.
  • Why it matters: proper manipulation enables data analysis, ensures data integrity when copying, and allows organizing data through sorting.

๐Ÿ“Š Statistical calculations on arrays

๐Ÿ“Š Calculating average temperature

The excerpt demonstrates calculating the average of temperature values stored in an array:

  • Declare a sum variable and initialize it to 0.
  • Use a for loop to iterate over each element in the temperature array, adding each element to sum.
  • When the loop terminates, divide sum by the array's length (temperatures.length).
  • Store the result in averageTemperature and print it.

Example: For seven temperature values, sum all seven and divide by 7 to get the average.

๐Ÿ”ฅ Finding maximum temperature

The excerpt explains finding the maximum value in an array:

  • Declare and initialize maxTemperature with the first element of the array (temperatures[0]).
  • Use a for loop starting from the second element (index 1) to iterate over each remaining element.
  • Check if the current element is greater than maxTemperature; if yes, update maxTemperature to the current element.
  • When the loop terminates, maxTemperature holds the maximum value.

Example: Start with the first temperature as the "current max," then compare each subsequent temperature and update if a higher value is found.

โ„๏ธ Finding minimum temperature

The excerpt mentions the minimum calculation follows a similar pattern to maximum:

  • Declare and initialize minTemperature with the first element.
  • Use a for loop starting from the second element to iterate over the array.
  • Check if the current element is less than minTemperature; if yes, update minTemperature.
  • When the loop terminates, minTemperature holds the minimum value.

๐Ÿ“ Calculating standard deviation

The excerpt provides a formula for standard deviation:

Standard deviation: the square root of (sum of squared differences divided by array length), where the sum of squared differences is the sum of the squared differences between each element and the average.

Steps shown in the code:

  • Calculate the average age first.
  • For each element, compute the difference from the average, square it, and add to sumOfSquaredDifferences.
  • Divide sumOfSquaredDifferences by ages.length.
  • Take the square root using Math.sqrt().

Example: If ages are 21, 20, 19, 20, 21, 19, 20 with average 20.0, compute (21-20)ยฒ + (20-20)ยฒ + (19-20)ยฒ + ... , divide by 7, then take the square root.

๐Ÿงฎ Counting and conditional operations

๐Ÿงฎ Counting students above/below average

The excerpt demonstrates counting elements that meet a condition:

  • Calculate the average first (total age divided by number of students).
  • Use a for loop to iterate through the array.
  • For each element, check if it is greater than the average; if yes, increment aboveAverageCount.
  • Use another for loop to check if each element is less than the average; if yes, increment belowAverageCount.

Example: With average age 20.0, ages 21 and 21 are above average (count = 2), ages 19 and 19 are below average (count = 2).

Don't confuse: Students exactly at the average are counted in neither group in this example.

๐Ÿ“‹ Copying arrays correctly

๐Ÿ“‹ The correct way to copy

The excerpt emphasizes that copying requires element-by-element assignment:

  • Create a new destination array with the same length as the source array.
  • Use a for loop to iterate through each index.
  • Assign each element from sourceArray[i] to destinationArray[i].
  • This ensures both arrays have separate memory locations.

Example code pattern:

int[] destinationArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) {
    destinationArray[i] = sourceArray[i];
}

โš ๏ธ The wrong way: reference assignment

The excerpt warns against a common mistake:

If we write sourceArray = destinationArray, we assign a reference to the array, and both sourceArray and destinationArray refer to the exact memory location.

Consequences:

  • Modifying one array affects the other because they point to the same data.
  • The excerpt demonstrates this with code: after destinationArray = sourceArray, changing destinationArray[0] = 100 also changes sourceArray[0] to 100.
ApproachWhat happensResult
Element-by-element copyEach array has its own memoryChanges to one do not affect the other
Reference assignment (=)Both variables point to the same memoryChanges to one are reflected in the other

Don't confuse: The = operator for arrays does not copy data; it copies the reference (memory address).

๐Ÿ”ง Array algorithms

๐Ÿ”ง Sorting with bubble sort

The excerpt introduces sorting an integer array using the bubble sort algorithm:

Bubble sort: an algorithm that compares adjacent elements in the array and swaps them if they are in the wrong order; this process is repeated until the array is fully sorted.

How it works (from the code):

  • Outer loop runs from i = 0 to arrLength - 1.
  • Inner loop runs from j = 0 to arrLength - i - 1.
  • Compare adjacent elements arr[j] and arr[j+1].
  • If arr[j] > arr[j+1], swap them using a temporary variable.
  • Repeat until no more swaps are needed.

Example: The unsorted array {19, 5, 20, 9, 3, 29, 8, 21, 13} is sorted into ascending order through repeated comparisons and swaps.

๐Ÿ—‘๏ธ Removing duplicates

The excerpt mentions removing duplicates from an array as one of the examples to be covered, though detailed implementation is not provided in this section.

๐Ÿ› ๏ธ Practical patterns

๐Ÿ› ๏ธ Using loops for array operations

The excerpt consistently demonstrates using for loops for array manipulation:

  • Iterate through all elements: for (int i = 0; i < array.length; i++)
  • Accumulate values: add each element to a running total.
  • Compare and update: check each element against a condition and update variables accordingly.
  • Enhanced for loop for printing: for (int element : array) iterates without needing an index.

๐Ÿ› ๏ธ Declaring variables for calculations

The excerpt shows a pattern of declaring accumulator variables before loops:

  • Initialize to appropriate starting values: 0 for sums, first element for max/min, 0 for counts.
  • Update inside loops based on conditions or operations.
  • Use after loops to compute final results or print.

Example: int totalAge = 0, aboveAverageCount = 0, belowAverageCount = 0; declares all needed counters at once.

29

Array Algorithms

5.4 Array Algorithms

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Array algorithms such as sorting and duplicate removal demonstrate how to manipulate array data through systematic iteration and comparison techniques.

๐Ÿ“Œ Key points (3โ€“5)

  • Sorting arrays: Bubble sort compares adjacent elements and swaps them if they are in the wrong order, repeating until the array is fully sorted.
  • Removing duplicates: A manual duplicate-removal algorithm checks each element against a collection of unique elements already found, adding only new ones.
  • Common confusion: Assignment vs. copyingโ€”setting one array variable equal to another (destinationArray = sourceArray) does not copy elements; it makes both variables refer to the same location, so changes to one affect the other.
  • Algorithm structure: Both examples use nested loopsโ€”outer loops traverse the array, inner loops perform comparisons or checks.

๐Ÿ”„ Sorting an Integer Array

๐Ÿซง Bubble sort mechanism

Bubble sort: an algorithm that compares adjacent elements in an array and swaps them if they are in the wrong order, repeating this process until the array is fully sorted.

  • The algorithm uses nested loops:
    • Outer loop runs from index 0 to array length minus 1
    • Inner loop compares adjacent pairs: arr[j] and arr[j+1]
  • When arr[j] > arr[j+1], the two elements are swapped using a temporary variable
  • The process repeats until no more swaps are needed

๐Ÿ“Š How it works step-by-step

  1. Start with an unsorted array (e.g., {19, 5, 20, 9, 3, 29, 8, 21, 13})
  2. Compare each pair of adjacent elements
  3. If the left element is greater than the right element, swap them
  4. Continue through the entire array
  5. Repeat the process until the array is sorted in ascending order
  6. Result: {3, 5, 8, 9, 13, 19, 20, 21, 29}

๐Ÿ”ง Implementation details

  • A bubbleSort() method takes an integer array as input
  • A printArray() method displays array contents before and after sorting
  • The excerpt mentions that the code can be modified to sort in descending order or to use other sorting algorithms like insertion sort

๐Ÿ—‘๏ธ Removing Duplicate Items

๐Ÿ” Duplicate detection logic

The duplicate-removal algorithm traverses the input array and checks if each element is already present in a collection of unique elements found so far.

How the algorithm works:

  • Create a new array uniqueArr to store unique elements
  • Track the count of unique elements with uniqueCount (initially 0)
  • For each element in the original array:
    • Check if it already exists in uniqueArr using an inner loop
    • If found (duplicate): break the inner loop and skip adding
    • If not found (unique): add it to uniqueArr and increment uniqueCount

๐Ÿ“ฆ Edge cases and resizing

Special cases handled:

  • If the array is empty (length = 0) or has only one element (length = 1), return the original array
  • No duplicates are possible in these cases

Final step:

  • Resize uniqueArr using Arrays.copyOf to remove unused elements (initially set to 0)
  • The new size equals uniqueCount (the actual number of unique elements found)

๐ŸŽฏ Example walkthrough

  • Input: {10, 20, 30, 20, 40, 10, 50}
  • Process:
    • 10: unique, add to uniqueArr โ†’ {10}
    • 20: unique, add โ†’ {10, 20}
    • 30: unique, add โ†’ {10, 20, 30}
    • 20: duplicate (already in uniqueArr), skip
    • 40: unique, add โ†’ {10, 20, 30, 40}
    • 10: duplicate, skip
    • 50: unique, add โ†’ {10, 20, 30, 40, 50}
  • Output: {10, 20, 30, 40, 50}

โš ๏ธ Variation: keeping last occurrence

The excerpt notes that the default behavior keeps the first occurrence of duplicates. The code can be modified to keep the last occurrence instead, which would change the output for the same input array to {30, 20, 40, 10, 50}.

๐Ÿ”— Array Reference vs. Copy

๐Ÿšจ Common pitfall: assignment is not copying

The excerpt includes a warning about array assignment:

  • destinationArray = sourceArray does not copy elements
  • It only makes destinationArray refer to the same memory location as sourceArray
  • Changes to one array will affect the other

Example scenario:

  • Before assignment: two separate arrays with identical contents
  • After destinationArray = sourceArray: both variables point to the same array
  • Modifying destinationArray[0] = 100 also changes sourceArray[0] to 100
  • Both arrays now show the modified value

Don't confuse: This is different from copying elements one by one or using a copy method, which would create an independent duplicate array.

30

Multidimensional Arrays

5.5 Multidimensional Arrays

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Multidimensional arrays in Java enable storing data in a table-like structure with rows and columns, making them powerful tools for organizing tabular data and performing operations like matrix multiplication.

๐Ÿ“Œ Key points (3โ€“5)

  • What multidimensional arrays are: arrays that store data in multiple dimensions (rows and columns), with 2D arrays being the most common type.
  • How to declare and initialize: use double brackets syntax with row and column dimensions, and can initialize with nested curly braces.
  • How to access elements: use two indicesโ€”one for the row and one for the column (both zero-based).
  • Common confusion: indices are zero-based, so the first row is index 0, second row is index 1, etc.; same applies to columns.
  • Practical applications: useful for tabular data, matrix operations in mathematics, image processing, and game development.

๐Ÿ“ Structure and syntax

๐Ÿ“ What a 2D array is

A multidimensional array enables storing data in multiple dimensions, with elements arranged in rows and columns, forming a table-like structure.

  • The most common type is a 2D array (also called a matrix).
  • Arrays with three or more dimensions are also possible, but the excerpt focuses on 2D arrays.
  • Think of it as a table where you can store values in a grid format.

๐Ÿ”ค Declaration syntax

The basic syntax for declaring a 2D array:

data_type[][] array_name = new data_type[rows][columns];
  • data_type specifies what type of elements the array holds (e.g., int, String).
  • rows and columns represent the dimensions of the array.
  • Example: int[][] matrix = new int[4][3]; creates a 2D array with 4 rows and 3 columns.
  • All elements are initialized to default values (0 for numeric types).

๐ŸŽฏ Initialization syntax

You can initialize a 2D array with specific values:

data_type[][] array_name = { {value1, value2, value3, ...}, {value4, value5, value6, ...}, ... };
  • Each set of curly braces represents one row.
  • Elements inside the braces are the column values for that row.
  • The number of elements in each row must match the number of columns declared.
  • Example: int[][] matrix = { {1, 2, 3}, {5, 6, 7}, {9, 10, 11} }; creates a 3ร—3 matrix.

๐Ÿ” Accessing and using elements

๐Ÿ” Two-index access

To access elements in a 2D array, use two indices:

int element = matrix[1][2];
  • First index specifies the row, second index specifies the column.
  • Don't confuse: indices are zero-based, so matrix[1][2] accesses the 2nd row, 3rd column.
  • Example: to get the element at row 2, column 3, use matrix[1][2] (not matrix[2][3]).

๐Ÿ” Traversing with nested loops

The excerpt shows how to display all elements using nested loops:

  • Outer loop iterates through rows: for (int i = 0; i < 3; i++)
  • Inner loop iterates through columns: for (int j = 0; j < 3; j++)
  • Access each element with matrix[i][j]
  • This is called "row-major order" traversal.

๐Ÿงฎ Matrix multiplication example

๐Ÿงฎ Multiplication requirements

The number of columns in the first matrix must equal the number of rows in the second matrix for multiplication to be possible.

  • This is a fundamental constraint for matrix multiplication.
  • Example: a 2ร—3 matrix can multiply with a 3ร—2 matrix, but not with a 2ร—2 matrix.

โš™๏ธ How the algorithm works

The excerpt describes the multiplication process:

  1. Get dimensions: Extract rows and columns from both input matrices.
  2. Create result matrix: Size is rows1 ร— columns2.
  3. Calculate each element: For position (i, j) in the result:
    • Take the dot product of the i-th row of matrix1 and j-th column of matrix2.
    • Multiply corresponding elements and sum them up.
  4. Triple nested loop: Outer two loops iterate through result positions, innermost loop calculates the dot product.

๐Ÿ“Š Example calculation

The excerpt provides a concrete example:

Matrix 1Matrix 2Result
1 25 619 22
3 47 843 50
  • Position (0,0) in result: (1ร—5 + 2ร—7) = 19
  • Position (0,1) in result: (1ร—6 + 2ร—8) = 22
  • And so on for all positions.

๐Ÿ’ก Practical applications

๐Ÿ’ก Where 2D arrays are useful

The excerpt mentions several use cases:

  • Tabular data: Organizing data in rows and columns.
  • Matrix operations: Mathematical computations in linear algebra.
  • Image processing: Representing pixel grids.
  • Game development: Storing game boards or tile maps.

๐ŸŽฏ Why they're powerful

  • Provide a structured way to organize and manipulate data.
  • Enable efficient access to elements using row and column coordinates.
  • Support complex operations like matrix multiplication with relatively simple code.
31

Array Pitfalls and Best Practices

5.6 Array Pitfalls and Best Practices

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Understanding common array mistakesโ€”such as index errors, uninitialized elements, and pass-by-reference behaviorโ€”is essential for writing correct and efficient array-based programs.

๐Ÿ“Œ Key points (3โ€“5)

  • Index bounds: Array indices run from 0 to array.length - 1; accessing outside this range causes runtime errors.
  • Default initialization: Arrays are initialized with default values (0 for integers, false for booleans, null for objects), not meaningful data.
  • Type consistency: Arrays must contain elements of a single data type; mixing types causes compilation errors.
  • Common confusion: Arrays passed to methods use pass-by-reference, so modifications inside methods affect the original array outside.
  • Best practices: Use enhanced for loops for traversal, allocate correct array sizes, and be mindful of side effects when passing arrays to methods.

โš ๏ธ Common runtime and logic errors

โš ๏ธ Array index out of bounds

ArrayIndexOutOfBoundsException: a runtime error that occurs when attempting to access an array element using an invalid index.

  • Valid indices range from 0 to array.length - 1.
  • Attempting to access index 5 in a 5-element array (valid indices 0โ€“4) will throw an exception.
  • Example from the excerpt: int[] numbers = {1, 2, 3, 4, 5}; int value = numbers[5]; causes an error because index 5 is out of bounds.
  • Prevention: Always verify that your index is within the valid range before accessing elements.

๐Ÿ”ข Uninitialized array elements

  • When you create an array without explicitly assigning values, Java initializes elements with default values based on data type.
  • Default values:
    • Integers โ†’ 0
    • Booleans โ†’ false
    • Object references โ†’ null
  • The excerpt warns that arrays are "not automatically populated with meaningful values."
  • Example: Creating int[] numbers = new int[5] results in all elements being 0, which may not be the intended data.
  • Best practice: Initialize arrays with appropriate values to ensure elements contain meaningful data from the start.

๐Ÿ“ Incorrect array size

  • Misjudging the required array size leads to two problems:
    • Too small: Data may be lost or overwritten.
    • Too large: Wastes memory (not an error, but inefficient).
  • Example from the excerpt: Declaring int[] scores = new int[10] but only storing 7 student scores leaves 3 elements at their default value (0), which may be misleading when displayed.
  • Implication: The output shows "Student 8: 0, Student 9: 0, Student 10: 0" even though these students don't exist.

๐Ÿšซ Type and traversal constraints

๐Ÿšซ Mixing array types

Arrays are static data structures with a fixed data type.

  • You cannot mix different data types (e.g., integers, strings, doubles) within a single array.
  • Attempting to do so results in a compilation error.
  • Example from the excerpt: int[] mixedArray = {1.5, 2, "Hello", 3.14, 4}; produces multiple compilation errors:
    • incompatible types: possible lossy conversion from double to int
    • incompatible types: String cannot be converted to int
  • Key point: All elements in an array must be of the same declared type.

๐Ÿ”„ Caution during array traversal

  • The excerpt recommends using the enhanced for loop (for-each loop) instead of the traditional for loop.
  • Enhanced for loop advantages:
    • Simpler syntax
    • Cleaner and more readable code
    • Reduces risk of index errors
Loop typeSyntax exampleUse case
Traditional for loopfor (int i = 0; i < numbers.length; i++)When you need the index
Enhanced for loopfor (int num : numbers)When you only need the element value
  • Example from the excerpt shows both approaches produce the same output: 12345.

๐Ÿ”— Pass-by-reference behavior

๐Ÿ”— How arrays are passed to methods

Pass-by-reference mechanism: when a method receives an array as a parameter, it gets a reference to the original array, not a copy of it.

  • Any changes made to array elements within the method are reflected in the original array outside the method.
  • This is different from primitive types (like int, double), which are passed by value.
  • Example from the excerpt: The doubleElements method modifies the array elements, and these changes persist after the method returns.

โšก Side effects and implications

  • Advantage: Efficient for modifying array elements without creating copies.
  • Risk: Modifications inside methods may lead to unintended consequences, especially in large programs.
  • Example scenario from the excerpt:
    • Original array: [1, 2, 3, 4, 5, 6]
    • After calling doubleElements(numbers): [2, 4, 6, 8, 10, 12]
    • The original array is permanently changed.
  • Warning: The excerpt emphasizes being "mindful of side effects" when using arrays as method parameters.
  • Concept check question: The excerpt asks how to prevent the original array from being modified when passed to a method (answer would involve creating a copy, though the excerpt doesn't provide the solution).
32

5.7 Exercise

5.7 Exercise

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

This exercise section provides seven programming problems focused on array manipulation and two problems on 2D array operations, building on the concept that arrays passed to methods can be modified directly.

๐Ÿ“Œ Key points (3โ€“5)

  • Array manipulation tasks: reversing in place, finding elements, merging sorted arrays, and calculating frequencies.
  • Character array operations: counting vowels/consonants, checking palindromes, finding anagrams, and identifying common characters.
  • 2D array operations: transposing matrices and calculating diagonal sums.
  • Common confusion: the exercises build on the side-effect conceptโ€”arrays modified in methods affect the original array unless extra space is used.
  • Skill progression: problems range from basic in-place operations to more complex tasks like merging sorted arrays and matrix transposition.

๐Ÿ”ข Array manipulation exercises

๐Ÿ”„ Reversing arrays in place

Problem 1: Take an integer between 20 and 100 from the user, create an array with that many items, then reverse the array without using extra space.

  • "In place" means modifying the original array directly.
  • "Without using extra space" means no additional array is created.
  • Example approach: swap elements from both ends moving toward the center.

๐Ÿ” Finding specific elements

Problem 2: Find the second smallest element in an array.

  • Given array: [23, 43, 18, 98, 11, 30, 29, 63, 18, 84, 11, 110, 37]
  • Expected output: [23, 43, 98, 11, 30, 29, 63, 84, 11, 110, 37]
  • Note: The output shows the second smallest element (18) removed from the array.

๐Ÿ”— Merging sorted arrays

Problem 3: Merge two sorted arrays into a new sorted array.

  • Array A1: [23, 43, 58, 98, 111, 130]
  • Array A2: [29, 63, 68, 84, 91, 110, 137]
  • Merged result: [23, 29, 43, 58, 63, 68, 84, 91, 98, 110, 111, 130, 137]
  • The result must maintain sorted order.

๐Ÿ“Š Counting frequencies

Problem 4: Find the frequency of each element in a sorted integer array.

  • Input: [1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 7, 7, 7]
  • Output: [1, 3, 4, 2, 2, 2, 1, 3]
  • Each number in the output represents how many times the corresponding unique element appears.
  • Example: 1 appears once, 2 appears three times, 3 appears four times, etc.

๐Ÿ”ค Character array exercises

๐Ÿ”  Vowel and consonant counting

Problem 5: Count vowels and consonants in a character array.

  • Input: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
  • Output: Vowels: 3, Consonants: 7
  • The function must return both counts.

๐Ÿ”„ Palindrome checking

Problem 6: Check if a character array forms a palindrome.

  • A palindrome reads the same forwards and backwards.
  • Example (palindrome): ['r', 'a', 'c', 'e', 'c', 'a', 'r'] โ†’ "It is a palindrome."
  • Example (not palindrome): ['r', 'a', 'c', 'e'] โ†’ "It is not a palindrome."

๐Ÿ”€ Anagram detection

Problem 7: Check if two character arrays are anagrams of each other.

Anagrams: two arrays that contain the same characters with the same frequencies, but possibly in different orders.

  • Example (anagrams): ['l', 'i', 's', 't', 'e', 'n'] and ['s', 'i', 'l', 'e', 'n', 't'] โ†’ true
  • Example (not anagrams): ['h', 'e', 'l', 'l', 'o'] and ['w', 'o', 'r', 'l', 'd'] โ†’ false

๐Ÿ” Finding common characters

Problem 8: Find common characters between two character arrays, showing each unique character only once.

  • Input: ['D', 'E', 'L', 'A', 'W', 'A', 'R', 'E'] and ['F', 'L', 'O', 'R', 'I', 'D', 'A']
  • Output: ['D', 'L', 'A', 'R'] or any order
  • Input: ['h', 'e', 'l', 'l', 'o'] and ['l', 'o', 'l', 'l', 'y', 'p', 'o', 'p']
  • Output: ['l', 'o']
  • Don't confuse: even if 'l' appears multiple times in both arrays, show it only once in the output.

๐Ÿงฎ 2D array exercises

๐Ÿ”„ Matrix transposition

Problem 9: Calculate the transposition of a 2D matrix.

Transposition: rows become columns and columns become rows.

Example:

  • Input matrix A:
    3 2
    1 2
    3 4
    
  • Output matrix A^T:
    3 1 3
    2 2 4
    
  • The first row [3, 2] becomes the first column [3, 2].

โž• Diagonal sum

Problem 10: Calculate the sum of the diagonal elements in a square 2D array.

  • Assumption: number of rows equals number of columns.
  • Input matrix:
    3 2 1 4
    1 2 8 7
    3 4 9 2
    7 4 5 1
    
  • Diagonal elements: 3, 2, 9, 1
  • Output: 15 (sum of 3 + 2 + 9 + 1)
  • The diagonal runs from top-left to bottom-right.
33

Introduction to Class

6.1 Introduction to Class

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Classes in Java serve as blueprints or templates that define the structure and behavior of objects, encapsulating data (instance variables) and code (methods) into new data types that can be instantiated.

๐Ÿ“Œ Key points (3โ€“5)

  • What a class is: a template that defines the structure and behavior of objects, establishing new data types in Java.
  • Class vs object relationship: a class is the blueprint; an object (or instance) is the actual thing created from that blueprintโ€”the terms "object" and "instance" are used interchangeably.
  • What classes contain: instance variables (data/attributes) and methods (behaviors/actions); most real-world classes include both.
  • Common confusion: don't confuse the class (the general template, e.g., "Dog") with an object (a specific instance, e.g., "Mojo the dog").
  • Why classes matter: they organize and define properties and actions, forming the foundation of object-oriented programming in Java.

๐Ÿ—๏ธ What classes are and why they exist

๐Ÿ—๏ธ Classes as blueprints

Class: a blueprint or template for creating objects that defines the structure and behavior of those objects.

  • A class is not an object itself; it is the plan from which objects are built.
  • Classes are declared using the class keyword.
  • They establish new data types that can be instantiated as objects.
  • Example: a class named "Dog" defines what all dogs should have (breed, age) and what they can do (bark, fetch); an individual dog named Mojo is an object created from that class.

๐Ÿ”— Class and object relationship

  • Class: the general definition (e.g., "Dog").
  • Object/Instance: a specific realization of that class (e.g., "Mojo").
  • The excerpt emphasizes that "object" and "instance" are used interchangeably in Java.
  • Don't confuse: the class is the template; the object is what you create from the template.

๐Ÿ“ General structure of a class

๐Ÿ“ Basic class syntax

The excerpt provides a simplified format for defining a class:

class classname {
  type instanceVariable1;
  type instanceVariable2;
  // List all variables
  
  type methodName1(parameter-list) {
    // body of method
  }
  type methodName2(parameter-list) {
    // body of method
  }
  // List all methods
}
  • class classname: declares the beginning of a class definition.
  • Instance variables: represent the data that each object of the class will hold (also called member variables or properties).
  • Methods: functions associated with the class that perform specific actions using the class's data (also called member functions).

๐Ÿงฑ Components of a class

ComponentWhat it isPurpose
Instance variablesData fields (e.g., String breed; int age;)Hold the state/attributes of each object
MethodsFunctions (e.g., void bark() { ... })Define behaviors/actions the object can perform
  • Most real-world classes contain both data and code.
  • Basic classes might consist solely of code or data, but this is less common.

๐Ÿ• Concrete example: the Dog class

๐Ÿ• Defining attributes and behaviors

The excerpt provides a complete example of a "Dog" class:

Instance variables (attributes):

  • String breed โ€“ the dog's breed
  • int age โ€“ the dog's age
  • String color โ€“ the dog's color

Methods (behaviors):

  • void bark() โ€“ makes the dog bark (outputs "Woof! Woof!")
  • void wagTail() โ€“ makes the dog wag its tail (outputs "The dog wags its tail happily.")
  • void play() โ€“ makes the dog play (outputs "The dog plays with joy.")

๐ŸŽฏ How the example illustrates the concept

  • The "Dog" class specifies what all dogs should have (breed, age, color) and what they can do (bark, wag tail, play).
  • An individual dog like Mojo would be an object of the Dog class, with its own specific values for breed, age, and color.
  • Example: if you create a Dog object named Mojo, Mojo can call the bark() method to perform the barking behavior defined in the class.

๐ŸŽ Objects: bringing classes to life

๐ŸŽ What an object is

Object: a real instance created based on a class blueprint, with its own unique characteristics (state) and the ability to perform actions defined by the class.

  • An object is something you can "touch or interact with" in a program.
  • It is built following the blueprint (class).
  • Example analogy from the excerpt: a blueprint for a toy robot tells you what parts it has (arms, legs, head) and what it can do (walk, talk, light up); when you build the robot, you create an object based on that class.

๐Ÿ”„ From class to object

  • The class defines what the object can do and what information it holds.
  • When you create an object, you instantiate the classโ€”you make a concrete instance.
  • Each object has its own unique state (values for instance variables) but shares the same behaviors (methods) defined in the class.
  • Don't confuse: the class is the general definition; the object is the specific, tangible instance with actual data.
34

Objects

6.2 Objects

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Objects in Java are instances built from class blueprints that encapsulate both data (member variables) and behavior (methods), enabling modular and reusable code design where each object maintains its own independent state.

๐Ÿ“Œ Key points (3โ€“5)

  • What an object is: a real instance created from a class blueprint, holding unique characteristics (state) and performing specific actions (behavior).
  • How objects are created: using the new keyword with a constructor that initializes the object's member variables.
  • Member variables vs methods: variables define the object's state (data fields like breed, age, color); methods define the object's behavior (actions the object can perform).
  • Common confusion: the this keywordโ€”it distinguishes class-level member variables from constructor parameters when they share the same name.
  • Why objects matter: each object operates independently with its own state, facilitating modular and reusable code design.

๐Ÿ—๏ธ What objects are and how they work

๐Ÿ—๏ธ The blueprint-to-instance relationship

An object is created based on a blueprint called a class, which defines what the object can do and what information it holds.

  • Think of a class as a blueprint for building a toy robot: the blueprint specifies parts (arms, legs, head) and actions (walk, talk, light up).
  • When you build the robot following that blueprint, you create an object based on that class.
  • In Java, an object is like the real-life robot you build using the blueprintโ€”it has unique characteristics and can perform specific actions.

๐Ÿ”ง How objects encapsulate data and behavior

  • An object encapsulates data (member variables) and behavior (methods) defined within its class.
  • This allows you to create multiple instances of the same class, each with different states and functionalities.
  • Each object operates independently and maintains its own state.
  • Example: Three dogs (Mojo, Vojo, and Dingo) are all instances of the "Dog" class, but each has its own breed, age, and color values.

๐Ÿ› ๏ธ Creating and using objects

๐Ÿ› ๏ธ Object creation with constructors

The excerpt shows how to create an object using the new keyword and a constructor:

Dog myDog = new Dog("Labrador", 3, "Golden");
  • The constructor initializes the object's member variables when the object is created.
  • You pass required values as arguments to the constructor (breed, age, color in this example).
  • The constructor assigns these values to the object's fields.

๐Ÿ”‘ The this keyword

The this keyword is used within the constructor to distinguish between the class-level member variables and the constructor's parameters, as both have the same names.

  • this explicitly refers to the current object's variables.
  • It ensures that the values provided in the parameters are correctly assigned to the object's breed, age, and color fields.
  • Don't confuse: without this, the constructor might not correctly assign parameter values to the object's member variables when names overlap.

๐Ÿ“ž Accessing object methods

  • After creating an object, you invoke its methods using the dot notation: myDog.displayDetails();
  • The method internally accesses the object's member variables to perform actions (e.g., printing breed, age, and color).
  • Each method call operates on the specific object's data.

๐Ÿ“ฆ Class members: variables and methods

๐Ÿ“ฆ Member variables (properties)

Member variables, properties, or attributes are data fields associated with each class instance. They define the state of objects and hold different values for each object.

  • Member variables are declared within the class body.
  • They can have various data types: integers, strings, booleans, or custom objects.
  • In the "Dog" class example: breed, age, and color are member variables representing characteristics specific to each dog object.
  • These variables define attributes that distinguish one dog from another.
AspectDescription
LocationDeclared within the class body
PurposeDefine the state and characteristics of objects
UniquenessEach object instance holds its own values for these variables
ExampleString breed; int age; String color; in the Dog class

โš™๏ธ Member functions (methods)

Member functions, aka methods, encapsulate the behavior or actions that objects can perform.

  • Methods enable objects to exhibit specific behaviors or functionalities.
  • They allow interaction with the object's data and other objects in the system.
  • In the "Dog" class example: displayDetails() is a method that displays the dog's breed, age, and color.
  • Methods operate on the object's member variables to perform their tasks.

๐Ÿ”’ Scope and accessibility

  • The excerpt mentions that understanding the scope and accessibility of class members is crucial for designing well-organized and maintainable code.
  • Member variables can be declared private, restricting direct access from outside the class.
  • The example shows private member variables (private String breed;) that are initialized through a constructor and accessed through methods.
  • This encapsulation protects the object's internal state and controls how data is modified.
35

Class Members and Scope

6.3 Class Members and Scope

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Understanding class members (variables and methods), their access modifiers, and scope is essential for designing well-organized, maintainable object-oriented code that properly encapsulates data and behavior.

๐Ÿ“Œ Key points (3โ€“5)

  • Member variables and methods: Variables define object state/characteristics; methods define behaviors/actions objects can perform.
  • Access modifiers control visibility: public allows access from anywhere; private restricts access to within the same class only.
  • Scope determines accessibility: The scope of a class member defines where in the program it can be accessed or modified.
  • Common confusion: Direct access vs. controlled accessโ€”private variables cannot be accessed directly from outside the class; public getter/setter methods provide controlled access while maintaining encapsulation.
  • Encapsulation principle: Access modifiers help hide internal implementation details and prevent unauthorized access to class members.

๐Ÿ—๏ธ Member variables (properties)

๐Ÿ—๏ธ What member variables represent

Member variables (also called properties or attributes): data fields associated with each class instance that define the state of objects and hold different values for each object.

  • They are declared within the class body.
  • Can have various data types: integers, strings, booleans, or custom objects.
  • Each object instance maintains its own copy of these variables with potentially different values.

๐Ÿ• Example: Dog class attributes

The excerpt uses a Dog class to illustrate member variables:

  • breed (String): represents the breed of the dog
  • age (int): represents the age of the dog
  • color (String): represents the color of the dog

Example: Three dog objects (Mojo, Vojo, and Dingo) are all instances of the Dog class, but each has different values for breed, age, and color, allowing differentiation between individual dogs.

๐ŸŽฌ Member functions (methods)

๐ŸŽฌ What methods encapsulate

Member functions (aka methods): encapsulate the behavior or actions that objects can perform, enabling objects to exhibit specific behaviors or functionalities.

  • Methods allow interaction with the object's data and other objects in the system.
  • They promote code reusability, modularity, and maintainability.
  • Declared within the class and can manipulate the object's state by accessing and modifying member variables.

๐Ÿ• Example: Dog behaviors

The excerpt adds three methods to the Dog class:

  • bark(): simulates a dog barking (prints "Woof! Woof!")
  • wagTail(): simulates a dog wagging its tail
  • play(): simulates a dog playing with joy

These methods encapsulate behaviors associated with dogs and allow Dog objects to exhibit these behaviors.

๐Ÿ” Access modifiers

๐Ÿ” Four types of access control

Java provides four access modifiers that control visibility and accessibility of class members:

ModifierAccessibility
PublicAccess from any other class
PrivateAccess only within the same class
ProtectedAccess within the same package or subclasses
Default (Package-private)Access within the same package

The excerpt focuses on public and private as the most commonly used, providing clear contrast between unrestricted access and strict encapsulation.

๐Ÿ”’ Private members and encapsulation

When member variables are declared private:

  • They are accessible only within the same class.
  • Cannot be accessed or modified directly from outside the class.
  • Controlled access is provided through public accessor (getter) and mutator (setter) methods.

Example: The Dog class declares private String breed, then provides public String getBreed() and public void setBreed(String newBreed) to allow controlled reading and modification of the breed variable.

โš ๏ธ Compilation errors from access violations

The excerpt demonstrates what happens when access rules are violated:

// In Main class, attempting to access private member:
myDog.breed = "Labrador";  // Error: breed has private access in Dog class
System.out.println("My dog's breed is: " + myDog.breed);  // Error

Don't confuse: You cannot use the dot operator to directly access private members from outside the classโ€”this violates encapsulation and results in compilation errors.

๐Ÿ“ Scope of class members

๐Ÿ“ What scope defines

Scope of a class member: defines its accessibility within the program; class members with different access modifiers have different scopes.

  • Understanding scope is vital for writing modular and maintainable code.
  • Helps prevent unintended access and modification of data.
  • Different access modifiers create different scopes affecting accessibility from other classes and methods.

๐ŸŒ Public member scope

When members are declared public:

  • The scope encompasses the entire program.
  • Accessible and modifiable from any class or method within the program.
  • Example: public String breed in the Dog class can be accessed from anywhere, and public void displayBreed() can be invoked from any class or method.

๐Ÿ”’ Private member scope

When members are declared private:

  • The scope is limited to within the declaring class only.
  • Cannot be accessed directly from outside the class.
  • Must use public methods to interact with private members.

Example: The excerpt shows that attempting myDog.breed from the Main class results in a compilation error because breed is private. Instead, the public displayDetails() method internally accesses the private member variables to display information.

๐ŸŽฏ Practical demonstration

The excerpt provides a complete example showing:

  1. Dog class with private member variables (breed, age, color)
  2. Public constructor to initialize these variables using the this keyword
  3. Public displayDetails() method that internally accesses private variables
  4. Main class that creates a Dog object and calls the public method (correct approach)
  5. Commented-out code showing the compilation error from attempting direct access to private members (incorrect approach)

Key takeaway: The scope rules enforce encapsulationโ€”external code must use the public interface (methods) rather than directly manipulating private data.

36

Constructors

6.4 Constructors

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Constructors are special methods that initialize objects when they are created, and Java allows multiple constructors with different parameters to provide flexible initialization options.

๐Ÿ“Œ Key points (3โ€“5)

  • What constructors do: special methods with the same name as the class that set up initial values for an object's attributes when the object is created.
  • Two main types: default constructors (no parameters, set default values) vs. parameterized constructors (accept specific values during creation).
  • Constructor overloading: a class can have multiple constructors with different parameter lists, letting you initialize objects in different ways depending on what information you have.
  • Common confusion: default vs. parameterizedโ€”if you define any constructor explicitly, Java will not automatically provide a default constructor; you must write it yourself if you want both.
  • Why it matters: constructors ensure objects start in a consistent, ready-to-use state and make code more flexible and readable.

๐Ÿ› ๏ธ What constructors are and how they work

๐Ÿ› ๏ธ Definition and purpose

A constructor is a special type of method with the same name as the class that is used to initialize new objects.

  • Constructors assign initial values to an object's attributes.
  • They ensure that an object starts its life in a consistent state.
  • Example: when creating a Dog object, the constructor can immediately set its breed, color, and age so the object is ready to use right away.

๐Ÿ”‘ The this keyword

  • Inside a constructor, this refers to the current object being created.
  • It differentiates between instance variables and parameters that share the same name.
  • Example: this.breed = breed; assigns the parameter breed to the instance variable breed.

๐Ÿ“ Basic constructor syntax

The excerpt shows a Dog class constructor:

public Dog(String breed, String color, int age) {
    this.breed = breed;
    this.color = color;
    this.age = age;
}
  • The constructor name matches the class name (Dog).
  • It takes three parameters and assigns them to the object's instance variables.
  • When you write Dog myDog = new Dog("Poodle", "White", 2);, the constructor runs and initializes myDog with those values.

๐Ÿ”€ Default vs. parameterized constructors

๐Ÿ”€ Default constructors

A default constructor doesn't take any parameters. Java automatically provides one if no other constructors are explicitly defined in the class.

  • The default constructor initializes the object with default values or performs default initialization tasks.
  • Example from the excerpt: the Dog class default constructor sets breed and color to "Unknown" and age to 0.
  • Don't confuse: if you define any constructor yourself, Java will not automatically provide a default constructorโ€”you must write it explicitly if you want one.
Constructor typeParametersWhen to use
DefaultNoneWhen you want to create an object without specifying details upfront
ParameterizedOne or moreWhen you have specific values to set during object creation

๐ŸŽฏ Parameterized constructors

A parameterized constructor takes parameters to initialize the object with specific values.

  • It allows for customization of object initialization by accepting arguments during object creation.
  • Example: Dog poodle = new Dog("poodle", "White", 3); creates a poodle with specific breed, color, and age.
  • The excerpt notes that Section 6.4.1 provides the main example of a parameterized constructor.

๐Ÿ”„ Using both types together

The excerpt shows you can define both a default and a parameterized constructor in the same class:

  • Dog unknownDog = new Dog(); uses the default constructor โ†’ creates a dog with "Unknown" breed/color and age 0.
  • Dog poodle = new Dog("poodle", "White", 3); uses the parameterized constructor โ†’ creates a poodle with specified details.
  • This flexibility lets users of your class choose how much information to provide when creating an object.

๐Ÿงฉ Constructor overloading

๐Ÿงฉ What overloading means

Constructor overloading in Java is a technique where a class includes more than one constructor with different parameter lists.

  • Overloaded constructors can take different numbers of parameters or parameters of different types.
  • This provides flexibility and improves code readability by allowing various ways of object instantiation based on the user context.
  • Example: the Dog class can have a default constructor, a two-parameter constructor (breed and color only), and a three-parameter constructor (breed, color, and age).

๐Ÿ“ฆ Multiple initialization options

The excerpt demonstrates three constructors in the Dog class:

  1. Default constructor: no parameters, sets everything to "Unknown" or 0.
  2. Parameterized constructor 1: takes breed and color only.
  3. Parameterized constructor 2 (overloaded): takes breed, color, and age.

This allows three different ways to create Dog objects:

  • Dog unknownDog = new Dog(); โ†’ breed and color "Unknown", age 0.
  • Dog goldenRetriever = new Dog("Golden Retriever", "Golden"); โ†’ breed and color set, age remains 0 (uninitialized in this constructor).
  • Dog poodle = new Dog("Poodle", "White", 5); โ†’ all three attributes set.

๐ŸŽจ Versatility in practice

  • Constructor overloading lets you match the constructor to the information you have available.
  • Example: if you know only the breed and color of a dog, you can use the two-parameter constructor instead of being forced to provide an age.
  • The excerpt emphasizes that this technique improves code readability and flexibilityโ€”users can choose the most appropriate constructor for their context.
37

Passing Objects as Arguments

6.5 Passing Objects as Arguments

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Passing objects as arguments in Java enables methods to modify the original object because Java passes a copy of the object's reference, not the object itself, which means changes to the object's fields persist but reassignment to a new object does not affect the original reference.

๐Ÿ“Œ Key points (3โ€“5)

  • What Java passes: a copy of the object's reference (the value of the reference), not the object itself or a direct reference link.
  • Effect of modifying fields: changes to the object's fields inside the method affect the original object because both references point to the same object.
  • Effect of reassignment: reassigning the parameter to a new object inside the method does not change the original reference outside the method.
  • Common confusion: "passing by value vs. reference"โ€”Java passes by value, but the value being passed is the reference itself, so it looks like passing by reference when you modify fields, but reassignment reveals the difference.
  • Why it matters: understanding this behavior is crucial for creating flexible and efficient programs and avoiding unexpected bugs when methods manipulate objects.

๐Ÿ”„ How Java passes objects

๐Ÿ“ฆ Pass-by-value of the reference

Java operates on the principle of passing arguments by value: when you pass an object to a method, you pass the object's reference, not the object itself.

  • The method receives a copy of the reference, not a direct link to the original reference variable.
  • This is not the same as "passing by reference" in other languagesโ€”the copy means reassignment inside the method won't affect the caller's reference.
  • Example: if the caller has myDog pointing to object A, the method gets a copy of that pointer; both point to A, but they are separate pointer variables.

๐Ÿ”— Same object, different reference variables

  • Because the copy points to the same object in memory, modifications to the object's fields are visible outside the method.
  • The method and the caller share access to the same object, but each has its own reference variable.
  • Don't confuse: "same object" does not mean "same reference variable."

๐Ÿ› ๏ธ What you can and cannot do

โœ… Modifying the object's fields

  • Changes to fields (e.g., dog.name = "Max") affect the original object.
  • Why: the method's reference and the caller's reference both point to the same object in memory.
  • Example from the excerpt:
    • Before calling changeDog: name is "Buddy", age is 5.
    • Inside changeDog, the code sets dog.name = "Max" and dog.age = 6.
    • After calling changeDog: name is "Max", age is 6โ€”the changes persist.

โŒ Reassigning the reference

  • Reassigning the parameter to a new object (e.g., dog = new Dog("Rocky", 2)) does not change the original reference outside the method.
  • Why: the method has only a copy of the reference; reassigning the copy does not affect the caller's reference variable.
  • Example from the excerpt:
    • Inside changeDog, the code does dog = new Dog("Rocky", 2).
    • This makes the local dog variable point to a new object.
    • The original myDog in main still points to the old object (now with name "Max" and age 6).
    • The new "Rocky" object is not visible outside the method.

๐Ÿ“‹ Detailed example walkthrough

๐Ÿ• The Dog class and TestDog class

The excerpt provides a complete example with a Dog class (fields: name, age; methods: constructor, displayInfo) and a TestDog class with main and changeDog methods.

๐Ÿ” Step-by-step behavior

StepCodeEffect
1. Create objectDog myDog = new Dog("Buddy", 5);myDog references an object with name "Buddy", age 5
2. Call methodchangeDog(myDog);Method receives a copy of the reference to the same object
3. Modify fieldsdog.name = "Max"; dog.age = 6;Original object's fields are changed; myDog now sees "Max" and 6
4. Reassigndog = new Dog("Rocky", 2);Local dog variable points to a new object; myDog is unaffected
5. After methodmyDog.displayInfo();Output: "Name: Max, Age: 6"โ€”field changes persist, reassignment does not

๐Ÿ“ค Output from the example

Before calling changeDog:
Name: Buddy, Age: 5
After calling changeDog:
Name: Max, Age: 6
  • The name and age changed from "Buddy"/5 to "Max"/6 because the method modified the object's fields.
  • The reassignment to "Rocky"/2 inside the method had no effect on myDog.

๐Ÿงฉ Key distinction: value vs. reference

๐Ÿ”‘ What "pass by value" means here

  • Java always passes by value, but for objects, the value being passed is the reference (the memory address).
  • This is different from passing a primitive (like int), where the value is the number itself.
  • Don't confuse: "pass by value of the reference" with "pass by reference"โ€”the latter would mean the method could change what the caller's variable points to, which Java does not allow.

๐ŸŽฏ Why the distinction matters

  • Modifying fields: because both references point to the same object, changes are visibleโ€”this looks like "pass by reference."
  • Reassignment: because the method has only a copy of the reference, reassigning the parameter does not affect the callerโ€”this reveals "pass by value."
  • Understanding this prevents bugs where you expect reassignment to work but it doesn't.

๐Ÿงช Testing your understanding

  • If you want a method to change which object a variable points to, you cannot do it by passing the objectโ€”you must return a new object and reassign in the caller.
  • Example: myDog = changeDog(myDog); with return new Dog("Rocky", 2); would work, but just changeDog(myDog); with internal reassignment will not.
38

Conclusion: Classes and Objects in Java

6.6 Conclusion

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

This chapter provided foundational insights into Java's object-oriented programming by covering class creation, constructors, constructor overloading, and how Java handles object references when passing objects to methods.

๐Ÿ“Œ Key points (3โ€“5)

  • Classes as blueprints: classes serve as templates for creating objects in Java.
  • Constructors and initialization: constructors initialize objects, and constructor overloading allows multiple ways to create objects with different parameters.
  • Passing objects to methods: Java passes a copy of the object's reference (not the object itself), allowing methods to modify the original object but not reassign the reference outside the method.
  • Common confusion: modifying an object's fields inside a method affects the original object, but reassigning the parameter to a new object does not change the original reference.
  • Comprehensive coverage: the chapter moved from basic class creation through constructor techniques to object passing mechanics.

๐Ÿ“š What the chapter covered

๐Ÿ“š Fundamental concepts

The chapter began with:

  • Classes as blueprints: explaining that classes define the structure and behavior for objects.
  • Object creation: how to instantiate objects from class templates.

๐Ÿ”ง Constructors

The chapter explored:

  • Initialization: how constructors set up objects when they are created.
  • Different types: various constructor forms and their purposes.
  • Constructor overloading: providing multiple constructors with different parameter lists for enhanced flexibility when creating objects.

๐Ÿ”„ Passing objects as arguments

๐Ÿ”„ The core mechanism

Java passes arguments by value: when you pass an object to a method, you pass a copy of the object's reference, not the object itself.

  • The method receives a copy of the reference, not a direct link to the original object variable.
  • This sounds like "passing by reference," but it is technically "passing the value of the reference."

โœ๏ธ What you can and cannot do

ActionEffect on original objectWhy
Modify object fields (e.g., dog.name = "Max")Changes the originalThe method's reference points to the same object
Reassign the parameter (e.g., dog = new Dog(...))Does not change the originalOnly the copy of the reference is reassigned; the original reference remains unchanged

๐Ÿ• The "Dog" class example

The chapter used a "Dog" class to illustrate object passing:

  • Before the method call: a Dog object named "Buddy" with age 5 exists.
  • Inside the method:
    • Changing dog.name to "Max" and dog.age to 6 affects the original object.
    • Reassigning dog to a new Dog object ("Rocky", age 2) does not affect the original myDog outside the method.
  • After the method call: the original object now has name "Max" and age 6 (not "Rocky" and 2).

Don't confuse: modifying fields vs. reassigning the referenceโ€”the former changes the original object; the latter only changes the local copy of the reference.

๐Ÿ’ก Why this matters

Understanding this distinction is crucial for:

  • Creating flexible programs: methods can work with and modify objects created elsewhere.
  • Avoiding bugs: knowing that reassignment inside a method won't affect the caller's reference prevents unexpected behavior.
  • Efficient code: passing references (rather than copying entire objects) is more memory-efficient.

๐ŸŽฏ Chapter scope and progression

๐ŸŽฏ From basics to advanced

The chapter provided a logical progression:

  1. Basic class creation: defining classes and their role.
  2. Constructor techniques: initialization, types, and overloading.
  3. Object passing mechanics: how Java handles object references in method calls.

๐ŸŽฏ Foundational insights

The chapter emphasized:

  • Object-oriented principles: classes and objects are central to Java's design.
  • Practical understanding: using concrete examples (the "Dog" class) to clarify abstract concepts.
  • Comprehensive exploration: covering multiple aspects of classes and objects in one cohesive chapter.
39

6.7 Exercises

6.7 Exercises

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

This exercise set reinforces Java object-oriented programming by having learners build classes with properties and methods, test object manipulation, and apply concepts like constructors, method calls, and object state changes.

๐Ÿ“Œ Key points (3โ€“5)

  • What the exercises cover: creating classes (Car, Dog, Circle, Student, BankAccount, etc.) with properties and methods to manipulate and display object state.
  • Core skills practiced: defining properties, writing methods to update/calculate/display data, creating instances, and calling methods.
  • Progression pattern: exercises start with simple display/update methods, then add calculations (area, circumference, dog years), conditional logic (eligibility checks, alerts), and state management (check-out/return, deposit/withdraw).
  • Common confusion: remember that methods modify object state through the referenceโ€”exercises test understanding of how objects are manipulated after creation.
  • Why it matters: these exercises build foundational skills for working with objects, encapsulation, and method design in Java.

๐Ÿš— Basic class creation and state manipulation

๐Ÿš— Car class (Exercise 1)

  • Task: Define a Car class with make, model, and year properties.
  • Methods needed:
    • displayInfo(): show car details.
    • updateYear(int newYear): change the year property.
  • Example scenario:
    Car myCar = new Car("Toyota", "Camry", 2015);
    myCar.displayInfo();  // Output: Car: Toyota Camry, Year: 2015
    myCar.updateYear(2018);
    myCar.displayInfo();  // Output: Car: Toyota Camry, Year: 2018
    
  • Key point: the updateYear method modifies the object's state; the change persists across method calls.

๐Ÿ• Dog age calculations (Exercise 2)

  • Task: Expand the Dog class to calculate and display age in dog years.
  • Method needed: displayDogYears() (likely multiplies human age by 7).
  • Example scenario:
    Dog myDog = new Dog("Buddy", 5);
    myDog.displayDogYears();  // Output: Dog Buddy's age in dog years: 35
    
  • Don't confuse: this is a calculation method, not just a display methodโ€”it computes a derived value from the object's properties.

๐Ÿ”ต Circle geometry (Exercise 3)

  • Task: Implement a Circle class with radius property and methods to calculate area and circumference.
  • Methods needed:
    • calculateArea(): compute and display area.
    • calculateCircumference(): compute and display circumference.
  • Example scenario:
    Circle myCircle = new Circle(5);
    myCircle.calculateArea();           // Output: Area of the circle: 78.54
    myCircle.calculateCircumference();  // Output: Circumference of the circle: 31.42
    
  • Key point: these methods perform mathematical operations on the object's properties.

๐ŸŽ“ Conditional logic and state checks

๐ŸŽ“ Student class with grade management (Exercises 4โ€“5)

  • Task (Exercise 4): Create a Student class with name, age, and grade properties.

  • Methods needed:

    • displayInfo(): show student details.
    • updateGrade(String newGrade): change the grade.
  • Example scenario:

    Student student1 = new Student("Alice", 18, "A");
    student1.displayInfo();      // Output: Name: Alice, Age: 18, Grade: A
    student1.updateGrade("B");
    student1.displayInfo();      // Output: Name: Alice, Age: 18, Grade: B
    
  • Task (Exercise 5): Add a method to check graduation eligibility (grade above a threshold).

  • Method needed: isEligibleForGraduation() (returns or displays eligibility status).

  • Example scenario:

    Student student2 = new Student("Bob", 20, "C");
    student2.isEligibleForGraduation();  // Output: Bob is not eligible for graduation
    
  • Key point: this method uses conditional logic to evaluate object state and return a result.

๐Ÿ• Dog age category checks (Exercise 6)

  • Task: Add methods to check if a dog is a puppy (age < 1) or senior (age > 10).
  • Methods needed: isPuppy(), isSenior() (implied).
  • Example scenario:
    Dog myDog = new Dog("Max", 0.5);
    myDog.isPuppy();  // Output: Max is a puppy
    
  • Don't confuse: these are boolean-style checks that evaluate a condition, not calculations that transform data.

๐Ÿ’ฐ Transaction and state management

๐Ÿ’ฐ BankAccount class (Exercises 7, 10)

  • Task (Exercise 7): Define a BankAccount class with accountNumber, balance, and accountHolder.

  • Methods needed:

    • deposit(double amount): add to balance.
    • withdraw(double amount): subtract from balance.
    • displayInfo(): show account details.
  • Example scenario:

    BankAccount myAccount = new BankAccount("123456789", 1000, "John Doe");
    myAccount.deposit(500);
    myAccount.withdraw(200);
    myAccount.displayInfo();  // Output: Account Number: 123456789, Balance: 1300, Account Holder: John Doe
    
  • Task (Exercise 10): Add a balance alert feature (warn if balance < $1,000).

  • Method needed: checkBalanceAlert() (checks threshold and displays message).

  • Example scenario:

    myAccount.checkBalanceAlert();  // Output: Your account is doing well! Account balance is above $1000.
    myAccount.withdraw(600);
    myAccount.displayInfo();        // Output: Account Number: 123456789, Balance: 700, Account Holder: John Doe
    myAccount.checkBalanceAlert();  // Output: Alert! Account balance is below $1000.
    
  • Key point: the alert method evaluates the current state after transactionsโ€”it demonstrates how methods can monitor and respond to object state changes.

๐Ÿ“ Geometry and multi-property classes

๐Ÿ“ Triangle class (Exercise 8)

  • Task: Implement a Triangle class with properties for all three sides.
  • Methods needed:
    • calculateArea(): compute and display area.
    • calculatePerimeter(): compute and display perimeter.
  • Example scenario:
    Triangle myTriangle = new Triangle(3, 4, 5);
    myTriangle.calculateArea();       // Output: Area of the triangle: 6
    myTriangle.calculatePerimeter();  // Output: Perimeter of the triangle: 12
    
  • Key point: this class requires multiple properties (three sides) and uses them together in calculations.

๐Ÿ“š Object state transitions

๐Ÿ“š LibraryBook class (Exercise 9)

  • Task: Create a LibraryBook class with title, author, and checkedOut properties.
  • Methods needed:
    • checkOut(): mark book as checked out.
    • returnBook(): mark book as returned.
    • displayInfo(): show book details including checkout status.
  • Example scenario:
    LibraryBook book1 = new LibraryBook("Java Programming", "John Smith");
    book1.checkOut();
    book1.displayInfo();  // Output: Book: Java Programming, Author: John Smith, Checked Out: true
    book1.returnBook();
    book1.displayInfo();  // Output: Book: Java Programming, Author: John Smith, Checked Out: false
    
  • Key point: this exercise demonstrates state transitionsโ€”the checkedOut property toggles between true and false, and methods change object state without returning values.
  • Don't confuse: checkOut() and returnBook() are mutator methods that change internal state, not accessor methods that just read data.

๐ŸŽฏ Exercise design patterns

๐ŸŽฏ Common structure across exercises

ElementWhat exercises requirePurpose
PropertiesDefine fields (name, age, balance, etc.)Store object state
ConstructorInitialize objects with starting valuesSet up new instances
Display methodsdisplayInfo() or similarShow current object state
Update methodsupdateYear(), updateGrade(), deposit(), etc.Modify object state
Calculation methodscalculateArea(), displayDogYears(), etc.Derive values from properties
Conditional methodsisEligibleForGraduation(), isPuppy(), checkBalanceAlert()Evaluate state and provide feedback

๐ŸŽฏ Testing approach

  • Pattern: create instances โ†’ call methods โ†’ observe output.
  • Key skill: learners must verify that object state changes persist across method calls (e.g., after updateYear, subsequent displayInfo shows the new year).
  • Example: the BankAccount exercise chains multiple transactions (deposit, withdraw) and checks that balance updates correctly each time.
40

Introduction to File Handling

7.1 Introduction to File Handling

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

File handling in Java enables programs to read from and write to files using the java.io library, allowing persistent storage of data and information beyond program execution.

๐Ÿ“Œ Key points (3โ€“5)

  • What a file is: a named location that stores data (e.g., names) and information (e.g., names combined with addresses).
  • Two main operations: reading from files (requires the file to exist) and writing to files (creating, updating, or deleting; can create a new file if it doesn't exist).
  • The File class: from java.io, creates a File object using a file path, providing methods to check properties and manipulate files.
  • Common confusion: reading vs writing behaviorโ€”reading throws an exception if the file doesn't exist, but writing creates a new file automatically.
  • Why it matters: file handling allows user inputs to be passed to programs and program outputs to be saved persistently.

๐Ÿ“ What files and directories are

๐Ÿ“„ File definition

A file is a named location that can be used to store data and information.

  • Data vs information: data might be raw names; information is data combined with context (e.g., names + addresses).
  • Files provide persistent storageโ€”data remains after the program stops.

๐Ÿ“‚ Directory structure

  • A directory contains collections of files and sub-directories.
  • Sub-directories are directories inside another directory.
  • Sub-directories can exist empty (no files or further sub-directories inside).

๐Ÿ”ง Core file operations

๐Ÿ“– Reading a file

  • Precondition: the file must already exist.
  • If the file does not exist, the program encounters a "file not found exception."
  • Example: a program tries to read my_test_file.txtโ€”if the file is missing, an error is thrown.

โœ๏ธ Writing to a file

Writing includes three sub-operations:

  • Creating: if the file does not exist, the program creates a new file with the given name.
  • Updating: adding new content to an existing file; the program should check if the file exists first.
  • Deleting: removing a file; the program should verify the file exists before attempting deletion.

Don't confuse: reading requires the file to exist beforehand, but writing can create the file on the fly.

๐Ÿ› ๏ธ The File class in Java

๐Ÿ—๏ธ Creating a File object

  • Import the java.io.File library.
  • Create a File object by passing a file path (at minimum, the file name) as a parameter.

Syntax:

File file = new File(String filepath);

Example from the excerpt:

File myFile = new File("my_test_file.txt");

๐Ÿงฐ Built-in methods

The File class provides helpful methods to inspect and manipulate files:

Method NameDescriptionReturn Type
canRead()Tests if the file is readableboolean
canWrite()Tests if the file is writableboolean
canExecute()Checks if the file is executable by the userboolean
createNewFile()Creates an empty fileboolean
delete()Deletes a fileboolean
exists()Tests whether the file existsboolean
getName()Gets the name of the fileString
getAbsolutePath()Gets the absolute pathname of the fileString
length()Gets the size of the file in bytesLong
list()Gets an array of files in the directoryString[]
mkdir()Creates a directoryboolean

๐Ÿ” Using File methods

The excerpt shows two methods in action:

  • canExecute(): checks if the file is executable; stores result in a boolean variable.
  • getAbsolutePath(): retrieves the full path of the file; stores result in a String variable.

Example: after creating File myFile = new File("my_test_file.txt"), calling myFile.canExecute() returns true or false, and myFile.getAbsolutePath() returns the full path as a String.

๐Ÿ“š Reading files with FileReader

๐Ÿ“ฅ How to read file content

The excerpt demonstrates reading a file using a FileReader object:

  1. Create a File object with the file name.
  2. Pass the File object to a FileReader constructor.
  3. Use a character array sized to the file's length: char[] chars = new char[(int) file.length()].
  4. Call reader.read(chars) to read the file content into the array.
  5. Convert the character array to a String: content = new String(chars).

๐Ÿงน Closing resources

  • After reading, call reader.close() to free up resources used by the file.
  • The excerpt emphasizes this is important to avoid resource leaks.
  • The finally block ensures the reader is closed even if an exception occurs.

Don't confuse: forgetting to close the reader can leave system resources tied up, even after the program finishes using the file.

โš ๏ธ Exception handling with try-catch

๐Ÿ›ก๏ธ Why use try-catch

A "try-catch" block is used to handle exceptions by placing code that might throw an exception in the "try" block, and defining how to handle specific exceptions in the corresponding "catch" block.

  • File operations can fail (e.g., file not found, I/O errors).
  • The try block contains the risky code.
  • The catch block defines what to do if an exception occurs (e.g., print the error with e.printStackTrace()).

๐Ÿ”„ The finally block

  • The excerpt shows a finally block that runs regardless of whether an exception occurred.
  • Used to ensure cleanup actions (like closing the reader) always happen.
  • Example: if (reader != null) { reader.close(); } ensures the reader is closed even if reading failed.
41

File Classes in Java

7.2 File Classes in Java

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java's File class from the java.io package enables programmers to create File objects that provide methods to inspect, navigate, and manipulate files and directories without directly reading or writing content.

๐Ÿ“Œ Key points (3โ€“5)

  • What the File class does: creates File objects that represent file paths and provide information about files (existence, type, path, size, etc.) without performing actual read/write operations.
  • How to create a File object: import java.io.File, then instantiate with new File("filename") passing at least a filename as a parameter.
  • Built-in methods: the File class offers methods like exists(), canRead(), canWrite(), getName(), getAbsolutePath(), isDirectory(), isFile(), and listFiles() to query file properties.
  • Common confusion: a File object itself does not read or write file contentโ€”it only holds metadata and path information; actual reading requires additional classes like FileReader.
  • Resource management: when using File objects with readers, always call close() in a finally block to free up system resources.

๐Ÿ“ฆ Creating and using File objects

๐Ÿ“ฆ What a File object represents

A File object: an instance of the File class that represents a file path and provides access to file metadata and properties.

  • The File object does not contain the file's content; it is a reference to a file location.
  • Creating a File object requires passing a file path (at minimum, the filename) as a parameter to the constructor.
  • Example: File myFile = new File("my_test_file.txt"); creates an object representing that file path.

๐Ÿ”ง How to instantiate a File object

  1. Import the File class: import java.io.File;
  2. Call the constructor with a filename or path: File myFile = new File("my_test_file.txt");
  3. The File object is now ready to call methods that inspect the file's properties.

Don't confuse: creating a File object does not create the actual file on diskโ€”it only creates a Java object that points to that path.

๐Ÿ› ๏ธ Built-in methods of the File class

๐Ÿ› ๏ธ Methods for checking file properties

The excerpt provides a table of methods with their descriptions and return types:

Method NameMethod DescriptionReturn Type
canRead()Test whether the file is readableboolean
canWrite()Test whether the file is writableboolean
canExecute()Check if the file is executable by the userboolean
exists()Test whether the file existsboolean
getName()Get the name of the fileString
getAbsolutePath()Get absolute pathname of the fileString
length()Get the size of the file in bytesLong
createNewFile()Create an empty fileboolean
delete()Delete a fileboolean
list()Get an array of the files in the directoryString[]
mkdir()Create a directoryboolean
  • These methods allow inspection and basic manipulation without opening the file for reading or writing.
  • Example: myFile.canExecute() returns true if the file is executable, false otherwise.

๐Ÿ” Example: querying file properties

The excerpt shows Example 2:

  • A File object myFile is created for "my_test_file.txt".
  • Inside a try block, myFile.canExecute() checks if the file is executable and stores the result in a boolean variable.
  • myFile.getAbsolutePath() retrieves the full path and stores it in a String variable.
  • The catch block handles any I/O exceptions by printing the stack trace.

Why try-catch: File operations can throw exceptions (e.g., if the file path is invalid), so the excerpt wraps method calls in a try-catch block to handle errors gracefully.

๐Ÿ“– Reading file content with File objects

๐Ÿ“– How File objects work with FileReader

  • A File object alone does not read file content; it must be passed to a FileReader (or similar class) to access the data inside.
  • Example 3 demonstrates this workflow:
    1. Create a File object: File file = new File("my_test_file.txt");
    2. Create a FileReader and pass the File object: FileReader reader = new FileReader(file);
    3. Read the content into a character array: char[] chars = new char[(int) file.length()]; then reader.read(chars);
    4. Convert the character array to a String: content = new String(chars);
    5. Print the content and close the reader: reader.close();

๐Ÿ”’ Resource management: closing the reader

  • The excerpt emphasizes calling reader.close() to free up system resources.
  • The close() call should happen after all tasks are complete.
  • Example 3 uses a finally block to ensure the reader is closed even if an exception occurs: if (reader != null) { reader.close(); }

Don't confuse: the File object itself does not need to be closedโ€”only the FileReader (or other stream/reader objects) must be closed.

๐Ÿ—‚๏ธ Navigating and distinguishing files vs directories

๐Ÿ—‚๏ธ Listing files in a directory

  • The listFiles() method returns an array of File objects (or pathnames) representing files and directories in the specified directory.
  • Example 4:
    • A File object f is created for the root directory "/".
    • f.listFiles() returns an array of File objects for all items in that directory.
    • A for-each loop iterates over the array and prints each file or directory name using path.getName().

๐Ÿ“ Checking if a path is a directory

  • The isDirectory() method returns true if the File object represents a directory, false otherwise.
  • Example 5:
    • A File object f is created for "test.txt".
    • f.createNewFile() creates the file on disk.
    • f.getAbsoluteFile() returns a new File object with the absolute path.
    • f1.isDirectory() checks if the path is a directory and prints the result.

๐Ÿ“„ Checking if a path is a file

  • The isFile() method returns true if the File object represents a regular file, false otherwise.
  • Example 6 mirrors Example 5 but uses f1.isFile() instead.

Common confusion: a File object can represent either a file or a directoryโ€”use isFile() and isDirectory() to distinguish between them.

42

File Navigation and Manipulation

7.3 File Navigation and Manipulation

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java's File class provides methods to inspect, navigate, and manipulate files and directories, enabling programs to check file properties, list directory contents, and perform operations like creating, deleting, and renaming files.

๐Ÿ“Œ Key points (3โ€“5)

  • File class capabilities: The File class offers methods to check file properties (executable status, existence, size), retrieve paths, and list directory contents.
  • Navigation methods: listFiles() returns an array of files/directories in a directory; getAbsolutePath() retrieves the full path; getName() gets the filename.
  • File vs directory distinction: isDirectory() and isFile() methods help distinguish whether a path points to a directory or a regular file.
  • Common confusion: A File object represents a pathname, not the file content itselfโ€”reading content requires additional classes like FileReader.
  • Manipulation operations: Files can be created (createNewFile()), deleted (delete()), and renamed (renameTo()) using File class methods.

๐Ÿ“‚ File Class Methods and Properties

๐Ÿ” Checking file properties

The File class provides several boolean methods to inspect file characteristics:

  • canExecute(): Returns true if the file is executable by the user
  • exists(): Tests whether the file exists at the specified path
  • length(): Returns the file size in bytes (Long type)

Example: A File object can check if "my_test_file.txt" is executable using myFile.canExecute(), which returns a boolean value.

๐Ÿ“ Path and name retrieval

Two key methods retrieve file location information:

MethodReturn TypePurpose
getName()StringGets the filename only
getAbsolutePath()StringGets the complete pathname from root

Don't confuse: getName() returns just the filename (e.g., "test.txt"), while getAbsolutePath() returns the full path (e.g., "/users/documents/test.txt").

๐Ÿ—‚๏ธ Directory Navigation

๐Ÿ“‹ Listing directory contents

listFiles(): Returns an array of pathnames (File[]) for files and directories in the directory denoted by the File object.

  • The method returns a File array, not a String array of names
  • Each element in the array is itself a File object representing a file or subdirectory
  • You can iterate through the array to process each file/directory

Example: Creating a File object pointing to "/" and calling listFiles() returns an array of all files and directories in the root directory, which can be looped through to print each name.

๐Ÿ”Ž Distinguishing files from directories

isDirectory() method:

  • Returns true if the pathname points to a directory
  • Returns false otherwise

isFile() method:

  • Returns true if the pathname points to a regular file
  • Returns false otherwise

Don't confuse: A path can exist but be neither a file nor a directory (e.g., a symbolic link or special system object), so both methods might return false.

โœ๏ธ File Manipulation Operations

โž• Creating files

createNewFile(): Creates an empty file at the specified pathname.

  • Returns a boolean indicating success
  • Must handle exceptions (IOException) when creating files
  • The file is created in the filesystem, not just in memory

๐Ÿ”„ Renaming files

The renameTo() method changes a file's name:

  • Takes another File object as parameter representing the new name
  • Returns boolean indicating whether the rename succeeded
  • Syntax: oldFile.renameTo(newFile)

Example: To rename "test.txt" to "test1.txt", create two File objects and call f.renameTo(f1), which returns true if successful.

๐Ÿ—‘๏ธ Deleting files

delete(): Removes the file or directory from the filesystem.

  • Returns boolean indicating success
  • The file must exist for deletion to succeed
  • After deletion, the File object still exists in memory but no longer points to an existing file

๐Ÿ“– Reading File Content

๐Ÿ“„ FileReader basics

The excerpt shows that reading file content requires a separate class:

  • A File object is passed as a parameter to FileReader constructor
  • FileReader enables reading the character stream from the file
  • The File object's length() method helps determine how many characters to read

๐Ÿ”’ Resource management

Important principle demonstrated in the examples:

  • Always call close() on the reader after finishing file operations
  • Use try-catch-finally blocks to ensure resources are freed even if errors occur
  • The finally block ensures reader.close() executes regardless of exceptions

Don't confuse: The File object itself doesn't need closingโ€”only the FileReader (or other stream objects) must be closed to free system resources.

43

Reading and Writing Text Files

7.4 Reading and Writing Text Files

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Java provides several classes for reading and writing text files, with buffered versions offering better performance for larger data operations through internal buffering mechanisms.

๐Ÿ“Œ Key points (3โ€“5)

  • FileReader and FileWriter: simple classes for reading character streams and writing strings to files directly.
  • BufferedReader and BufferedWriter: more efficient alternatives that use internal buffers, making them better for frequent or large-scale file operations.
  • Common confusion: FileWriter vs BufferedWriterโ€”FileWriter writes directly to disk (good for small writes), while BufferedWriter uses a buffer (better for frequent or large writes).
  • Exception handling: file operations can fail (e.g., file not found, no access), so try-catch blocks are essential to prevent crashes.
  • Basic pattern: create a reader/writer object with a filename, perform read/write operations, then close the object.

๐Ÿ“– Reading from files

๐Ÿ“– FileReader basics

FileReader: a class from java.io that reads a stream of characters from files.

  • Provides an easy way to read input from a file character by character.
  • The read() method returns the next character as an integer; returns -1 when the file is empty or reaches end-of-file.
  • Example pattern: create a FileReader with a filename, loop while read() doesn't return -1, cast each integer to a character, then close the reader.

Don't confuse: the integer returned is the character code, not the character itselfโ€”you must cast (char)i to display it.

๐Ÿ“š BufferedReader for efficiency

BufferedReader: a class from java.io that reads character-input streams using buffering, making it efficient for reading characters, arrays, and lines.

  • Uses an internal buffer to reduce the number of disk reads.
  • Requires a FileReader object to be passed to its constructor.
  • The excerpt shows a two-step pattern:
    1. Create a FileReader object with the filename.
    2. Pass that FileReader to a new BufferedReader.
  • Can read into a character array using read(charArray).
  • Must be closed after use, just like closing a file.

Why buffering matters: reading directly from disk is slow; buffering reads larger chunks at once and stores them in memory, improving performance for repeated reads.

โœ๏ธ Writing to files

โœ๏ธ FileWriter basics

FileWriter: a class from java.io used to write to a file; creates the file if it does not exist.

  • Simple pattern: create a FileWriter with a filename, use write(data) to write a string, then close the writer.
  • Writes directly to the file on disk.
  • Limitation: the excerpt notes it is "only good for situations in which a small amount of writing is needed" and "limited to a set number of characters or string length."

๐Ÿ—‚๏ธ BufferedWriter for larger operations

BufferedWriter: similar to FileWriter but uses an internal buffer to write data into files, making it a better choice for frequent or large-scale writing.

  • The excerpt states: "if more frequent writing is needed, then BufferedWriter is a good choice."
  • Requires a FileWriter object to be passed to its constructor (same two-step pattern as BufferedReader).
  • Pattern:
    1. Create a FileWriter with the filename.
    2. Pass that FileWriter to a new BufferedWriter.
    3. Use write(data) on the BufferedWriter.
    4. Close the BufferedWriter.
ClassBest forHow it works
FileWriterSmall, infrequent writesWrites directly to disk
BufferedWriterLarge or frequent writesUses internal buffer to batch writes

Don't confuse: both can write strings, but BufferedWriter reduces disk access by buffering, making it faster for repeated operations.

โš ๏ธ Exception handling in file operations

โš ๏ธ Why exceptions occur

IOException: a checked exception in Java that occurs when an attempt to open a file denoted by a specified pathname fails.

  • The excerpt lists common causes:
    • Dividing by zero (general exception example).
    • Attempting to open a file that does not exist.
    • Wrong file name or file not in the expected directory.
    • Trying to write to a file the program or user does not have access to.
  • If not handled, exceptions can cause "data loss, incorrect calculations, or even a complete system crash."

๐Ÿ›ก๏ธ Using try-catch blocks

  • FileNotFoundException: a specific type of IOException that occurs when a file cannot be found.
  • The excerpt shows two versions of the same code:
    • Without try-catch: the method signature includes throws IOException, which passes the exception up to the caller (can crash the program).
    • With try-catch: wraps file operations in a try block and catches FileNotFoundException, printing a user-friendly message instead of crashing.

Pattern:

try {
  // create File and Scanner/Reader/Writer
  // perform read/write operations
  // close the file
} catch (FileNotFoundException e) {
  // handle the error gracefully
}

Why this matters: run-time errors in file handling are not programming errorsโ€”they depend on external factors (file existence, permissions). Proper exception handling allows the program to "continue to function without disrupting its natural flow."

44

Exception Handling

7.5 Exception Handling

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Exception handling in Java file operations prevents unexpected behaviorsโ€”like missing files or access errorsโ€”from crashing programs by using try-catch blocks to manage run-time errors gracefully.

๐Ÿ“Œ Key points (3โ€“5)

  • What exceptions are: situations that lead to unexpected behavior (e.g., dividing by zero, opening non-existent files) that can cause data loss, incorrect calculations, or system crashes if not handled.
  • IOException and FileNotFoundException: checked exceptions that occur when file operations fail (wrong filename, file not in expected directory).
  • How to handle: use try-catch blocks to catch exceptions and allow the program to continue functioning without disrupting its natural flow.
  • Common confusion: run-time errors vs programming errorsโ€”run-time errors aren't coding mistakes but environmental issues (file moved between systems, access permissions) that must be anticipated.
  • Best practices: use specific exceptions in catch blocks, avoid empty catch blocks, and don't overuse checked exceptions.

๐Ÿšจ Understanding exceptions in file handling

๐Ÿšจ What exceptions are

Exception: a situation that leads to unexpected behavior in programming.

  • Not a programming error but an unexpected condition during execution.
  • Common file-handling scenarios:
    • Dividing by zero
    • Attempting to open a file that does not exist
    • Trying to write to a file without proper access permissions
  • Consequences if not handled: data loss, incorrect calculations, or complete system crash.

๐Ÿ“ IOException and FileNotFoundException

IOException: a checked exception in Java that occurs when an attempt to open a file denoted by a specified pathname fails.

  • FileNotFoundException is a part of IOException.
  • Occurs when:
    • The file name is wrong
    • The file is not available in the directory where the code is looking for it
  • Example scenario: A program tries to open "input.txt" but the file doesn't exist or is in a different location.

๐Ÿ›ก๏ธ Exception handling mechanisms

๐Ÿ›ก๏ธ Try-catch blocks

The excerpt shows two versions of the same file-reading code:

Without exception handling (Example 13):

  • Uses throws IOException in the method signature
  • If the file is missing, the program will show FileNotFoundException and crash

With exception handling (Example 14):

  • Wraps file operations in a try block
  • Catches FileNotFoundException in a catch block
  • Displays a user-friendly message: "There was some problem opening the file"
  • Program continues to function instead of crashing

๐Ÿ”„ Why exception handling matters for file operations

  • Run-time errors are not programming errors: they arise from environmental conditions, not code mistakes.
  • Programs move between systems: a file path that works on one machine may not work on another.
  • Multiple failure points: reading non-existent files, writing to files without access permissions.
  • Goal: allow the program to continue functioning without disrupting its natural flow.

Don't confuse: A run-time error (like a missing file) is different from a syntax error or logic bugโ€”it's an external condition the program must handle gracefully.

โœ… Best practices

โœ… Exception handling guidelines

The excerpt provides specific recommendations:

PracticeWhat to do
Use try-catch blocksWrap file operations to catch exceptions
Use specific exceptionsCatch FileNotFoundException rather than generic Exception
Avoid empty catch blocksDon't silently ignore exceptionsโ€”at minimum, log or display a message
Avoid overusing checked exceptionsDon't force exception handling where it's not needed

๐ŸŽฏ Simple try-catch pattern

The excerpt emphasizes that a "simple try...catch block can help to ease the program flow":

  • Place file operations inside the try block
  • Specify the exact exception type in the catch block (e.g., FileNotFoundException)
  • Provide meaningful feedback or alternative actions in the catch block
  • This pattern prevents the entire program from crashing due to a single file issue

Example: Instead of the program terminating when "input.txt" is missing, it prints a helpful message and continues execution.

45

Best Practices and Error Handling

7.6 Best Practices and Error Handling

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Proper exception handling in Java file operations requires using try-catch blocks with specific exceptions to maintain program flow and prevent crashes when files are missing or inaccessible.

๐Ÿ“Œ Key points (3โ€“5)

  • Core practice: Use try-catch blocks to catch exceptions during file handling operations.
  • Specificity matters: Use specific exceptions in catch blocks rather than generic ones; avoid empty catch blocks.
  • Why it's needed: Run-time errors in file handling (missing files, access denied) are not programming errors but environmental issues that must be handled gracefully.
  • Common confusion: Run-time errors vs programming errorsโ€”run-time errors occur due to external conditions (file not found, wrong permissions) and can happen when moving programs between systems.
  • Performance insight: Reading files in bulk is fastest, line-by-line is moderate, and character-by-character is slowest.

๐Ÿ›ก๏ธ Exception handling fundamentals

๐Ÿ›ก๏ธ What exceptions are in file operations

An exception is a situation that leads to unexpected behavior, such as attempting to open a file that does not exist.

  • In file handling, exceptions occur when operations fail due to external conditions.
  • If not handled properly, exceptions can cause data loss, incorrect calculations, or complete system crashes.
  • Example: IOException is a checked exception in Java that occurs when an attempt to open a file denoted by a specified pathname fails.

๐Ÿ” FileNotFoundException example

The excerpt shows that FileNotFoundException is part of IOException and may occur if:

  • The file name is wrong
  • The file is not available in the directory where the code is looking for it

Without exception handling (Example 13):

  • Code uses throws IOException in the method signature
  • If the file "input.txt" does not exist, the program will crash with FileNotFoundException

With exception handling (Example 14):

  • Code wraps file operations in a try block
  • Catch block handles FileNotFoundException specifically
  • Displays user-friendly message: "There was some problem opening the file"
  • Program continues to function without disrupting its natural flow

โš ๏ธ Why run-time errors need special handling

  • Run-time errors are not exactly programming errorsโ€”they arise from environmental conditions.
  • Common scenarios:
    • Trying to read a non-existent file
    • Trying to write to a file that the program or user does not have access to
  • These situations can happen as a program is moved from one system to another.
  • Don't confuse: Programming errors (bugs in code logic) vs run-time errors (environmental issues like missing files or permissions).

๐Ÿ“‹ Best practices checklist

๐Ÿ“‹ Four key rules

The excerpt lists specific steps that should be taken while handling files in Java:

PracticeWhat it means
Use try-catch blocksWrap file operations to catch exceptions
Use specific exceptionsCatch FileNotFoundException rather than generic Exception
Avoid empty catch blocksDon't leave catch blocks without any handling code
Avoid overusing checked exceptionsDon't force exception declarations unnecessarily

โœ… Proper try-catch structure

  • Place file opening, reading, and closing operations inside the try block.
  • Specify the exact exception type in the catch block (e.g., FileNotFoundException).
  • Provide meaningful error messages or recovery logic in the catch block.
  • Simple try-catch blocks can help ease the program flow and prevent crashes.

๐Ÿ“‚ CSV file handling

๐Ÿ“‚ What CSV files are

CSV stands for comma-separated values, which means all the data stored in a CSV file is usually separated by commas.

  • File extension: .csv
  • Example format: John, Doe, 2, 998888, USA

๐Ÿ“‚ Reading CSV files in Java

The excerpt provides Example 15 showing step-by-step how to read a CSV file:

  • Import necessary libraries (java.io.*, java.util.Scanner)
  • Create a Scanner object with the CSV file
  • Use useDelimiter(",") to specify comma as the delimiter
  • Loop through tokens with hasNext() and next()
  • Close the scanner after reading

โšก Performance comparison of reading methods

โšก Three reading approaches

The excerpt compares three methods for reading files (Example 16):

MethodDescriptionPerformance
Read in bulkFiles.readAllBytes() reads entire file at onceFastest (0.008 seconds for 100KB file)
Read line by lineFiles.lines() processes one line at a timeModerate (0.039 seconds for 100KB file)
Read character by characterFileInputStream.read() processes one character at a timeSlowest (0.243 seconds for 100KB file)

โšก Performance conclusions

  • Reading in bulk is fastest because it minimizes I/O operations.
  • Reading line by line is faster than character-by-character but slower than bulk.
  • Reading character by character is the slowest method.
  • Example output from the performance test:
    • Read bulk took 0.008 seconds
    • Read line by line took 0.039 seconds
    • Read character by character took 0.243 seconds

โšก When to use each method

The excerpt demonstrates the trade-offs but does not prescribe specific use cases; the choice depends on:

  • Whether you need to process the entire file at once (bulk)
  • Whether you need to process line-by-line (streaming large files)
  • Whether you need character-level control (parsing or validation)
46

7.7 Practical Examples and Exercises

7.7 Practical Examples and Exercises

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

Reading files in bulk is significantly faster than reading line-by-line or character-by-character in Java, and CSV file handling is a major practical advantage of Java file I/O.

๐Ÿ“Œ Key points (3โ€“5)

  • CSV file handling: Java can read comma-separated values files by setting a delimiter and scanning tokens.
  • Three reading strategies: bulk (all at once), line-by-line, and character-by-character, each with different performance characteristics.
  • Performance hierarchy: bulk reading is fastest, line-by-line is intermediate, and character-by-character is slowest.
  • Common confusion: don't assume all reading methods have similar speedโ€”the difference can be dramatic (e.g., 0.008 seconds vs 0.243 seconds for the same file).
  • Practical exercises: the section provides 10 programming tasks covering file creation, reading, writing, appending, and pattern matching.

๐Ÿ“„ CSV file handling

๐Ÿ“„ What CSV files are

CSV stands for comma-separated values, which means all the data stored in a CSV file is usually separated by commas.

  • File extension: .csv
  • Example format: John, Doe, 2, 998888, USA
  • Each value is separated by a comma delimiter.

๐Ÿ”ง How to read CSV files in Java

The excerpt provides a complete example (Example 15) that demonstrates:

  • Import libraries: java.io.* and java.util.Scanner
  • Pass the file name: create a Scanner object with new File("test.csv")
  • Specify the delimiter: use sc.useDelimiter(",") to set the comma as the separator
  • Loop through tokens: while (sc.hasNext()) returns a boolean to check if more tokens exist
  • Retrieve tokens: sc.next() finds and returns the next complete token
  • Close the scanner: sc.close() releases resources

Example: If a CSV file contains John, Doe, 2, 998888, USA, the scanner will read each value separately by splitting on commas.

โšก Performance comparison of reading strategies

โšก Three reading methods

The excerpt compares three approaches using Example 16:

MethodDescriptionImplementation
BulkRead all bytes at onceFiles.readAllBytes(file.toPath()) returns a byte array
Line-by-lineRead one line at a timeFiles.lines(file.toPath()) returns a stream of lines
Character-by-characterRead one character at a timeFileInputStream.read() returns one character per call

๐Ÿ“Š Performance results

The excerpt provides concrete timing data for a 100KB file:

  • Bulk reading: 0.008 seconds (fastest)
  • Line-by-line reading: 0.039 seconds (intermediate)
  • Character-by-character reading: 0.243 seconds (slowest)

Why the difference matters:

  • Bulk reading loads everything into memory at once, minimizing I/O operations.
  • Line-by-line reading performs I/O for each line, adding overhead.
  • Character-by-character reading performs I/O for every single character, creating maximum overhead.

Don't confuse: "character-by-character" does not mean "more precise"โ€”it simply means more I/O calls, which slows down the program significantly.

๐Ÿ” How the comparison works

The example uses System.nanoTime() to measure elapsed time:

  • Record start time before reading: long start = System.nanoTime()
  • Perform the read operation
  • Calculate elapsed time: long time = System.nanoTime() - start
  • Convert nanoseconds to seconds: divide by 1e9
  • Output formatted result: System.out.printf("Read bulk took %.3f seconds\n", time / 1e9)

๐Ÿ› ๏ธ Practice exercises

๐Ÿ› ๏ธ Basic file operations (Exercises 1โ€“3)

The excerpt lists 10 exercises; the first three cover fundamentals:

  1. Create a new file: practice file creation in Java
  2. Read and display: read a text file and show content on screen
  3. Copy file content: read from first.txt and write to second.txt

๐Ÿ“‹ CSV and advanced operations (Exercises 4โ€“8)

More complex tasks:

  1. CSV copying: read from first.csv and write to second.csv
  2. Line-by-line reading: read a file one line at a time
  3. Partial reading: read only the first 3 lines
  4. Pattern matching: find the line that matches a given word
  5. Appending: write a new line to an existing file without removing previous content (hint: use append mode)

Don't confuse: "write to an existing file" can mean either overwrite (replace all content) or append (add to existing content)โ€”Exercise 8 specifically requires append.

๐Ÿ”ง BufferedReader and storage (Exercises 9โ€“10)

Final two exercises focus on specific techniques:

  1. BufferedReader: read content using the BufferedReader class
  2. Store in variable: read a file line-by-line and store the content in a variable (not just display it)
47

7.8 Exercise

7.8 Exercise

๐Ÿงญ Overview

๐Ÿง  One-sentence thesis

This exercise section provides ten practice problems to reinforce file I/O skills in Java, ranging from basic file creation and reading to more advanced tasks like appending content and working with CSV files.

๐Ÿ“Œ Key points (3โ€“5)

  • Scope of exercises: covers creating files, reading/writing text and CSV files, line-by-line processing, pattern matching, and appending.
  • Progression: starts with simple tasks (create a file, read and display) and moves to more complex operations (append without overwriting, BufferedReader usage).
  • Key techniques practiced: bulk reading vs. line-by-line vs. character-by-character; file copying; selective reading (first N lines, matching lines).
  • Common confusion: appending vs. overwritingโ€”exercise 8 explicitly requires preserving existing content when writing new lines.

๐Ÿ“ Basic file operations

๐Ÿ“ Creating and reading files

  • Exercise 1: Write a program to create a new file.
    • Tests the ability to instantiate file objects and handle file creation.
  • Exercise 2: Read a text file's content and display it on the screen.
    • Reinforces reading from a file and outputting to standard output.
    • Example: Open "data.txt", read its contents, and print each line to the console.

๐Ÿ“ Copying files

  • Exercise 3: Read from one text file (e.g., first.txt) and write to another (e.g., second.txt).
    • Combines reading and writing operations; tests understanding of input/output streams.
  • Exercise 4: Read from a CSV file (e.g., first.csv) and write to another CSV file (e.g., second.csv).
    • Same pattern as exercise 3, but with Comma-Separated-Values format.
    • Don't confuse: CSV files are still text files, but the structure (comma delimiters) may require special handling in more advanced scenarios.

๐Ÿ” Line-based processing

๐Ÿ” Reading line by line

  • Exercise 5: Read a file line by line.
    • Focuses on iterating through file content one line at a time (as opposed to bulk reading).
  • Exercise 6: Read only the first 3 lines of a file.
    • Tests selective reading and loop control (stopping after a fixed number of lines).
    • Example: Open a file, read lines in a loop, and break after the third line.

๐Ÿ” Pattern matching

  • Exercise 7: Find the line that matches a given word.
    • Combines line-by-line reading with string searching.
    • Example: Search for the word "error" in a log file and return the matching line(s).

โž• Appending and advanced reading

โž• Appending to existing files

  • Exercise 8: Write a new line to an existing file without removing previous content.
    • The file may or may not already have content.
    • Hint provided: use "append" mode.
    • Don't confuse: appending vs. overwritingโ€”default file write operations often overwrite; append mode preserves existing content.

โž• Using BufferedReader

  • Exercise 9: Read content from a file using BufferedReader.
    • Reinforces the use of BufferedReader, which is efficient for line-by-line reading.
  • Exercise 10: Read a file line by line and store it into a variable.
    • Tests the ability to accumulate file content in memory (e.g., a String or List variable).
    • Example: Read all lines from a file and concatenate them into a single String variable.

๐Ÿ“Š Summary table

ExerciseTaskKey skill
1Create a new fileFile instantiation
2Read and display text fileBasic reading + output
3Copy text file to anotherRead + write combination
4Copy CSV file to anotherCSV handling (text format)
5Read file line by lineLine-based iteration
6Read first 3 linesSelective reading + loop control
7Find line matching a wordPattern matching + search
8Append new line to fileAppend mode (preserve content)
9Read using BufferedReaderEfficient line reading
10Store file lines in variableIn-memory accumulation
    Programming with Java | Thetawave AI โ€“ Best AI Note Taker for College Students