Csa notes

Csa notes ( im cooked )

Ch 1: Introduction

Unicode

The computer stores letters, numbers, and punctuation as binary data (0's and 1's) using standard codes like ASCII and Unicode to ensure compatibility across different systems.

ASCII:

ASCII encodes each character as an 8-bit pattern, allowing for 256 different characters.

It includes characters like digits (0-9), uppercase letters (A-Z), lowercase letters (a-z), and special characters.

ASCII is sufficient for English but not for languages with more characters, like Chinese.

Unicode:

Unicode is a 16-bit code, providing 65,536 possible characters, covering all known languages.

The first 256 Unicode characters are the same as ASCII, ensuring backward compatibility.

Non-keyboard characters in Unicode can be represented with escape sequences.

General:

In both ASCII and Unicode, digits, uppercase letters, and lowercase letters are stored in a consecutive and ordered manner.

Text files use these codes to store all characters.

History of Programming Languages

Programming languages have evolved through three generations: Machine Languages, Assembly Languages, and High-Level Languages.

### Machine Languages (First Generation):

- The first programming languages, still the only ones understood by computers.

- Use only 0's and 1's, making them difficult for humans.

- Each computer model has its own unique machine language, so programs are not portable.

- Programs are lengthy and hard to write.

### Assembly Languages (Second Generation):

- More human-readable, using names instead of numbers for operations and memory locations.

- Requires an assembler to translate assembly language into machine language.

- Programs are easier to write than in machine language but still not portable and remain lengthy.

### High-Level Languages (Third Generation):

- Examples include FORTRAN, BASIC, COBOL, C, C++, and Java.

- Use English words and symbols, making them the easiest to use.

- Programs are portable and shorter because they can be compiled or interpreted on different machines.

- High-level instructions translate into several machine language instructions.

**Key Points:**

- Machine languages are difficult, non-portable, and lengthy.

- Assembly languages are easier but still non-portable and lengthy.

- High-level languages are the easiest, portable, and shorter.

Java rules

Java Programming Ground Rules:

Class Definition: The basic unit in Java, a class, serves as the blueprint for objects. Java programs consist of classes, either from the Java Library or user-defined.

Main Method: Every Java program must include a main method, which is the entry point and must be declared exactly as public static void main (String args[]).

Syntax Rules:

All code must be enclosed within braces {}.

Java is case-sensitive: keywords like public, class, and static are in lowercase.

Statements end with a semicolon ;.

Class Naming Standards:

Class names should start with an uppercase letter.

The Java file name must match the public class name (e.g., Hello.java for the Hello class).

Comments:

Use // to comment a single line. Comments are ignored by the compiler and are for explaining the code to humans.

Reserved Words:

Keywords like public, class, and static have specific meanings and cannot be used for other purposes.

Algorithms

### Key Concepts:

- **Algorithm Definition**: An algorithm is a clear, step-by-step set of operations designed to achieve a specific result, moving from an initial state to a final state.

- **Precondition**: A requirement that must be met before an algorithm runs, such as the input being positive numbers.

- **Writing an Algorithm**: An algorithm should be unambiguous, have defined inputs and outputs, and guarantee to terminate with a correct result.

### Examples:

- **Peanut Butter and Jelly Sandwich**: Write a detailed, step-by-step algorithm to make the sandwich.

- **Finding the Largest Number**:

- You have 10 doors, each hiding a number.

- You can only open one door at a time.

- Write down and compare the numbers to find the largest, erasing previous numbers as needed.

Intro to errors

**I. Syntax Errors**

- **Definition**: Errors in the grammar or rules for forming legal Java statements.

- **Examples**:

- Missing a semicolon `;`

- Mismatched parentheses `()`

- Unmatched braces `{}` and `}`

- Undeclared or misspelled identifiers

- **Detection**: Identified by the Java compiler during translation of `.java` files to `.class` files.

- **Good News**: The compiler provides error messages with location and nature of the syntax error, and with practice, these errors become easier to fix.

