edusolum

📖 Unit 1: Using Objects and Methods

# UNIT 1: USING OBJECTS AND METHODS

# 1. INTRODUCTION

Welcome to the world of Computer Science! At its core, programming is not just about typing lines of text into a computer; it is the art of problem-solving. Imagine you are tasked with designing a system for a self-driving car, a high-frequency trading platform, or a simple mobile game. All these complex systems rely on the same fundamental building blocks: Algorithms and Objects.

In this unit, we will explore the foundational elements of the Java programming language. We begin by understanding how to give instructions to a computer through algorithms and how the computer translates our human-readable code into something it can execute. We will then dive into the way data is stored using variables and how we can manipulate that data using mathematical expressions. Finally, we will introduce the "Object-Oriented" nature of Java, where we learn to use pre-written blueprints (Classes) to create powerful tools (Objects) that can perform complex tasks with just a few lines of code. By the end of this chapter, you will be able to write programs that interact with users, perform precise calculations, and manipulate text—all while maintaining the rigorous logic required for college-level software development.


# 2. ALL KEY CONCEPTS, TERMS, FOUNDATIONAL KNOWLEDGE, and PRINCIPLES

# 2.1 Programming Fundamentals

  • Algorithm: A step-by-step procedure or formula for solving a problem.
  • Sequencing: The execution of program statements one after another in the order they are written.
  • Compiler: A program that translates source code (Java) into machine-understandable bytecode.
  • Syntax Error: A "grammar" mistake in the code that prevents the compiler from running the program.
  • Logic Error: The program runs but produces the wrong output because the underlying logic is flawed.
  • Run-time Error: An error that occurs while the program is executing, often causing it to "crash."
  • Exception: A specific type of run-time error (e.g., ArithmeticException).

# 2.2 Data and Variables

  • Primitive Type: Basic data types that store raw values. In AP CSA, these are int, double, and boolean.
  • Reference Type: A data type that stores the memory address (reference) of an object.
  • Variable: A named storage location in memory for a value.
  • Assignment: Using the = operator to store a value in a variable.
  • Casting: Explicitly converting a value from one data type to another (e.g., (int)3.5).

# 2.3 Operations and Output

  • String Literal: A sequence of characters enclosed in double quotes, like "Hello".
  • Escape Sequence: Special characters starting with a backslash (e.g., \n) to represent non-printable or reserved characters.
  • Modulus (%): An operator that returns the remainder of a division.
  • Compound Assignment: Shorthand operators like += or *= that perform an operation and assign the result.

# 2.4 Objects and Methods

  • Class: A blueprint or template for creating objects.
  • Object: An instance of a class that contains attributes and behaviors.
  • Method: A named block of code that performs a specific task.
  • Constructor: A special method called when an object is created using the new keyword.
  • Parameter: A variable in a method header that receives data.
  • Argument: The actual value passed to a method during a call.
  • Static (Class) Method: A method belonging to the class itself, called using the class name.
  • Instance Method: A method called on a specific object (instance).
  • Null: A special value indicating that a reference variable does not point to any object.
  • Immutable: An object whose state cannot be changed after it is created (e.g., String).

# 3. IN-DEPTH EXPLANATION of EVERY CONCEPT and PRINCIPLE

# 3.1 Algorithms, Programming & Compilers

An algorithm is a precise set of instructions. In Java, we implement algorithms through sequencing. This means the computer starts at the first line of the main method and executes each line in order.

When you write code in an IDE (Integrated Development Environment), it must be compiled. The compiler checks for Syntax Errors—violations of Java's rules, such as a missing semicolon or a misspelled keyword. If syntax is perfect, the code runs. However, it may still have:

  1. Logic Errors: You meant to add two numbers but used the minus sign instead. The computer does what you told it to do, not what you intended.
  2. Run-time Errors (Exceptions): The program encounters a situation it cannot handle, such as dividing by zero ($x / 0$).

# 3.2 Variables and Data Types

Java is a "strongly typed" language. You must declare a variable's type before using it.

  • int: Stores integers (whole numbers) like $-5, 0, 42$.
  • double: Stores decimal numbers like $3.14159$ or $-0.001$.
  • boolean: Stores logical values: true or false.

Variables of Reference Types do not hold the actual data; they hold a "pointer" or memory address to where the object is stored.

# 3.3 Expressions and Output

We use System.out.print() to display text. System.out.println() does the same but moves the cursor to a new line afterward.

Escape Sequences allow us to print special characters:

  • \" : Prints a double quote.
  • \\ : Prints a backslash.
  • \n : Moves to a new line.

Arithmetic Rules:

  1. Integer Division: When dividing two ints, the decimal portion is truncated (dropped).
    • Example: $7 / 3 = 2$.
  2. Double Arithmetic: If at least one operand is a double, the result is a double.
    • Example: $7 / 3.0 = 2.3333333333333335$.
  3. Operator Precedence: Parentheses $\rightarrow$ Multiplication/Division/Modulus $\rightarrow$ Addition/Subtraction.

