COMP1010 Week 8

Command Line Interface, Terminal Utilities, and Text Editors

  • Significance of the Terminal in Modern Computing:

    • Contemporary Information and Communications Technology (ICT) workflows often insulate developers from the command line through graphical user interfaces and high-level search systems.

    • Command line navigation and core utilities like grep, find, and recursive directory traversals are essential in industry domains including cyber security, artificial intelligence, data science, and web development.

    • Foundational terminal workflows require understanding directory navigation, file inspection, command-line compilation, and script execution.

  • Standard Command-Line Shell Commands:

    • Directory Listing:

    • Unix/Linux/macOS: ls displays directory contents.

    • Windows (DOS): dir displays directory contents.

    • Present Working Directory:

    • pwd prints the full path of the current active working directory on Unix systems.

    • Changing Directories:

    • cd <directory_name> changes the working directory to the target path.

    • Pressing the Tab key provides command-line auto-completion; if multiple matching directories share a prefix, pressing Tab displays all possible completion candidates.

    • Screen Clearing:

    • Unix/Linux/macOS: clear resets and clears the terminal display.

    • Windows: cls clears the command screen.

    • File Content Display:

    • cat (concatenate) displays the text content of a specified file directly in the terminal interface (e.g., cat hello.java).

  • VI and VIM Text Editors:

    • vi and its enhanced version vim are keyboard-driven modal text editors standard on Unix-like environments.

    • Operating Modes:

    • Normal/Read Mode: The default navigation state when opening a file. Normal keystrokes trigger commands rather than entering text.

    • Insert/Edit Mode: Activated by specific command keys to insert or edit text:

      • Pressing i transitions to insert mode immediately at the current cursor position.

      • Pressing a enters append mode immediately after the cursor.

      • Pressing A (uppercase or Shift + a) moves the cursor directly to the end of the line and activates insert mode.

    • Line Deletion: Pressing dd in normal mode cuts or deletes the entire current line.

    • Saving and Exiting: Pressing the Esc key exits insert mode and returns to normal mode. Entering :wq writes (saves) the buffer changes to disk and quits the editor.

    • Advanced Capabilities:

    • Configurable auto-compilation triggers upon file saving.

    • Text snippet expansions for rapidly generating boilerplate constructs (such as public static void main).

    • Extensions are available inside integrated development environments (IDEs) such as Visual Studio Code.

  • Java Compilation and Bytecode Execution Lifecycle:

    • Source files with the .java extension contain human-readable high-level code.

    • Compiling via javac <Filename>.java converts the high-level source code into platform-independent assembly-level bytecode stored in a .class file.

    • Successful compilation emits no console output; compilation errors report missing delimiters, syntax faults, or invalid references.

    • Executing via java <Filename> invokes the Java Virtual Machine (JVM) to execute the bytecode in the .class file (omitting the .class extension).

    • If changes are made to a .java file, the program must be recompiled using javac; running java without recompilation continues to execute the previous, stale .class bytecode.

    • If the compiled .class binary is deleted, the JVM cannot run the program and throws an error indicating the class cannot be found.

    • Curriculum continuation: COMP2200 and COMP2310 (Digital Forensics) extend these terminal and system-level programming skills.