**II. Fatal Run-Time Errors (Java "Exceptions")**

- **Definition**: Errors that occur when the program asks the computer to perform an impossible task.

- **Examples**:

- Division by zero

- Taking the square root of a negative number

- Accessing an out-of-bounds list item

- Dereferencing a null pointer

- **Detection**: Occur during program execution; in Java, these are called exceptions.

- **Good News**: The Java interpreter (JRE) provides an approximate location and description of the exception. Avoiding exceptions improves with experience and defensive programming techniques.

**III. Logic Errors**

- **Definition**: The program compiles and runs without exceptions, but produces incorrect output.

- **Examples**:

- Incorrect formulas

- Arithmetic operations in the wrong order

- Improper initialization of variables

- **Detection**: Only detectable by examining the program's output and ensuring it meets the expected results.

- **Debugging Tips**:

- Hand-trace the program step by step ("playing computer").

- Insert temporary output statements to monitor variable values.

**Warning**

-Never assume your program is correct just because it compiles and runs; always verify the output manually.

String/Java output

Key Concepts:

  • Character: An individual letter, digit, or symbol.

  • String: A sequence of characters, like a word or sentence.

  • String Literal: A sequence of characters enclosed in double quotes (e.g., "Hello, World!").

Print vs. Println:

  • print: Outputs text without moving the cursor to the next line. The cursor stays on the same line after the text.

  • println: Outputs text and then moves the cursor to the beginning of the next line.

String Concatenation:

  • The + operator is used to join (concatenate) strings together.

  • When + is used between a string and another data type (like a number), the non-string data is converted to a string and then concatenated.

Ch 2: Using Objects

Accessor and Mutator Methods

1. Definition:

  • Accessor Methods (Get Methods):

    • Return the value of an object's instance variable.

    • Allow you to "get" or retrieve information about an object's state.

  • Mutator Methods (Set Methods):

    • Modify or change the value of an object's instance variable(s).

    • Alter the object's state without returning a value.

2. Differentiating Accessor and Mutator Methods:

  • Accessor Methods return a value and do not modify the object's state.

  • Mutator Methods do not return a value but change the object's state.

3. Object State:

  • Defined by the values of an object's instance variables.

  • Accessor methods retrieve these values; mutator methods modify them.

4. Naming Conventions:

  • Accessor methods typically start with "get" (e.g., getX()).

  • Mutator methods typically start with "set" (e.g., setX()).

5. Examples:

  • Rectangle Class in Java:

    • Instance variables: x, y, width, height.

    • Accessor methods: getX(), getY(), getWidth(), getHeight().

    • Mutator method: translate(int dx, int dy) changes the position of the rectangle.

This distinction between accessor and mutator methods is crucial for understanding how objects interact in an encapsulated environment, where direct access to instance variables is restricted.

The Assignment Operator and Object Variables

1. Java Assignment Operator:

  • Used to store a value in a variable, whether it's a primitive type (e.g., int, double) or an object variable.

2. Assigning Primitive-Type Variables:

  • When you assign one primitive-type variable to another (e.g., x = y;), the value in y is copied into x.

3. Assigning Object Variables:

  • Object Variables Hold References:

    • An object variable doesn't store the object itself but a reference (memory address) to the object.

  • Assignment Behavior:

    • Assigning one object variable to another copies the reference, meaning both variables refer to the same object.

  • Impact:

    • This differs from having two separate objects with identical values; instead, both variables point to the exact same object in memory.c

4. Example:

  • Rectangle one = new Rectangle(5, 10, 20, 30);

    • Rectangle two = new Rectangle(7, 11, 24, 7);

  • If you assign two = one;, both one and two will refer to the same Rectangle object (x = 5, y = 10). The original object (x = 7, y = 11) is no longer referenced.

5. Garbage Collection:

  • If an object is no longer referred to by any variable, it becomes eligible for garbage collection. This means its memory can be reclaimed by the system for future use.

