CS 164: Introduction to Java Programming & Computational Thinking

Course Administrative Details & Schedule

  • Course Identification:

    • Course Code: CS 164 / CS 1

    • Course Title: Computational Thinking with Java

    • Institution: Colorado State University

  • Weekly Schedule & Key Milestones:

    • Thursday: Lab 1 session.

    • Friday: Required readings covering Method Basics, Parameters, and Returning Values.

    • Student Response System: Join iClicker class via https://join.iclicker.com/WIPE.

  • Required Student Action Items (TODO):

    • Complete Microsoft Teams workspace setup.

    • Complete Syllabus Quiz.

    • Complete Lab Quiz.

    • Begin Programming Assignment 1 (PA 1).

Java Language Fundamentals & Architecture

  • Core Definition:

    • Java is an object-oriented, compiled programming language originally created by Sun Microsystems and currently maintained by Oracle Corporation.

    • Object-Oriented paradigm: Uses classes to define structural blueprints and behaviors for object instances.

  • Compiled vs. Interpreted Languages:

    • Compiled Languages (Java): Source code must be processed by a compiler prior to execution by a virtual machine or host system.

    • Interpreted Languages (Python): Source code is parsed and executed line-by-line at runtime. Unexecuted lines containing syntax or runtime errors will not throw errors until execution reaches them.

  • Write Once, Run Anywhere (WORA):

    • Java achieves hardware and operating system independence through the Java Virtual Machine (JVM).

    • Source code is compiled into platform-independent intermediate byte code.

    • Execution Rule: Compiled Java byte code can run on any device with a Java Runtime Environment (JRE) or Java Development Kit (JDK) installed, provided the JRE/JDK version is equal to or newer than the compiler version.

    • Multi-Platform Deployment Example: Code compiled on macOS can be executed on Windows or ARM-based systems like Raspberry Pi without recompilation, provided valid JVM installations exist on target platforms.

Java JVM Platform Independence Diagram

Java Syntax Rules & File Structure

  • File Naming Conventions:

    • Java source code is saved in files bearing the .java file extension.

    • The source file must contain a public class declaration whose name exactly matches the filename.

    • Example: File Example.java must define public class Example.

  • Case Sensitivity:

    • Java is strictly case-sensitive.

    • Identifiers such as Example (capitalized) and example (lowercase) are distinct tokens.

  • Basic Structure Example:

  public class Example {
      public static void main(String[] args) {
          System.out.print("Hello World");
      }
  }
  ```

# Java Data Types & Memory Allocation

* **Strong vs. Weak Data Typing:**
  * **Weak/Dynamic Typing (Python):** Variables can reassign data types dynamically at runtime (e.g., `data = 7` followed by `data = "7"`).
  * **Strong/Static Typing (Java):** Variables are permanently bound to a single declared data type at compile time.
  * Attempting to store incompatible data throws a compilation error: `Type mismatch: cannot convert from String to int`.
  * Memory Allocation: Declaring a strong type explicitly informs the Java compiler how much memory space to allocate for variable storage.

* **Java Primitive Data Types:**
  * `byte`: 8-bit8\text{-bit} signed integer.
  * `short`: 16-bit16\text{-bit} signed integer.
  * `int`: 32-bit32\text{-bit} signed integer (default for integer literals).
  * `long`: 64-bit64\text{-bit} signed integer; denoted by trailing `l` or `L` suffix (e.g., `123456789l`).
  * `float`: 32-bit32\text{-bit} single-precision floating-point; denoted by trailing `f` or `F` suffix (e.g., `32.5f`).
  * `double`: 64-bit64\text{-bit} double-precision floating-point (default for floating-point literals).
  * `boolean`: Truth value represented strictly by `true` or `false`.
  * `char`: 16-bit16\text{-bit} single Unicode character enclosed in single quotes (e.g., `'a'`, `'7'`).

* **String Types in Java:**
  * `String` is NOT a primitive type in Java; it is a reference/object type.
  * String literals are defined strictly using double quotes (`"`).
  * **String Literal:** `String lit = "This is a String Literal";`
  * **Constructed String:** `String obj = new String("This is a constructed String");`