Object-Oriented Design and UML Class Modeling

  • Unified Modeling Language (UML) Class Diagram Structure:

    • Visual representation of an object-oriented class uses a three-tier rectangular box:

    1. Top Compartment: Class Name.

    2. Middle Compartment: Instance Variables (attributes describing the state of an object).

    3. Bottom Compartment: Instance Methods (behaviors operating on that state).

    • Visibility Modifiers in UML:

    • + denotes public access.

    • - denotes private access.

    • Advanced visibility scopes such as package-private and protected are introduced in COMP2000.

  • Domain-Specific Attribute Selection:

    • Instance variables must reflect the specific problem domain for which a system is built.

    • An attribute like hair color is essential in a salon management application but inappropriate or irrelevant in a general person model.

    • General domain attributes for individuals include personal identifiers, names, dates of birth, and physical addresses.

    • Identifiers (ID) serve as unique primary keys in database architectures (as detailed in COMP1350).

  • Decomposition of Complex Composite Types:

    • Deconstructing Names: Representing a name as a single String lacks structure. A dedicated Name class provides robust representation:

    • givenName (String)

    • familyName (String)

    • otherName (String), which generically accommodates middle names, maternal names, and multi-part cultural naming traditions (such as Sri Lankan bowler Chaminda Vaas).

    • Deconstructing Dates: Representing dates as composite types containing three primitive integers:

    • day (int)

    • month (int)

    • year (int)

    • Deconstructing Addresses: Real-world postal addresses require modular decomposition:

    • blockNumber (int)

    • unitNumber (int)

    • streetName (String)

    • streetType (String, e.g., Street, Avenue, Lane)

    • suburb (String)

    • postcode (int)

    • country (Country)

    • Suburbs and Postcodes Relationship: Multiple distinct suburbs can share an identical postcode, and a large suburb can span across multiple postcodes; hence, retaining separate fields for both is mandatory.

    • Enumerations (enum): Storing fields such as country as raw strings allows invalid arbitrary values (e.g., "Hallelujah" or "Champions League"). Defining an enum restricts values to a controlled drop-down list of predefined valid constants (studied in COMP2000).

    • Design Metric (Class Cohesion): Exceeding five instance variables in a single class is an indicator that the class carries too many responsibilities and should be split into smaller, modular composite classes.

  • Class Composition vs. Inheritance:

    • Composition ("Has-a" Relationship): Occurs when a composite class contains instance references pointing to objects of other classes (e.g., a Person has a Name, a Date of birth, and an Address). Represented in UML diagrams using a rhombus/diamond marker.

    • Inheritance ("Is-a" Relationship): Occurs when a child class extends a parent class (e.g., class Dog extends Animal), establishing a specialization hierarchy (studied in COMP2000).

    • Class composition forms the architectural basis for recursive data structures.

  • Constructor Mechanics and Argument Order:

    • In Java, constructor invocation enforces strict positional parameter order matching the constructor signature (e.g., parameter 1: Name, parameter 2: Date, parameter 3: Address).

    • Unlike Java, some alternative programming languages (such as Python) permit out-of-order parameter assignment via explicit keyword syntax (e.g., b=10, a=5).

    • Parameterized constructors explicitly initialize instance fields with passed values.

    • Default/placeholder constructors provide fallback baseline values when no parameters are passed:

    • Unix Epoch Date initialization: Day = 11, Month = 11, Year = 19701970. Unix systems store current time as the total elapsed seconds since this epoch timestamp, which eventually encounters an integer overflow.

    • The toString() method should be overridden in classes to prevent printing the default memory hash code, providing instead a structured canonical text representation of the object's contents.

Memory Diagrams, References, and Object Copying

  • Core Rules for Skills Lab Memory Diagrams:

    • References vs. Instances:

    • A variable with an outgoing arrow is a reference located on the stack.

    • A memory box with an incoming arrow is an object instance allocated on the heap.

    • Labels and Types:

    • The exact name of each instance variable must be clearly labeled (e.g., length, width, height).

    • The data type of each variable must be declared (e.g., int). Explicitly labeling a variable as primitive is unnecessary if standard primitive type markers (int) are provided.

    • UML visibility symbols (+, -) must not be included in memory diagrams.

    • Exclusions for Exam Constraints:

    • String objects are excluded from required memory diagrams because fully visualizing them requires drawing an internal char[] reference pointing to a discrete array instance containing individual character elements.

    • ArrayList collections are similarly excluded because visualizing them requires drawing internal heap array buffer references and backing array instances.

  • Memory Diagram Grading Criteria:

    • Fully correct diagrams (or diagrams containing only an obvious, minor omission such as omitting the = sign in length = 5) receive 100%100\% marks.

    • Diagrams with two minor errors receive 75%75\% to 80%80\% marks.

    • Diagrams displaying major structural errors (e.g., failing to distinguish references from instances) receive a maximum of 50%50\%.

    • Diagrams with minimal correctness omitting variable names, types, and instance labels receive a maximum of 20%20\% to 25%25\%.

    • Memory diagram questions represent approximately 15%15\% to 20%20\% of the total Skills Lab assessment.

  • Instance Copy vs. Reference Copy:

    • Reference Copy:

    • Created via direct assignment: Date d2 = d1;.

    • Copies only the memory address stored in reference d1d_1 into reference d2d_2.

    • Both references point to the exact same heap instance.

    • Mutating the instance through one reference (e.g., modifying d2.month from 88 to 99) mutates the shared instance; evaluating d1.month subsequently reflects the updated value (99).

    • Instance Copy (Clone):

    • Created by generating a distinct second instance via a copy constructor: Date d2 = new Date(d1);.

    • Implementation copies all primitive values from the source instance into the newly allocated target instance:

      • this.day = source.day;

      • this.month = source.month;

      • this.year = source.year;

    • References d1d_1 and d2d_2 point to completely independent instances in heap memory.

    • Mutating an attribute via d2 (such as changing its month to 99) leaves the state of the original instance referenced by d1d_1 untouched (88).

  • Visualizing Composite Classes in Memory:

    • When an instance contains references to other object instances (such as a House containing references r1 and r2 pointing to independent Room instances), the primary instance box contains named reference fields whose arrows point to the secondary heap instances.

    • Abstract trace examples with classes A (holding integer p), B (holding integer q), and C (holding references to instances of A and B) reinforce the mechanical dynamics of reference traversal and mutation independent of human intuition.