# 3.4 Assignment and Input

The assignment operator = evaluates the right side first, then stores the result in the variable on the left.

int x = 10 + 5; // x becomes 15

To get input, we use the Scanner class from the java.util package.

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

# 3.5 Casting and Range of Variables

Casting is the manual conversion of types.

  • (double) 5 becomes 5.0.
  • (int) 5.9 becomes 5 (truncation).

Rounding Rule: To round a positive double $x$ to the nearest integer:
$$rounded = (int)(x + 0.5)$$

Integer Limits:
An int is 32-bit.

  • Integer.MIN_VALUE = $-2^{31}$
  • Integer.MAX_VALUE = $2^{31} - 1$
    If you add 1 to Integer.MAX_VALUE, you get Integer Overflow, and the value wraps around to Integer.MIN_VALUE.

# 3.6 Compound Assignment

Shorthand makes code cleaner:

Operator Equivalent to
x += 5 x = x + 5
x -= 2 x = x - 2
x *= 3 x = x * 3
x /= 4 x = x / 4
x %= 2 x = x % 2
x++ x = x + 1
x-- x = x - 1

# 3.7 APIs and Libraries

A Library is a collection of pre-written classes. The API (Application Programming Interface) is the manual that tells you how to use them. For example, java.lang is a package included automatically that contains the Math and String classes.

# 3.8 Documentation

  • // : Single-line comment.
  • /* ... */ : Multi-line block comment.
  • /** ... */ : Javadoc comment for documentation.

Preconditions: What must be true before calling a method (e.g., "radius must be positive").
Postconditions: What the method guarantees after it finishes (e.g., "returns the area of the circle").

# 3.9 Method Signatures and Calls

A Method Signature is defined by: methodName(parameterTypes).

  • Parameters: The placeholders in the method definition.
  • Arguments: The actual values passed during the call.
    Java uses Call by Value, meaning the method receives a copy of the argument's value.

# 3.10 & 3.11 The Math Class

The Math class contains static methods. You don't need to create a Math object; you just call them using Math.methodName().

Method Return Type Description
Math.abs(x) int or double Absolute value $
Math.pow(b, e) double $b^e$
Math.sqrt(x) double $\sqrt{x}$
Math.random() double Returns $r$ where $0.0 \le r < 1.0$

Random Integer Formula:
To get a random integer in the range $[low, high]$:
$$result = (int)(Math.random() * (high - low + 1) + low)$$

# 3.12, 3.13, & 3.14 Objects and Constructors

An object is an instance of a class.

  1. Declaration: Rectangle box; (Creates a reference variable, currently null).
  2. Instantiation: box = new Rectangle(5, 10); (Calls the Constructor to allocate memory and initialize attributes).

Instance Methods are called on the object: box.getArea();. If you call a method on a null reference, you get a NullPointerException.

# 3.15 String Manipulation

String objects are sequences of characters. They are immutable.

  • Index: Starts at $0$ and ends at $length - 1$.

Essential String Methods:

Method Description
int length() Number of characters.
String substring(int from, int to) Returns string from from to to-1.
String substring(int from) Returns string from from to the end.
int indexOf(String str) Index of first occurrence of str, or -1.
boolean equals(String other) Checks if contents are identical.
int compareTo(String other) $0$ if equal, negative if this < other, positive if this > other.

# 4. EXAMPLES

# Example 1: Integer Division Truncation

int result = 10 / 4;
System.out.println(result); 

Explanation: $10 / 4 = 2.5$. Since both are int, the result is truncated to 2.

# Example 2: Mixing Types (Promotion)

double result = 10 / 4.0;

Explanation: Since 4.0 is a double, the integer 10 is promoted to 10.0. Result is $2.5$.

# Example 3: Modulus Operator

int remainder = 17 % 5;

Explanation: $17 = (3 \times 5) + 2$. The remainder is 2.

# Example 4: Modulus with Negative Numbers

int result = -15 % 4;

Explanation: Java's modulus maintains the sign of the dividend. $-15 / 4 = -3$ remainder $-3$. Result is -3.

# Example 5: Operator Precedence

int val = 5 + 10 * 2 / 5;

Calculation:

  1. $10 * 2 = 20$
  2. $20 / 5 = 4$
  3. $5 + 4 = 9$
    Result: 9.

# Example 6: Double Round-off Error

System.out.println(0.1 + 0.2);

Explanation: Because doubles are stored in binary, simple decimals might result in values like 0.30000000000000004.

# Example 7: Integer Overflow

int big = Integer.MAX_VALUE + 1;
System.out.println(big);

Explanation: $2,147,483,647 + 1$ becomes $-2,147,483,648$ (the MIN_VALUE).

# Example 8: Manual Casting

double money = 99.99;
int dollars = (int) money;

