Operations, Control Flow, Methods, and String Handling in Java, CS 101 – Study Notes
offline

Difficulty: Beginner to Intermediate | Prerequisites: Java Fundamentals (compilers, data types, memory).


Big Picture

Once you know how Java stores data, the next step is learning how to operate on it: arithmetic, logic, decision-making, repetition, and organising reusable blocks of code into methods. String handling sits here too, because strings are the most common data you will manipulate in early programs. This unit bridges the gap between "I can declare a variable" and "I can write a program that solves a real problem." If you are behind, make sure you are comfortable with primitive types, reference types, and the difference between syntax and semantic errors before diving in.


TL;DR

Java provides arithmetic, modulo, and logical operators. Control flow uses if/else, switch, and three loop types (for, while, do-while). Methods let you package reusable logic, and method overloading allows multiple methods with the same name but different parameter lists. Strings are immutable character sequences with a rich set of built-in operations for searching, slicing, and converting.


Key Terms

Binary operation

An operation that takes two operands: addition (+), subtraction (-), multiplication (*), division (/).

Modulo operator (%)

Returns the remainder after integer division. 7 % 3 evaluates to 1. Think of it as "what is left over after dividing evenly."

Logical operators

Operators that evaluate boolean expressions: && (AND, both sides must be true), || (OR, at least one side must be true), ! (NOT, inverts the value).

Conditional statement

A construct that chooses which block of code to execute based on a boolean condition: if, else, and switch-case.

While loop

A loop that checks its condition before each iteration. If the condition is false from the start, the body never executes.

Do-while loop

A loop that executes its body at least once, then checks the condition. Useful when you need the first iteration to happen regardless.

For loop

A loop with a built-in counter: initialisation, condition, and update are all declared in the loop header. Ideal when you know in advance how many iterations you need.

Method overloading

Defining multiple methods with the same name but different parameter lists (different number or types of parameters). The compiler selects the correct version based on the arguments you pass. In simple terms, one method name, several signatures, and Java picks the right one automatically.

Method stub

A placeholder method with an empty body (or a minimal return statement), used during development so the rest of the code compiles while you work on other parts.

Local variable

A variable declared inside a method. It exists only while that method is executing and is discarded when the method returns.

Void method

A method that performs an action (like printing) but does not return a value. Its return type is declared as void.

Concatenation

Joining two strings together using the + operator. "Hello" + " World" produces "Hello World".

Sentinel bound

A loop termination strategy where the loop continues until a special input value (the sentinel) is encountered. The sentinel itself is not processed as data.


Core Content

Arithmetic and Logical Operations

  • Java's binary arithmetic operators: +, -, *, /.

  • Integer division truncates: 7 / 2 evaluates to 3, not 3.5. Use double operands if you need the decimal portion.

  • The modulo operator % gives the remainder: 10 % 3 is 1. Useful for checking divisibility, cycling through indices, and extracting digits.

  • Logical operators combine boolean expressions:

    • && short-circuits: if the left side is false, the right side is never evaluated.

    • || short-circuits: if the left side is true, the right side is never evaluated.

    • ! flips true to false and vice versa.

Control Flow

  • if / else: the most basic decision structure. The condition must evaluate to a boolean.

  • switch-case: selects among discrete values. Each case needs a break statement; without it, execution "falls through" to the next case.

  • Nested ifs: placing one if inside another for hierarchical decisions. Useful, but deep nesting hurts readability.

Loop Types

  • For loop: for (int i = 0; i < n; i++). Best when the number of iterations is known.

  • While loop: while (condition). Best when the number of iterations depends on a runtime condition.

  • Do-while loop: do { ... } while (condition);. Guarantees at least one execution of the body.

Loop Termination Strategies (Bound Types)

  • Counting bound: loop runs a set number of times (classic for loop with a counter).

  • Flag bound: loop runs until a boolean flag is set to true.

  • Limit bound: loop runs until a computed value reaches a threshold.

  • Sentinel bound: loop runs until a special input value (like -1 or "quit") is entered.

Methods

  • Methods are named blocks of code that perform a specific task. They improve reusability and readability.

  • A method signature consists of the method name and its parameter list.

  • Method overloading means having add(int a, int b) and add(double a, double b) in the same class. Java resolves which to call based on argument types.

  • Local variables live only inside the method where they are declared and cannot be accessed from outside.

  • Arguments are the values you pass into a method call; parameters are the variables declared in the method header that receive those values.

  • Void methods have a return type of void and do not return a value. Non-void methods must include a return statement with a value of the correct type.

String Handling

  • Strings are sequences of characters enclosed in double quotes: "Hello".

  • Strings are immutable and stored on the heap. Every modification creates a new String object.

  • Common string operations:

    • length() returns the character count.

    • charAt(index) returns the character at position index (0-based).

    • substring(start, end) extracts characters from start up to but not including end.

    • toLowerCase() / toUpperCase() return a new String with case changed.

    • replace(oldChar, newChar) returns a new String with all occurrences of oldChar swapped.

    • trim() removes leading and trailing whitespace.

    • Concatenation with + joins strings together.

