Back to GT CS-1331

Primitive Types vs Classes:

  • Classes can have values of multiple types

  • Classes also offer methods

Declaring Variables of Classes:

  • Declared the same as a normal variable

  • Called reference variables

  • Stores memory address to the class

    • Primitives store actual value instead

    • Due to complexity, classes are stored in a seperate part of memory called the heap

Instantiation:

  • Creating an instance of a new class:

    • Use the ‘new’ operator
      • Calls special method of the class called a constructor
        • Initializes certain properties of the new method
//Creating instance of String using the String class
String hi;
hi = new String("Hi"); 
//Same thing but using a literal (used for String)
String hi = "hi";

Invoking Methods:

  • Standard Library/Java API

    • Classes that are auto bundled with Java
  • Template identifier.methdodName(parameters)

//Using String hi from last example
hi.length();
  • Methods return values when executed without errors

    • Value returned is called a return value

    • Type of the value returned is called the return type

Reference Variables:

  • Equaling reference variables will not copy the data

    • They will point to the same memory location

      • Edit one, change both

Garbage Collection:

  • Happens automatically

  • If an object has no variables pointing to it, Java will free up that area of memory

String Methods:

  • Method Signature consists of the method’s name and type/position

  • Methods:

    • toLowerCase(): returns new String in lowercase
    • toUpperCase(): returns new String in uppercase
    • concat(String str): combines two Strings and returns result
    • replace(char oldChar, char newChar): replaces each occurrence of some character in a string
    • substring(int start, int end): returns string from index start to index end - 1. [start, end) - Index: integer that represents the position of a character in a string - If index is not in list, creates StringIndexOutOfBoundsException
    • indexOf(String str): returns index of first occurrence of string, otherwise -1
    • lastIndexOf(String str): returns last index of first occurrence of string, otherwise -1

String Immutability:

  • String are Immutable (can’t be edited)

  • Reasons:

    • Security: Protect important data stored in strings from being edited

    • JVM:

      • JVM stores several critical values, including the names of classes it will load, as Strings.

      • Dynamically changing the contents could allow untrustworthy code to exploit programs.

    • Allows for better optimization at runtime (faster execution times)

    • Allows for reuse of String literals