L3: Back to Basics

Whitespace in Java

  • Whitespace: Includes spaces, tabs, and newline characters. It separates words and symbols to make the code readable.
  • The compiler ignores extra whitespace, but using it improves code readability for developers.

Errors in Java

  1. Compiler Errors vs. Runtime Errors:
    • Compiler Errors: Occur when the code violates Java’s syntax rules (e.g., missing a semicolon or misspelled keywords). These errors prevent the program from compiling and provide details like the error type and line number.
    • Runtime Errors: Occur while the program is running (e.g., division by zero). These errors are not caught by the compiler.
  2. Logical Errors:
    • The program compiles and runs, but produces incorrect results due to flawed logic (e.g., incorrect calculations or using the wrong condition in an if statement).
    • Testing and debugging are essential to identify and fix these errors.
  3. Syntax vs. Semantics:
    • Syntax: Refers to the correct structure of code (e.g., correct use of keywords and punctuation).
    • Semantics: Refers to the meaning and logic of the code. Syntactically correct code can still have semantic errors.

Variables and Constants

  1. Variables: Store data in memory. Defined by a data type (e.g., intdouble) and an identifier (name).

    • Scope: The section of the program where the variable can be accessed. Defined by the braces {} in which it is declared. A variable declared inside a method cannot be accessed outside that method.
  2. Constants: Values that do not change after they are assigned. Declared using the final keyword.

    final double PI = 3.14159;
    • Constants follow the same scope rules as variables.

Primitive Data Types

image.png

  • Integer Types: byteshortintlong
  • Floating-Point Types: floatdouble
  • Character Type: char
  • Boolean Type: boolean
  1. Sizes in Memory:

    • byte: 8 bits
    • short: 16 bits
    • int: 32 bits
    • long: 64 bits
    • float: 32 bits
    • double: 64 bits
    • char: 16 bits
    • boolean: 1 bit (true or false)
  2. Legal Assignment of Literals:

    • Integer literals default to int, floating-point literals to double.

    • Suffixes can change default types:

      long bigNumber = 123456789L;
      float fraction = 3.14F;
  3. Type Conversion:

    • Widening: Safe conversion of a smaller type to a larger type (e.g., int to double).

    • Narrowing: Risky conversion from a larger type to a smaller type, which may cause data loss.

    • Casting: Explicitly converts one data type to another using (target_type). Useful when narrowing:

      int num = (int) 3.14;  // Results in 3
  4. Purpose of Multiple Numerical Types:

    • Different types allow optimization of memory usage and precision based on the requirements of the program.

Primitive Operations

  1. Arithmetic Operators:

    • +/%
    • Integer Division: Dividing two integers truncates the decimal (e.g., 9 / 2 results in 4).
  2. Order of Operations: Follows standard algebraic precedence (e.g., multiplication and division before addition and subtraction). Parentheses can be used to alter the order.

    image.png

  3. Incrementing and Decrementing:

    • ++ (increment) and -- (decrement) operators to increase or decrease a variable’s value by 1.

    • In the prefix form, the operator is placed before the operand. The value of the operand is incremented or decremented first, and then the result is used in the expression. The syntax for prefix increment and decrement operators is as follows:

      ++variable;
      --variable;
    • In the postfix form, the operator is placed after the operand. The value of the operand is used in the expression first, and then it is incremented or decremented. The syntax for postfix increment and decrement operators is as follows:

      variable++;
      variable--;
  4. Assignment Operators:

    ⚠️

    If you declare an variable inside a method (including the main method) without initializing it, it won’t have a default value. You must explicitly assign a value to it before using it, otherwise, you’ll get a compilation error.

    If you declare an variable as a member of a class (outside any method), it will automatically be initialized to the appropriate default value.

    • = for assignment.

    • Compound operators (e.g., +===/=) combine an operation with assignment:

      int x = 5;
      x += 3;  // Equivalent to x = x + 3;

      image.png

Strings in Java

  1. String Creation: Defined using double quotes ("):

    String greeting = "Hello, World!";
  2. String Methods: Common methods include:

    • length(): Returns the length of the string.
    • charAt(int index): Returns the character at the specified index.
    • substring(int start, int end): Returns a substring from the start to the end index.
    • toUpperCase()toLowerCase(): Converts the string to uppercase or lowercase.
  3. String “Arithmetic” (Concatenation):

    • The + operator concatenates strings:

      String fullName = "John" + " " + "Doe";  // "John Doe"
  4. String Immutability: Strings are immutable, meaning once created, they cannot be changed. Any modification results in a new string.

  5. String Constant Pool: Strings with identical content are stored in a common pool to optimize memory usage.

  6. Predefined Classes: Java’s standard library includes classes like String, which provide methods for handling text efficiently.

Reference Variables

  1. Instantiation Using new:

    • Creates a new object of a class:

      String message = new String("Hello");
  2. Aliases: When two reference variables point to the same object, changes through one reference affect the other.

  3. Garbage Collection: Automatically frees memory by removing objects that no longer have any references.

  4. Invoking Methods: Methods are called using dot notation:

    int length = message.length();