Computer Science I Exam 1 Comprehensive Notes

Exam Structure and Preparation

  • Scope of Content: The exam focuses on three primary areas:

    • Terms: Understanding the vocabulary of computer science and object-oriented programming.

    • Concepts: Grasping the underlying principles of software design.

    • Application: Demonstrating the ability to apply knowledge through coding and tracing.

  • Exam Modalities: The assessment is structured using various question types:

    • Matching: Associating terms with their correct definitions.

    • True/False: Verifying the correctness of statements.

    • Short Answer: Providing brief written explanations.

    • Code Tracing: Mentally or manually executing code to determine its output or state.

    • Coding: Writing valid Java code to solve prompted problems.

Introduction to Computer Science and Algorithms

  • Definition of Computer Science: Computer Science is a complex field, but for the purposes of this course, the focus is placed on understanding and developing software.

  • Problem-Solving: Developing software is inherently a process of problem-solving.

  • Algorithm:

    • Constructed as a sequence of instructions used to solve a specific problem.

  • Program:

    • A program serves as the implementation of an algorithm within a specific programming language.

  • Roles in Development: Professionals who create programs may be referred to as Programmers, Coders, or Software Engineers.

Object-Oriented Basics

  • Object:

    • A representation of a real-world entity or abstract concept.

    • Conforms strictly to the specification of its Class.

    • Components of an Object:

      • Data (Fields): The attributes or state of the object.

      • Behavior (Methods): The actions the object can perform.

    • Existence: Objects exist at runtime, which is when the program is actively running.

  • Class:

    • Defines the blueprint or structure of objects.

    • Specifies the available fields (data) and methods (behavior) that its objects will possess.

Fundamental Coding Terminology

  • Programming Language: The language used to specify a program's instructions.

  • Package: A hierarchical container used to group related classes together.

  • Field: Data stored by an object as defined by its class.

  • Comment: Portions of a program intended solely for human readers. Use of comments is ignored by the compiler.

    • In-line Comment: Created using // (e.g., //TODO Add the code here).

    • Multi-line/Javadoc Comment: Structured as: ```java /**

      • Draws a figure on the screen using the big turtle. *

      • @precondition none

      • @postcondition none */         ```

Environment and Tools

  • IDE (Integrated Development Environment):

    • An application providing comprehensive tools for software development.

    • Example: Eclipse.

    • Features: Includes tools for refactoring and project management.

  • Package Explorer: Provides a hierarchical overview of projects within the workspace.

  • Compiler/Interpreter: Converts human-readable source code into a form the computer can execute.

    • The compiler "compiles" programs written in a specific programming language.

  • Source Code: The files where the program is written in a programming language.

Syntax and Errors

  • Syntax Definition: The specific structure to which a program must adhere; the orderly system of linguistic elements.

  • Syntax Error: A failure to specify a portion of code as expected by the compiler or interpreter.

    • Common Examples:

      • Missing semicolons (;).

      • Mismatched curly braces ({}) or parentheses (()).

  • Bug: An error residing in the code.

  • Debugging: The systematic process of localizing and correcting bugs within the code.

Testing Terminology and Frameworks

  • Testing: The process of checking that a program is correct.

  • Test-Driven Development (TDD): A process where tests are written before the actual production code. The cycle follows:

    1. Create a new test (the test fails initially).

    2. Write the code.

    3. Run the tests.

    4. If tests pass? [Yes: Create new test; No: Debug].

  • Test Code vs. Production Code:

    • Test Code: Code whose sole responsibility is verifying that other program code works correctly (Unit Testing).

    • Production Code: Code that implements the actual behavior of the system and is distributed to clients (e.g., websites, desktop apps).

  • JUnit: A specific unit testing framework for Java that is built into the Eclipse IDE. JUnit tests are written in Java.

Java Class Structure

  • Class Components:

    • Package Declaration: Defines the namespace.

    • Imports: Brings in external classes.

    • Specification (Javadoc): Describes the purpose/conditions.

    • Header: Defines the class name and visibility.

    • Body: Surrounded by curly braces { }, containing the fields and methods.

  • Field Declaration:

    • Structure: Visibility Type Identifier; (e.g., private Turtle venus;).

    • Visibility: Typically private for encapsulation.

    • Type: Can be a primitive or an object (the type of an object is its class).

    • Naming Conventions: Must start with a lowercase letter, use camelCase, and use meaningful terms.

Methods and Constructors

  • Method Structure: Includes a specification (preconditions/postconditions), a header, and a body.

  • Method Header Components:

    • Visibility: public or private.

    • Return Type: The type of output (e.g., int, double, String). void indicates no value is returned.

    • Identifier: The name of the method (e.g., drawBigShape). Names should start with a lowercase letter.

    • Parameters: Enclosed in ( ), separated by commas. Parameters define input types and names (e.g., public int add(int a, int b)). Visibility keywords are NOT used for parameters.

  • Constructors:

    • A special method used to create and initialize objects.

    • No Return Type: Not even void.

    • Naming: Must be named exactly the same as the class.

    • Implicit Return: Implicitly returns an object of its class type.

    • Example from TurtleController:java public TurtleController() { this.bigTurtle = new Turtle(); }         