This concept is fundamental in understanding how objects and memory management work in Java, particularly the implications of sharing references between variables.

The Assignment Statement

1. Use of the Assignment Operator:

  • The assignment operator (=) is used to store a value in a variable.

2. Syntax:

  • The basic syntax is: variable = expression;

  • Variable: Can be a primitive type or an object variable.

  • Expression: A combination of literals, variables, and operators.

3. Execution Process:

  • Step 1: The expression on the right side of the assignment operator is evaluated.

  • Step 2: The result is stored in the variable on the left side.

4. Differences from Algebraic Equality:

  • The assignment operator is not the same as an equation in algebra. It should be understood as "gets the value of," meaning the variable on the left is assigned the value from the expression on the right.

5. Example:

  • String Example:

    • String greeting; (declares a String variable)

    • greeting = "Hi"; (assigns the value "Hi" to greeting)

    • System.out.println(greeting); (prints "Hi")

    • greeting = greeting + " Mom!"; (concatenates and assigns the new value "Hi Mom!")

    • System.out.println(greeting); (prints "Hi Mom!")

  • Integer Example:

    • int luckyNumber = 13; (declares and initializes luckyNumber to 13)

    • System.out.println(luckyNumber); (prints 13)

    • luckyNumber = 37; (assigns a new value 37 to luckyNumber)

    • System.out.println(luckyNumber); (prints 37)

    • luckyNumber = (2 * luckyNumber) - 1; (calculates and assigns a new value to luckyNumber)

    • System.out.println(luckyNumber); (prints the result of the calculation)

6. Variable Declaration and Initialization:

  • A variable must be declared only once within a block.

  • If a variable is used before being assigned a value (i.e., uninitialized), it will cause a syntax error.

7. Key Points:

  • Variables are declared once and can be reassigned multiple times.

  • The assignment operator should not be confused with equality; it indicates that the variable on the left side "gets" the value from the right side.

Constructing Objects, Object Variables, and Object References

1. Constructing ("Creating") Objects:

  • Use of new Operator:

    • Objects are created using the new operator.

    • Syntax: new class-name(parameters)

    • Example: new Rectangle(10,20,30,20)

    • Execution: The new operator calls a constructor, which initializes the object's instance variables and returns a reference to the object.

    • Storing Object Reference: Typically, the reference returned by new is stored in an object variable.

    • Example: Rectangle box = new Rectangle(10,20,30,20);

      • Declares a Rectangle object variable box.

      • Calls the Rectangle constructor to create a new object.

      • Stores the reference to the new object in box.

2. Objects vs. Object References:

  • Object Variables Store References:

    • An object variable does not store the object itself but a reference (memory address) to it.

    • Example: In Rectangle box = new Rectangle(10,20,30,20);, box stores a reference to the Rectangle object.

  • Primitive vs. Object Variables:

    • Primitive-type variables (e.g., int, double) store actual values.

    • Object variables store the address of the object, not the object itself.

  • Terminology: While programmers often refer to the object variable as "the object," it's essential to understand that the object variable only holds a reference to the actual object.

3. The null Reference:

  • Automatic Initialization:

    • In Java, object variables are automatically initialized to null.

    • null: A special keyword in Java indicating that the object variable does not refer to any object.

    • Example: Rectangle shoebox; is automatically initialized to null, equivalent to Rectangle shoebox = null;.

  • NullPointerException:

    • Attempting to use (dereference) a null reference (e.g., calling a method on a null object) results in a NullPointerException.

This understanding of object creation, storage, and references is crucial for working with objects in Java and managing how they are manipulated in memory.

Key Concepts in Programming Classes and Methods

1. Definition of a Programming Class:

  • A class is a blueprint for creating objects that share similar characteristics (attributes) and behaviors.

  • Objects: Instances of a class with specific values for their attributes.

  • Two Main Parts of a Class:

    1. Attributes (Fields): Define the properties of the objects.

    2. Methods: Define the behaviors or actions the objects can perform.