Type Conversion with Strings

  • Integer.parseInt("42") converts a String to an int.

  • Integer.toString(42) converts an int to a String.

  • Double.parseDouble("3.14") converts a String to a double.

  • Double.toString(3.14) converts a double to a String.

Formatted Output

  • System.out.printf() uses format specifiers for controlled output:

    • %d for integers.

    • %f for floating-point numbers (use %.2f for two decimal places).

    • %s for strings.

    • %c for characters.

  • Width and alignment options let you produce neatly formatted tables and reports.


Formulas / Diagrams

For-loop anatomy:

for (initialisation; condition; update) {
    // body
}

Execution order: initialisation runs once, then the cycle is condition-check, body, update, repeat.

Substring indexing:

String s = "Hello";
s.substring(1, 4);  // returns "ell" (index 1 inclusive, index 4 exclusive)

Real-World Applications

Loops and conditionals are the backbone of every interactive program, from processing user input in a web form to iterating over sensor readings in an embedded system. Method overloading is a practical convenience in libraries you will use constantly: System.out.println() is overloaded to accept int, double, String, boolean, and other types. String parsing and conversion (parseInt, parseDouble) are essential whenever you read numeric input from a file or user interface, which is to say, in nearly every real application.


Common Misconceptions

  • Students often confuse the while and do-while loops. The key difference is that do-while always executes the body at least once. If the condition is false from the start, a while loop does nothing, but a do-while loop still runs the body once.

  • Forgetting break in a switch-case causes fall-through, where multiple cases execute unintentionally. This is a frequent source of bugs in early assignments.

  • Students assume substring(1, 4) returns four characters. The end parameter is exclusive, so it returns characters at indices 1, 2, and 3 only.

  • Integer division surprises students: 5 / 2 is 2 in Java, not 2.5. At least one operand must be a double to get a decimal result.


Why It Matters / Exam Flags

⚠️ Be able to trace through a for, while, or do-while loop by hand and state the final value of the loop variable.

⚠️ Know what happens when break is omitted from a switch-case.

⚠️ Understand method overloading: given two overloaded methods and a call, identify which version Java selects.

⚠️ substring() end index is exclusive. This appears in tracing questions regularly.

⚠️ Know the difference between Integer.parseInt() (String to int) and Integer.toString() (int to String).


Quick Self-Test

  1. True or false: A do-while loop always executes its body at least once.

  1. Fill in the blank: 10 % 4 evaluates to _______.

  1. True or false: Method overloading requires methods to have different return types.

  1. Fill in the blank: "Hello".charAt(1) returns _______.

  1. True or false: "abc".substring(0, 2) returns "abc".

Answers: 1. True. 2. 2. 3. False (it requires different parameter lists; return type alone is not enough). 4. 'e'. 5. False (it returns "ab", because the end index is exclusive).


Practice Q&A

Q: What is the output of System.out.println(7 / 2); and why?

A: The output is 3. Both operands are integers, so Java performs integer division and truncates the decimal portion.

Q: Explain the difference between a while loop and a do-while loop.

A: A while loop checks its condition before each iteration, so the body may never execute. A do-while loop executes the body first and checks the condition afterwards, guaranteeing at least one execution.

Q: Given add(int a, int b) and add(double a, double b), which method is called by add(3, 5)?

A: The add(int a, int b) version, because both arguments are integers and Java matches the most specific parameter types.

Q: What does "Java".substring(1, 3) return?

A: "av". The method extracts characters starting at index 1 up to, but not including, index 3.

Q: What is a sentinel value, and how is it used in a loop?

A: A sentinel value is a special input (e.g., -1 or "quit") that signals the loop to stop. The loop reads input repeatedly and terminates when it encounters the sentinel. The sentinel itself is not processed as regular data.


Connections to Other Topics

Control flow and loops are prerequisites for the arrays unit, where you iterate through collections of data using for loops and apply patterns like reduce and filter. Methods connect directly to the object-oriented programming unit, where they become the behaviours defined inside classes. String handling recurs in web development (HTML content manipulation) and in file I/O (parsing text files).


Related Terms / Search Tags

arithmetic operators, modulo, remainder, logical operators, AND, OR, NOT, short-circuit evaluation, if else, switch case, fall-through, break, for loop, while loop, do-while loop, counting loop, sentinel, flag bound, limit bound, method, method overloading, method stub, local variable, void method, arguments, parameters, String, immutable, concatenation, length, charAt, substring, toLowerCase, toUpperCase, replace, trim, parseInt, toString, parseDouble, printf, format specifiers, CS 101, Texas A&M