Explanation: dollars becomes 99. The .99 is deleted, not rounded.

# Example 9: Rounding Calculation

double score = 85.7;
int roundedScore = (int)(score + 0.5);

Calculation: $85.7 + 0.5 = 86.2 \rightarrow (int)86.2 = 86$.

# Example 10: The Scanner Class

Scanner kb = new Scanner(System.in);
System.out.print("Enter radius: ");
double r = kb.nextDouble();
double area = Math.PI * Math.pow(r, 2);

Explanation: Reads a double from the user and calculates $\pi r^2$.

# Example 11: String Concatenation

String s = "Score: " + 10 + 5;

Explanation: Evaluation is left-to-right. "Score: " + 10 becomes "Score: 10". Then "Score: 10" + 5 becomes "Score: 105".

# Example 12: String Concatenation with Parentheses

String s = "Score: " + (10 + 5);

Explanation: Parentheses first. $10+5=15$. Result: "Score: 15".

# Example 13: Escape Sequences

System.out.println("Path: C:\\Users\\Name\n\"Hello\"");

Output:

Path: C:\Users\Name
"Hello"

# Example 14: Math.abs()

int diff = Math.abs(10 - 25); 

Result: $|-15| = 15$.

# Example 15: Math.sqrt() and casting

int side = (int) Math.sqrt(25);

Result: Math.sqrt(25) returns 5.0 (double), which is cast to the int 5.

# Example 16: Math.random() Range $[0, 10]$

int rand = (int)(Math.random() * 11);

Explanation: Math.random() is $[0.0, 1.0)$. Multiplying by 11 gives $[0.0, 11.0)$. Casting to int gives ${0, 1, 2, ..., 10}$.

# Example 17: Random Die Roll $[1, 6]$

int die = (int)(Math.random() * 6) + 1;

Calculation: $(int)([0.0, 6.0)) + 1 \rightarrow {0..5} + 1 \rightarrow {1..6}$.

# Example 18: String length()

String name = "Java";
int len = name.length();

Result: 4.

# Example 19: String substring(from, to)

String fruit = "Pineapple";
String sub = fruit.substring(0, 4);

Result: "Pine". (Indices 0, 1, 2, 3 included; 4 is excluded).

# Example 20: String substring(from)

String sub = "Pineapple".substring(4);

Result: "apple". (From index 4 to the end).

# Example 21: String indexOf()

int idx = "Mississippi".indexOf("iss");

Result: 1. (It finds the first occurrence).

# Example 22: String indexOf() Not Found

int idx = "Java".indexOf("python");

Result: -1.

# Example 23: String equals() vs ==

String s1 = new String("Hi");
String s2 = new String("Hi");
boolean b1 = (s1 == s2);      // false (different memory addresses)
boolean b2 = s1.equals(s2);   // true (same text)

# Example 24: compareTo() Basics

int res = "Apple".compareTo("Banana");

Result: Negative value (since "Apple" comes before "Banana" alphabetically).

# Example 25: compareTo() Equality

int res = "Cat".compareTo("Cat");

Result: 0.

# Example 26: Compound Assignment Shorthand

int x = 10;
x += 5; // 15
x /= 3; // 5

# Example 27: Increment Operator

int count = 0;
count++; 
count++; 

Result: count is 2.

# Example 28: Method Overloading

// In some class
public void printInfo(String name) { ... }
public void printInfo(int age) { ... }

Explanation: These methods have the same name but different signatures (different parameter types).

# Example 29: NullPointerException

String s = null;
int len = s.length(); // CRASH!

# Example 30: Calling a static method

double root = Math.sqrt(144);

Explanation: Called via the Class Name Math, not an object.

# Example 31: ArithmeticException

int x = 5 / 0; // CRASH!

# Example 32: Preconditions

/**
 * @param x must be non-negative (Precondition)
 */
public void calculateSqrt(double x) { ... }

# Example 33: Immutable Strings

String s = "Hello";
s.toUpperCase(); 
System.out.println(s);

Explanation: Prints "Hello". toUpperCase() returns a new string; it doesn't change s. To change it, you must assign: s = s.toUpperCase();.

# Example 34: Reference Assignment

String a = "Blue";
String b = a;
a = "Red";
System.out.println(b);

Explanation: Prints "Blue". b was pointing to the original object. Changing a to point to a new object "Red" doesn't change where b points.

# Example 35: Complex Expression with Casting

double val = (double) (1/4) * 10;

Explanation: 1/4 happens first inside parentheses, resulting in 0. (double)0 is 0.0. 0.0 * 10 is 0.0. Correct way: (double)1 / 4 * 10 which is 2.5.

Certificate terms & implications

Course Mastery Certificates require an active Unlimited subscription at the time of generation and 100% course completion. They recognise learning content completion only — not an accredited qualification, licence, or professional credential unless explicitly stated. edusolum may modify eligibility, design, and issuance requirements per its Terms of Service.