Variables and Assignment

  • Assignment Statement:

    • Format: LHS = RHS; (e.g., this.bigTurtle = new Turtle();).

    • The single equal sign = is the assignment operator.

    • Left-hand-side (LHS): Destination where information is stored.

    • Right-hand-side (RHS): The value or object to store.

  • The this Keyword:

    • A reference to the specific object upon which the current method was called.

  • Accessor Operator: The dot . used to access fields or call methods (e.g., this.venus.stepForward()).

  • Local Variables:

    • Variables created inside a method that do not exist outside that method's scope.

    • It is best practice to declare and initialize local variables simultaneously (e.g., double costOfBestThings = 0;).

Data Types and Literal Values

  • Literal: Represents a fixed value (e.g., "Bob", 22).

  • Primitive Types:

    • int: Whole numbers (e.g., −3-3, 3535).

    • double: Decimal numbers, more precise than float. We typically use double.

    • float: Decimal numbers requiring less space but offering less precision.

    • boolean: Captured logic with two values: true or false.

  • Strings:

    • A sequence of characters (letters, numbers, etc.) surrounded by double quotes (e.g., "2nd string!!!!").

Mathematical Expressions and Operators

  • Arithmetic Operators:

    • Addition: +

    • Subtraction: -

    • Multiplication: *

    • Division: /

    • Modulus: % (returns the remainder, e.g., 3%2=13 \% 2 = 1).

  • Order of Evaluation (PEMDAS):

    1. Parentheses ()

    2. Exponents

    3. Multiplication * and Division /

    4. Addition + and Subtraction -

    • If operators share the same precedence, evaluation proceeds from Left to Right.

  • Shorthand Operators:

    • count += 1; is same as count = count + 1;

    • count++; increments by 11.

    • count--; decrements by 11.

    • Others: result /= 2;, result *= 2;, result %= 2;.

Type Conversion and Casting

  • Implicit Conversion: Java automatically converts some types, such as int to double (e.g., double cost = 2; results in 2.02.0).

  • String Concatenation: Using + with a String converts other operands to Strings.

    • 2 + 2 + "2" →\rightarrow "42" (arithmetic happens first, then string concat).

    • 2 + "2" + 2 →\rightarrow "222" (first concat makes a string, then second concat).

  • Explicit Casting: Forcing conversion using (type).

    • (double)(3) / (double)(2) →\rightarrow 1.51.5.

    • (double)(3 / 2) →\rightarrow 1.01.0 (integer division happens first, resulting in 11, then cast to double).

    • Trancation: Casting double to int removes decimals: (int)(3.999999) returns 33.

    • Invalid Casts: (int)("something") results in an error.

Encapsulation: Getters and Setters

  • Setters (Mutators):

    • Methods that set the value of a field.

    • Requirement: Must have an @param tag to describe the parameter.

    • Control: Allows the class to control how a field is altered (e.g., ensuring age >= 0).

  • Getters (Accessors):

    • Methods that provide access to a field's value without altering the object's state.

    • Requirement: Must have an @return tag.

    • Utility: Supports hiding internal data types.

  • Derived Attribute: A getter that calculates a value on the fly rather than returning a stored field (e.g., getInitials() combining firstName and lastName).

Modular Design Principles

  • Single Responsibility Principle (SRP):

    • "A class should have only one reason to change."

    • Modules (classes or methods) should encapsulate distinct concerns (Separation of Concerns).

    • Example: A drawRow method should not also define how to draw an individual square.

  • Don't Repeat Yourself (DRY):

    • Repetitive structures should be refactored into private helper methods.

    • Distinct and crosscutting concerns should be separated.

Control Flow: Loops and Decisions

  • The for Loop Order of Execution:

    1. Initialization: Run once at the start (e.g., int i = 0).

    2. Condition: Checked before every body execution. If false, exit.

    3. Body: Statements inside the braces.

    4. Update: Statement run after the body (e.g., i++).

    5. Return to Step 2.

  • Counting Loop Pattern:

    • for(int i = 0; i < number_of_iterations; i++) repeats the body exactly number_of_iterations times.

  • If/Else Structure:

    • if body runs only if the condition is true.

    • else body runs only if the condition is false.

    • An else is always associated with its preceding if.

    • Nested If/Else: else if allows checking multiple exclusive conditions in sequence.

Questions & Discussion

  • Create a new object: This involves using the new keyword and a constructor (e.g., new Turtle()).

  • Declare/Add a field in the Troop class that will store a Monkey object:

    • Code: private Monkey nameOfVariable; inside the Troop class.

  • Implement the default constructor for the Troop class:java public Troop() { // Initialization code here } &nbsp;&nbsp;&nbsp;&nbsp;

  • Your code has a compilation error: This means the syntax is incorrect and the compiler cannot translate the source code into an executable form.

  • Simulation Exercise (Investment Growth):

    • Method accepts initialPrincipal and interestRate.

    • Loop for 1010 iterations (11 to 1010 years).

    • Logic: interest = currentPrincipal * interestRate; currentPrincipal += interest;.

    • Print metrics inside the loop.

  • Course Class Collaboration:

    • Fields to add: seatsAvailable (int), seatsTaken (int), courseName (String), isAsynchronous (boolean), instructor (Professor).

    • Formatted String output example: "CS101 has 5 seats left open."