2. Invoking a Method:

  • Definition: Calling a method means executing the sequence of instructions defined in that method.

  • Method Parameters: Values passed to a method to customize its operation. They act as inputs for the method.

  • What You Need to Know to Invoke a Method:

    1. The method’s name.

    2. The number and types of its parameters.

    3. The return type of the method (whether it returns a value or not).

3. APIs (Application Programming Interfaces):

  • Definition: Documentation that provides detailed information about the classes and methods available in a programming language.

  • Content: APIs include the method names, parameters, return types, and a brief description of what each method does.

4. String Methods:

  • length() Method:

    • Usage: Returns the number of characters in a string.

    • Example: String sport = "Basketball"; int length = sport.length(); // length = 10

  • replace() Method:

    • Usage: Replaces occurrences of a substring within a string with another substring.

    • Example: String sport = "basketball";
      String anotherSport = sport.replace("basket", "foot");
      // anotherSport = "football"

5. Methods That Return a Value vs. Those That Do Not:

  • Methods That Return a Value:

    • Perform a calculation or operation and return a result that can be stored or used further in the program.

    • Example: int length = sport.length();

  • Methods That Do Not Return a Value:

    • Perform an action but do not return any value.

    • Example: System.out.println("Hello, World!");

6. Common Programming Error:

  • Mistake: Calling a method that returns a value without using the returned value in a statement.

  • Example: sport.length(); // This does nothing by itself and could lead to a logic error.

Understanding these concepts is crucial for effectively working with classes and methods in Java, enabling you to construct, manipulate, and utilize objects efficiently in your programs.

Java Arithmetic and Operator Precedence

1. Arithmetic Operators and Operator Precedence:

  • Operator Precedence: Defines the order in which arithmetic operations are executed in an expression.

  • Operators and Their Precedence:

    • Highest Precedence: * (Multiplication), / (Division), % (Integer Modulus)

    • Lowest Precedence: + (Addition), - (Subtraction)

  • Note: There is no exponentiation operator in Java; use the Math class methods instead.

2. Evaluation of Arithmetic Expressions:

  • Rules:

    1. Operations with higher precedence are performed before those with lower precedence.

    2. Operations of equal precedence are performed from left to right.

    3. Parentheses: Used to override the natural order of operations, ensuring operations within the innermost parentheses are evaluated first.

  • Best Practice: Use parentheses for clarity, especially in complex expressions, to avoid confusion about the order of operations.

3. Integer Division and Modulus:

  • A. Integer Division:

    • When dividing two integers, the result is the integer part of the quotient, discarding any remainder.

    • Examples:

      • 10 / 4 = 2

      • 9 / 5 = 1

      • 99 / 100 = 0

    • Caution: Dividing integers expecting a non-integer (real) result can lead to logic errors.

  • B. Integer Modulus (%):

    • The modulus operator returns the remainder of integer division.

    • Examples:

      • 10 % 4 = 2

      • 9 % 5 = 4

      • 99 % 100 = 99

    • Important: The right-hand operand in both integer division and modulus must be non-zero; otherwise, Java throws an ArithmeticException for division by zero.

Understanding these rules is crucial for writing correct arithmetic expressions in Java, preventing common errors related to operator precedence and integer division.

OOP Terminology and Concepts

1. Definition and Examples of an Object:

  • Object: A software model representing something from the real world or imagination, having attributes (characteristics) and behaviors (actions).

  • Example: A spotlight object has attributes like color, intensity, and state (on/off) and behaviors like changing color, intensity, turning on/off, and reporting its current state.

2. What is a Class in Programming:

  • Class: A programmer-defined abstract data type (ADT) that acts as a blueprint for creating objects. A class defines a domain of objects and operations (methods) on those objects.

  • Analogy: Think of a class as a factory that produces many similar yet distinct objects.