# Object Concepts & Instantiation

* **Definition of Objects:**
  * Objects represent instances defined by a `Class` blueprint.
  * Objects possess stored attributes/variables and execution methods.
  * Objects are instantiated using the `new` operator:
    * `String s = new String();`
    * `Scanner scan = new Scanner(System.in);`
  * Uninitialized object variables default to `null`.

# Variables, Declaration, & Initialization

* **Variable Identifiers:**
  * Must be descriptive names (e.g., `puppyCounter` preferred over `x`).
  * Cannot be reserved keywords.
  * Cannot begin with numbers or special characters other than `_` or `$`.
  * Follows `camelCase` naming convention (first word lowercase, subsequent words capitalized).

* **Declaration vs. Initialization:**
  * **Declaration:** Reserves memory space and defines identifier type (`<TYPE> <IDENTIFIER>;`).
  * Multiple declarations on one line: `int x, y, z;`
  * **Initialization:** First assignment of value to declared variable (`int x = 7;`).
  * Declarations without assignment: primitives implicitly evaluate to zero values (00 or 0.00.0), while object reference types evaluate to `null`.

* **Assignment Rules:**
  * Assigned using standard assignment operator `=`.
  * Widening conversion example: `double my_value = a;` converts integer `5` into `5.0` automatically.
  * Invalid assignment example: `int _int = 10.5;` fails compilation due to double-to-int type incompatibility without casting.

# Console Output & Standard Printing

* **Standard Print Stream (`System.out`):**
  * Standard console print destination in Java.

* **Printing Variations:**
  * `System.out.println()`: Outputs string/data to console and appends a line break cursor return.
  * `System.out.print()`: Outputs string/data to console while maintaining cursor position on the active line.
  * String Concatenation: Operator `+` concatenates strings and implicitly converts adjacent non-string data types to text representation.

# Arithmetic, Relational, & Modulo Operators

* **Standard Operators:**
  * Addition: `+`, `+=`
  * Subtraction: `-`, `-=`
  * Multiplication: `*`, `*=`
  * Division: `/`, `/=`
  * Modulo: `%`, `%=`
  * Equality & Relational: `==`, `>`, `>=`, `<`, `<=`

* **Integer Division:**
  * Division between two integer primitive types truncates all decimal fractional values without rounding.
  * Example: 5/2=25 / 2 = 2
  * Example: 5/6=05 / 6 = 0
  * Example: 10/3=310 / 3 = 3
  * Floating-point promotion: If either operand is floating-point (`double`/`float`), calculation yields floating-point precision (9/10.0=0.99 / 10.0 = 0.9).

* **Modulo Operator (`%`):**
  * Evaluates integer remainder following division.
  * Division example: 250/6=41250 / 6 = 41
  * Remainder calculation: 250(41×6)=4250 - (41 \times 6) = 4
  * Modulo expression: 250(mod6)=4250 \pmod 6 = 4