Java File Input/Output Architectures: Scanner vs. BufferedReader

  • Console and Standard Input (System.in):

    • System.in represents the standard input stream linked directly to the physical keyboard buffer.

    • Processing keyboard input requires wrapping an input parser class around System.in.

  • java.util.Scanner Characteristics:

    • Found in the utility package: import java.util.Scanner;.

    • Initialized using a File object for file-based processing: new Scanner(new File("filename.csv")).

    • Convenience Features:

    • Provides built-in type-parsing methods including next() (reads the next single whitespace-delimited token), nextLine() (reads the remaining line buffer up to ), nextInt(), and nextDouble().

    • Contains built-in validation methods like hasNextLine(), which checks whether additional unread records remain without throwing end-of-file null errors.

    • Allows overriding the default whitespace delimiter with custom delimiters using useDelimiter(",") to parse comma-separated value (CSV) text files natively.

    • Trade-Offs:

    • Parsing tokens automatically into primitive numeric types incurs considerable computational overhead.

    • High convenience comes at the cost of execution speed.

  • java.io.BufferedReader Characteristics:

    • Found in the input/output package: import java.io.BufferedReader;.

    • Initialized by wrapping around a FileReader instance: new BufferedReader(new FileReader("filename.csv")).

    • All input/output classes can be bulk-imported using wildcard syntax: import java.io.*;.

    • Performance and Limitations:

    • Operates at a lower architectural level, providing fast, stream-buffered text ingestion.

    • Does not contain primitive parsing helpers (such as nextInt() or nextDouble()).

    • Reads input exclusively as complete string lines via readLine().

    • Reaching the end of the file causes readLine() to return null.

    • Tokenization and numeric parsing must be manually implemented by the programmer.

    • Selection Criterion:

    • In competitive programming environments (such as ACM ICPC contests organized among universities including UTS, UNSW, University of Sydney, Macquarie University, and Western Sydney University), input processing speed is critical, mandating BufferedReader over Scanner (or lower-level languages like C/C++).

  • File Read Pointer Mechanics and Discarding Headers:

    • When a file stream opens, an internal read pointer is positioned at the first byte/character of the file.

    • Executing a line read (readLine() or nextLine()) consumes all characters sequentially until encountering the newline escape character (), advancing the pointer to the start of the next line.

    • Java permits calling a fruitful method and completely ignoring its return value without storing it in a variable.

    • To discard CSV header metadata, programmers execute an unassigned call to reader.readLine() or scanner.nextLine(), advancing the read pointer to record data on line two.

  • Exception Handling in File Streams:

    • File access introduces checked runtime exceptions:

    • FileNotFoundException: Thrown if the target file path does not exist on disk.

    • IOException: Thrown if reading from the file stream fails.

    • Handling Exceptions via throws Declarations:

    • A throws clause added to a method signature acts like passing a "hot potato," declining to catch the failure locally and delegating handling to the calling method.

    • If applied to public static void main, unhandled exceptions terminate program execution and dump the stack trace directly to the console.