3. Two Distinguishing Parts of an Object:

  • Instance Variables (Instance Fields): Variables that store the attributes of an object. Each object has its own copy of these variables.

  • Methods: Functions in the class that model the behaviors of an object. Methods are shared by all instances of the class.

4. Instance Fields and Methods:

  • Instance Field: Stores the attributes of an object, such as color or intensity in a spotlight.

  • Method: Implements the behavior of an object. For example, a method to change the color of a spotlight.

5. Method Invocation:

  • Invoking a Method: Making an object perform an action by calling one of its methods using the syntax object-name.method-name(arguments).

  • Example: System.out.println("Hello, World!"); calls the println method to print the text.

6. Basic OOP Concepts and Advantages:

  • Reusability: Classes are easily reusable, like interchangeable hardware components, allowing for efficient and standardized software development.

  • Information Hiding: Implementation details of a class are hidden, meaning users interact with objects through well-defined interfaces (methods) without knowing or altering the underlying implementation.

  • Encapsulation: Attributes and behaviors are bundled together in a class, ensuring the integrity of the class by preventing unauthorized access or modification of instance variables.

  • Polymorphism: Different objects can have similar features or behaviors, even if they achieve those behaviors in different ways. For example, both birds and planes can fly, but how they fly differs.

Understanding these concepts is essential for effectively working with object-oriented programming in Java, as they form the foundation of creating and manipulating objects in a structured and reusable manner.

Intro to Variables and Types

What You Should Learn:

  1. Definition of a Variable

  2. Parts Needed to Declare a Variable

  3. How to Declare and Initialize a Variable

  4. Standard Conventions for Naming Variables

I. What is a Variable?

  • Variable Definition:

    • A variable is a location in memory where a value is stored.

    • Analogy: Think of a variable as "a box in which we store a value."

  • Key Characteristics of Variables:

    • Name: The identifier used to refer to the variable.

    • Data Type: Specifies the type of data the variable can store (e.g., int for integers, String for text).

    • Value: The actual data stored in the variable.

    • Address: The memory location where the variable's value is stored (abstracted away in programming).

    • Size: The amount of memory allocated for storing the variable, determined by its data type.

  • Importance of Variables in Programming:

    • Programming involves storing values in variables, manipulating them through operations, and storing the results for later use.

II. Rules for Naming Variables

  1. Allowed Characters: Use letters (A-Z, a-z), digits (0-9), and underscores (_). No spaces allowed.

  2. Starting Character: Must not start with a digit (e.g., 2B is invalid; not2Be is valid).

  3. Length: Can be of any length.

  4. Keywords: Cannot use Java reserved words like public, class, etc.

  5. Case Sensitivity: Variable names are case-sensitive (e.g., greeting and Greeting are different).

  • Best Practices for Naming Variables:

    • Use meaningful and descriptive names.

    • Follow the "humpback notation" (camelCase) convention: start with a lowercase letter and capitalize the first letter of each subsequent word (e.g., luckyNumber, timeOfDay).

III. Variable Declarations

  • Syntax for Declaring Variables:

    • type ident;

    • Where type is the data type, and ident is the variable name.

Examples:
java
Copy code
int luckyNumber;

double taxRate;

String message;

  • Declaring and Initializing Variables:

    • Variables can be given an initial value when declared.

java
Copy code
int luckyNumber = 37;

double taxRate = 0.065; // 6.5%

String message = "Hi Mom!";

  • Multiple Declarations:

    • You can declare multiple variables of the same type in one line.

java
Copy code
int luckyNumber = 37, classRank = 121, age = 12;

double taxRate = 0.065;

String message = "Hi Mom!";

  • Using Previously Declared Variables:

    • Variables declared earlier can be used in later declarations.

java
Copy code
int luckyNumber = 37, classRank = 121, age = 12;

double taxRate = luckyNumber + classRank; // Using previously declared variables

This overview covers the basics of variables in Java, including their definition, declaration, initialization, and naming conventions. Understanding these fundamentals is crucial for effective programming and code readability.