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:
lsdisplays directory contents.Windows (DOS):
dirdisplays directory contents.Present Working Directory:
pwdprints 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
Tabkey provides command-line auto-completion; if multiple matching directories share a prefix, pressingTabdisplays all possible completion candidates.Screen Clearing:
Unix/Linux/macOS:
clearresets and clears the terminal display.Windows:
clsclears 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:
viand its enhanced versionvimare 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
itransitions to insert mode immediately at the current cursor position.Pressing
aenters append mode immediately after the cursor.Pressing
A(uppercase orShift+a) moves the cursor directly to the end of the line and activates insert mode.
Line Deletion: Pressing
ddin normal mode cuts or deletes the entire current line.Saving and Exiting: Pressing the
Esckey exits insert mode and returns to normal mode. Entering:wqwrites (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
.javaextension contain human-readable high-level code.Compiling via
javac <Filename>.javaconverts the high-level source code into platform-independent assembly-level bytecode stored in a.classfile.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.classfile (omitting the.classextension).If changes are made to a
.javafile, the program must be recompiled usingjavac; runningjavawithout recompilation continues to execute the previous, stale.classbytecode.If the compiled
.classbinary 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:
Top Compartment: Class Name.
Middle Compartment: Instance Variables (attributes describing the state of an object).
Bottom Compartment: Instance Methods (behaviors operating on that state).
Visibility Modifiers in UML:
+denotespublicaccess.-denotesprivateaccess.Advanced visibility scopes such as package-private and
protectedare 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
Stringlacks structure. A dedicatedNameclass 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 ascountryas raw strings allows invalid arbitrary values (e.g., "Hallelujah" or "Champions League"). Defining anenumrestricts 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
Personhas aName, aDateof birth, and anAddress). 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 = , Month = , Year = . 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 asprimitiveis unnecessary if standard primitive type markers (int) are provided.UML visibility symbols (
+,-) must not be included in memory diagrams.Exclusions for Exam Constraints:
Stringobjects are excluded from required memory diagrams because fully visualizing them requires drawing an internalchar[]reference pointing to a discrete array instance containing individual character elements.ArrayListcollections 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 inlength = 5) receive marks.Diagrams with two minor errors receive to marks.
Diagrams displaying major structural errors (e.g., failing to distinguish references from instances) receive a maximum of .
Diagrams with minimal correctness omitting variable names, types, and instance labels receive a maximum of to .
Memory diagram questions represent approximately to 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 into reference .
Both references point to the exact same heap instance.
Mutating the instance through one reference (e.g., modifying
d2.monthfrom to ) mutates the shared instance; evaluatingd1.monthsubsequently reflects the updated value ().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 and point to completely independent instances in heap memory.
Mutating an attribute via
d2(such as changing its month to ) leaves the state of the original instance referenced by untouched ().
Visualizing Composite Classes in Memory:
When an instance contains references to other object instances (such as a
Housecontaining referencesr1andr2pointing to independentRoominstances), the primary instance box contains named reference fields whose arrows point to the secondary heap instances.Abstract trace examples with classes
A(holding integerp),B(holding integerq), andC(holding references to instances ofAandB) 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.inrepresents 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.ScannerCharacteristics:Found in the utility package:
import java.util.Scanner;.Initialized using a
Fileobject 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(), andnextDouble().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.BufferedReaderCharacteristics:Found in the input/output package:
import java.io.BufferedReader;.Initialized by wrapping around a
FileReaderinstance: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()ornextDouble()).Reads input exclusively as complete string lines via
readLine().Reaching the end of the file causes
readLine()to returnnull.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
BufferedReaderoverScanner(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()ornextLine()) 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()orscanner.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
throwsDeclarations:A
throwsclause 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), andFTAG(Full Time Away Goals), followed by auxiliary match statistics (half-time scores, referee name, yellow and red cards).Points System:
A victory awards points to the winning team.
A defeat awards points to the losing team.
A tie/draw awards point to each team.
Handshake Algorithm Combinatorics:
In a league containing 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:
Because each pairing competes twice, the total number of season matches is:
String Splitting and Number Parsing:
Date Parsing: Dates formatted as
DD-MM-YYYYare tokenized usingdateString.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 integer1729).Exceptions on Invalid Parsing: Passing non-numeric tokens (such as
"hallelujah") or floating-point formatted strings (such as"3.14159") toInteger.parseInt()triggers a runtimeNumberFormatException.
Architectural Implementation of the Standings Tracker:
TeamStandingClass Model:State fields:
name(String) andpoints(int).Constructor:
TeamStanding(String name)initializesthis.name = nameand setsthis.points = 0.Methods:
addPoints(int p)incrementsthis.points += p, andtoString()formats output asname + " " + 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
TeamStandingrecord with initial points.Compare home goals and away goals to award points:
If
homeScore > awayScore, add points to the home team.Else if
awayScore > homeScore, add points to the away team.Else, add point to both teams.
Sorting and Design Critique:
Sorting an
ArrayListof objects usingCollections.sort()requires the target class to implement theComparableinterface and definecompareTo().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
Matchclass or an overarchingLeaguecontroller.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
Personclass.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
primitiveneed to be drawn alongside primitive types?Response: Writing
intalongside the variable name and value is sufficient; it is universal knowledge thatintis 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 . Multiple minor errors receive to . Major structural errors (such as missing reference labels) receive a maximum of , while largely incomplete diagrams receive up to .
Handling File Reading Lines via
ifvs. Loops:Student Question: Why can't we just use an
if (scanner.hasNextLine())block to read data?Response: An
ifstatement evaluates the condition only once, processing a single record. Iterating over the entire dataset across all matches requires wrapping the check inside a continuouswhile (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. IftoString()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 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 . Students who achieve their desired grade (e.g., , , or ) 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.