Soccer League Data Processing Case Study

  • Domain Logic and League Rules:

    • Parsing real-world data from the English Premier League containing historical match data.

    • CSV columns include: Date, HomeTeam, AwayTeam, FTHG (Full Time Home Goals), and FTAG (Full Time Away Goals), followed by auxiliary match statistics (half-time scores, referee name, yellow and red cards).

    • Points System:

    • A victory awards 33 points to the winning team.

    • A defeat awards 00 points to the losing team.

    • A tie/draw awards 11 point to each team.

  • Handshake Algorithm Combinatorics:

    • In a league containing n=20n = 20 teams where every team plays every other team twice (home and away fixtures):

    • The number of unique single-match pairings is given by the handshake algorithm:       n(n−1)2=20×192=190\frac{n(n - 1)}{2} = \frac{20 \times 19}{2} = 190

    • Because each pairing competes twice, the total number of season matches is:       20×19=38020 \times 19 = 380

  • String Splitting and Number Parsing:

    • Date Parsing: Dates formatted as DD-MM-YYYY are tokenized using dateString.split("-"), yielding a three-element string array containing day, month, and year.

    • Integer Parsing: Integer.parseInt(string) parses numeric strings into primitive integer values (e.g., Integer.parseInt("1729") returns the integer 1729).

    • Exceptions on Invalid Parsing: Passing non-numeric tokens (such as "hallelujah") or floating-point formatted strings (such as "3.14159") to Integer.parseInt() triggers a runtime NumberFormatException.

  • Architectural Implementation of the Standings Tracker:

    • TeamStanding Class Model:

    • State fields: name (String) and points (int).

    • Constructor: TeamStanding(String name) initializes this.name = name and sets this.points = 0.

    • Methods: addPoints(int p) increments this.points += p, and toString() formats output as name + " " + points.

    • Core Algorithm for League Parsing:

    • Read match records line-by-line while skipping unwanted residual line tokens.

    • Track team standings dynamically within an ArrayList<TeamStanding> teams.

    • Implement a contains(teams, teamName) helper to safely verify whether a team already exists in the collection, performing checks for null lists or null team names before iterating.

    • If a home or away team is encountered for the first time, instantiate a new TeamStanding record with 00 initial points.

    • Compare home goals and away goals to award points:

      • If homeScore > awayScore, add 33 points to the home team.

      • Else if awayScore > homeScore, add 33 points to the away team.

      • Else, add 11 point to both teams.

    • Sorting and Design Critique:

    • Sorting an ArrayList of objects using Collections.sort() requires the target class to implement the Comparable interface and define compareTo().

    • Designing all match processing, team checks, and state updates directly inside the client driver class violates proper separation of responsibilities; match scoring belongs within the Match class or an overarching League controller.

    • Ingesting an entire large file into an unbounded memory block is unsafe and introduces memory leak risks.

Questions & Discussion

  • UML Class Attributes vs. Domain Context:

    • Audience Suggestion: Adding hair color as an instance variable for a Person class.

    • Response: Attribute relevance depends strictly on the application domain. Hair color is critical for a hair salon system, but unnecessary in general systems such as student records, immigration databases, or generic POS systems.

  • UML Visibility Symbols on Memory Diagrams:

    • Student Question: Is it necessary to include plus (+) or minus (-) visibility signs in Skills Lab memory diagrams?

    • Response: No. Plus and minus symbols represent UML visibility notation and must not be drawn in heap/stack memory diagrams.

  • Marking Leniency on Primitive Identifiers:

    • Student Question: Does the literal label primitive need to be drawn alongside primitive types?

    • Response: Writing int alongside the variable name and value is sufficient; it is universal knowledge that int is a primitive type.

  • Partial Marks Allocation for Memory Diagrams:

    • Student Question: Will partial marks be awarded for partially correct memory diagrams?

    • Response: Yes. Fully correct answers (or those with one minor cosmetic flaw) receive 100%100\%. Multiple minor errors receive 75%75\% to 80%80\%. Major structural errors (such as missing reference labels) receive a maximum of 50%50\%, while largely incomplete diagrams receive up to 25%25\%.

  • Handling File Reading Lines via if vs. Loops:

    • Student Question: Why can't we just use an if (scanner.hasNextLine()) block to read data?

    • Response: An if statement evaluates the condition only once, processing a single record. Iterating over the entire dataset across all 380380 matches requires wrapping the check inside a continuous while (scanner.hasNextLine()) loop.

  • Displaying Object References:

    • Student Question: What appears in console output when passing an object reference to System.out.println()?

    • Response: If the class implements toString(), the custom string representation is printed. If toString() is not implemented, Java outputs the class name followed by the default memory hash code.

  • Reading Full Files Directly into Memory:

    • Student Question: Can an entire file be ingested and stored directly in a single memory block string?

    • Response: While certain utilities exist, doing so is poor practice for arbitrary files. If an input file is exceptionally large, buffering the entire payload at once risks memory exhaustion and creates security vulnerabilities.

  • Skills Lab Assessment Rules and Policies:

    • Student Question/Concern: Clarification regarding exam attempts and time duration.

    • Response: Skills Lab exams run for approximately 100100 minutes. Students have up to three opportunities: Attempt 1 takes place during the teaching recess, Attempt 2 occurs in Week 9, and an additional attempt is granted to students who have sat at least one attempt and have an overall course mark below 50%50\%. Students who achieve their desired grade (e.g., 80%80\%, 90%90\%, or 100%100\%) do not need to resit, though unassessed challenge questions at the end of the paper allow high-achieving students to showcase skills for future Teaching Assistant (TA) recruitment.