![Long Division of 250 divided by 6 showing quotient 41 and remainder 4](https://assets.knowt.com/pdf-flow-prod/21802ea0-4a84-4143-a4ca-c889f4c56777-figures/9.jpg)

# Increment, Decrement, & Compound Operators

* **Compound Assignment:**
  * `value += 10` is equivalent to `value = value + 10`.

* **Prefix vs. Postfix Evaluation:**
  * **Prefix (`++value`, `--value`):** Increments/decrements variable value *before* expression evaluation.
  * **Postfix (`value++`, `value--`):** Evaluates active expression using current variable value *first*, then increments/decrements variable afterward.

* **Operation Step Execution Trace:**

java int value = 100; value++; // value becomes 101 value += 10; // value becomes 111 value /= 10; // value becomes 11 (111 / 10 truncated) value *= 2; // value becomes 22 --value; // value becomes 21 value %= 20; // value becomes 1 (21 % 20)   ```

Program Scope & Execution Structure

  • Main Execution Entry Point:

    • Every executable Java program requires a standard main method signature: java public static void main(String[] args) { // Executable program logic } &nbsp;&nbsp;&nbsp;&nbsp;

  • Block Scoping:

    • Java does NOT use indentation or whitespace to define scope.

    • Scope blocks are defined exclusively by opening and closing curly braces {}.

Practice Problems & Analytical Walkthroughs

  • Practice Problem 1: Primitive Data Types Classification

    • Question: Which list contains only Java primitive data types?

    • Options:

    • A. int, double, boolean, char

    • B. String, int, double, boolean

    • C. Integer, float, boolean, char

    • D. int, String, Character, Double

    • Correct Answer: Option A.

    • Explanation: String, Integer, Character, and Double are class/object reference types, not primitive types.

  • Practice Problem 2: Variable Reassignment & Swapping

    • Scenario 1:

    int A = 5;
    int B = 2;
    int C = 10;
    A = B;
    B = C;
    &nbsp;&nbsp;&nbsp;&nbsp;```
    * Result: A=2A = 2, B=10B = 10, C=10C = 10
    * Scenario 2:
    

    java int A = 10; int B = 20; A = B; B = A;     ```

    • Result: A=20A = 20, B=20B = 20 (value of original AA overwritten in step 1).

    • Variable Swapping Logic: Swapping values without loss requires introducing a temporary third variable: java int temp = A; A = B; B = temp; &nbsp;&nbsp;&nbsp;&nbsp;

  • Practice Problem 3: Modulo & Integer Arithmetic Output

    • Code: java public class Main { public static void main(String[] args) { int a = 17; int b = 5; System.out.print(a / b + "," + a % b + "," + b % a + "," + -17 % 5); } } &nbsp;&nbsp;&nbsp;&nbsp;

    • Step-by-Step Evaluation:

    • a / b = 17/5=317 / 5 = 3

    • a % b = 17(mod5)=217 \pmod 5 = 2

    • b % a = 5(mod17)=55 \pmod{17} = 5

    • -17 % 5 = 17(mod5)=2-17 \pmod 5 = -2 (sign of remainder follows dividend)

    • Printed Output: 3,2,5,-2

  • Practice Problem 4: Prefix Increment Evaluation

    • Code: java int value = 3; System.out.print(++value + 4); &nbsp;&nbsp;&nbsp;&nbsp;

    • Evaluation: ++value increments value to 44 prior to addition (4+4=84 + 4 = 8).

    • Printed Output: 8

  • Practice Problem 5: Postfix vs. Prefix Multiplication

    • Code Snippet 1:

    int value = 5;
    System.out.print(value-- * 2);
    System.out.print(value);
    &nbsp;&nbsp;&nbsp;&nbsp;```
    * `value-- * 2` uses 5×2=105 \times 2 = 10, then decrements `value` to 44.
    * Printed Output: `104`
    * Code Snippet 2:
    

    java int value = 5; System.out.print(--value * 2);     ```

    • --value * 2 decrements value to 44 first, then evaluates 4×2=84 \times 2 = 8.

    • Printed Output: 8

  • Practice Problem 6: Program Execution & Print Formatting Analysis

    • Code: java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); System.out.print("My Name is"); String s = "Logan Seabolt"; System.out.println(s); } } &nbsp;&nbsp;&nbsp;&nbsp;

    • Program Output: text Hello World My Name isLogan Seabolt &nbsp;&nbsp;&nbsp;&nbsp;

    • Identified Bug: Missing trailing space inside "My Name is" literal causes concatenation without spacing (My Name isLogan Seabolt).