Unit 2 - Using Objects

Primitive vs Object Types in Java

/

  • There are eight primitive types in Java. They represent small, simple pieces of data.

    • Example: int a = 3;

      • The value (3) for the variable a is stored directly in the stack memory.

    • Similarly, double and boolean variables store their values directly on the stack.

  • Object types (also called reference types) include String, Array, Scanner, and user-defined types like Dog.

    • Unlike primitive types, you can design your own object types (classes).

  • Object Type Variable Declaration and Initialization:

    • Dog x = new Dog();

    • Object type variables store a pointer on the stack. This pointer refers to a location in heap memory where the actual object is stored.

    • Heap memory is larger than stack memory and is used for more complex objects.

  • Object Identity:

    • Creating two objects of the same type (e.g., Dog y = new Dog(); Dog x = new Dog();) results in two equivalent but distinct objects in different locations in heap memory.

    • The pointers for x and y on the stack are different because they point to different memory locations.

  • Copying Variables:

    • Primitive Type: int d = a;

      • The value of a (from the stack) is copied and assigned to d.

      • Each variable (a and d) has its own unique value.

    • Object Type: Dog z = y;

      • The pointer value of y (from the stack) is copied and assigned to z.

      • Both z and y now point to the same location in heap memory (the same object).

      • x's pointer has a different value because it points to a different location on the heap.

  • Equality Operator (==):

    • Compares the values on the stack for two variables.

      • a == b (where a is an int and b is a double with the same numerical value): Evaluates to true because Java recognizes their mathematical equivalence.

      • x == y (where x and y are Dog objects pointing to different locations): Evaluates to false because the pointers are different.

      • y == z (where y and z are Dog objects pointing to the same location): Evaluates to true because the pointers are the same.

  • Object Equivalence:

    • Checking if two objects (referenced by x and y) have equivalent content requires specific methods depending on the object type (it's never ==).

  • Modifying Variables:

    • Primitive Type: d = 6;

      • Changes the value of d without affecting a.

      • a == d would now evaluate to false.

    • Object Type:

      • Modifying the object itself (e.g., changing y's color property to blue) affects both y and z because they point to the same object.

      • Reassigning z to point to a different object doesn't affect y because y still points to the original object.

Classes and Objects

  • Object: An instance of a class, possessing states (data) and behaviors (methods).

    • States: Represented by field variables (attributes).

    • Behaviors: Represented by methods (actions).

    • Example: A LightBulb object might have color and size as states and flash(), turnOff(), and switchColor() as behaviors.

  • Class: A blueprint or template for creating objects.

    • Java provides built-in classes like String, Arrays, and Scanner.

    • Programmers can also write custom classes.

    • A class can be used to create multiple objects (instances).

  • Object Creation: Creating an object from a class.

    • LightBulb x = new LightBulb();

      • Declares a variable x of type LightBulb and initializes it to point at a newly created LightBulb object.

    • Two-step declaration and initialization:

      • LightBulb y;

      • y = new LightBulb();

    • Objects are accessed through variables (references). Variables act as names to indentify objects.

  • Constructors: Used to initialize objects during creation.

    • LightBulb z = new LightBulb("green");

      • Passes the string "green" to the constructor, which sets the color field of the LightBulb object to green.

    • The class programmer defines the types of arguments a constructor can accept.

  • Fields (Variables): Manage the state of an object.

    • Class Variables (Static Fields): Belong to the class itself and are shared by all instances.

      • Changing a class variable affects the class and all its instances.

    • Instance Variables (Non-Static Fields): Belong to individual instances of the class.

      • Each instance has its own unique copy of the variable.

      • Changing the value of an instance variable only affects that instance.

  • Methods: Represent the behaviors of an object or class.

    • Static Methods: Can be called directly from the class or from an object.

      • Represent behaviors of the class itself.

      • LightBulb.decreaseSize();

      • Can only access class variables.

    • Non-Static Methods: Can only be called from an object.

      • Represent behaviors of the object.

      • q.switchColor();

      • Can access both class variables and instance variables.

  • Restrictions:

    • Static methods can only access class variables.

    • Non-static methods can access both class and instance variables.

  • Exceptions:

    • The String and Array classes have unique ways of creating objects.

Calling Methods in Java

  • Methods as Behaviors

    • Static Methods: Behaviors belonging to the class.

    • Non-Static Methods: Behaviors belonging to objects.

  • Example: Cake Class

    • blueprint for cake objects, includes fields, constructors, and methods

    • Method Headers (example car)

      • information on what a method does (driving it).

      • public: Access modifier, callable from inside or outside the class.

      • private: Access modifier. Only callable from inside the class.

      • static: Keyword indicating the method belongs to the class.

      • Return type: Data type returned by the method (primitive or object type).

      • void: Return type indicating no data is returned.

      • Method Name: Lower camel case, describing what the method does.

      • Parameters: Variables receiving data passed to the method.

  • Confusions

    • Parameters: Tell you what data needs to be sent to a method when we call it.

    • Return types: Tell you what type of data will be returned back.

  • Bakery Class (Main Method)

    • Calling Methods:

      • Cake.listFlavorChoices(): Calling a static method from the class.

      • Storing a Return Value:

        • String flavors = Cake.listFlavorChoices(); (Storing the returned string).

      • Calling Non-Static Methods:

        • Creating an Object: Cake vanilla = new Cake();

        • Calling Method on Object: int calories = vanilla.howManyCalories(); (Storing the returned int).

      • Methods and Objects

        • cakes have calories depending on the cake. The variability is key to understanding why how many calories is a non static method.

      • Modifying Objects: vanilla.addWriting("Happy Birthday");

      • Private Access Modifier: mixIngredients() (cannot be directly called from Bakery class).

  • Recap:

    • Methods are behaviors. Static methods belong to classes, and non-static methods belong to objects.

    • Static methods are called from the class, while non-static methods require creating an object.

    • Method headers contain access modifiers, return types, method names, and parameters.

Using the String Class

  • String Data Type: Holds text; internally an array of char.

  • String Pool: A special memory area for strings to reduce memory usage.

    • String a = "hello";

      • Creates a string literal, places the variable "a" on the stack and creates a pointer, pointing to the String object "hello" in the string pool.

    • If another string with the same value is created, Java will point the new variable to the existing string in the pool.

  • Creating a String Object (Less Common):

    • String c = new String("hello");

      • Creates a unique object outside the string pool.

      • Each object created this way occupies a different memory location, even with the same data.

  • Equality Comparisons:

    • ==: Compares the pointers (memory locations) on the stack, not the content.

      • a == b (where a and b point to the same string in the pool): true

      • c == d (where c and d are different String objects with the same value): false

      • Referential equality checks if variables are pointing at the same memory location.

    • .equals(): Compares the content of the strings.

      • a.equals(b) (where a and b have the same value): true

      • c.equals(d) (where c and d have the same value): true

  • String Immutability:

    • Strings are immutable which means once created, they cannot be modified.

    • Operations that seem to modify a string actually create a new string object.

  • Example:

    • String e = "hi"; (Creates a new object in the string pool).

    • String f = e; (Copies the pointer, so e and f point to the same object).

    • String g = "howdy"; (Points to a new string in the string pool).

    • String h = new String("HI"); (Creates a new object on the heap).

  • String Comparisons (Examples):

    • e.equals(f): true (same object, same value).

    • e.equals(h): false (case-sensitive comparison).

    • e.equalsIgnoreCase(h): true (ignores case).

  • Other Useful Methods:

    • .length(): Returns the length of the string (number of characters).

      • g.length() (where g is "howdy"): Returns 5.

    • .substring(int beginIndex): Returns a substring starting from the specified index (inclusive) to the end.

      • g.substring(2): Returns "wdy".

    • .substring(int beginIndex, int endIndex): Returns a substring starting from beginIndex (inclusive) and ending at endIndex (exclusive).

      • g.substring(1, 4): Returns "owd".

    • .compareTo(String anotherString): Compares two strings lexicographically (dictionary order), returning an int.

      • Returns 0 if the strings are equal.

      • Returns a value < 0 if the string is lexicographically less than the argument.

      • Returns a value > 0 if the string is lexicographically greater than the argument.

      • h.compareTo(e): Returns -32 (because 'H' comes before 'h').

  • Using Methods (Examples):

    • int i = h.length(); (Storing the length in an int).

    • if (e.equals("pi")) { ... } (Conditional execution based on string comparison).

Uses for the Plus Sign in Java

  • Two Functions:

    • Mathematical Addition: Adding numbers.

    • Concatenation: Combining strings into a single string.

  • Mathematical Addition:

    • 3 + 5 (ints): Evaluates to 8.

    • 2.0 + 4.0 (doubles): Evaluates to 6.0.

    • 4.2 + 3 (double and int): Evaluates to 7.2 (int is automatically converted to double).

    • Example: double a = 4.2 + 3;

  • String Concatenation:

    • Combining two strings:

      • "Hi" + " there": Evaluates to "Hi there".

    • String and int:

      • "great" + 8: Evaluates to "great8" (int converted to string).

  • Operator Precedence:

    • The + operator is left-associative (evaluated from left to right).

    • 8 + 9 + " years old": Evaluates to "17 years old".

    • Parentheses change the order of operations:

      • 8 + (9 + " years old"): Evaluates to "89 years old".

The Math Class in Java

  • Contains methods for various mathematical functions.

  • All methods are static, so they are called directly from the class (Math.random()).

  • Cannot be extended or instantiated.

  • Common Methods:

    • Math.abs(x): Returns the absolute value of x (int, double, float, or long).

      • Returns the same data type as the input.

      • Math.abs(-3.2): Returns 3.2.

    • Math.pow(x, y): Returns x raised to the power of y (exponents).

      • Can be passed ints, doubles, floats, or longs.

      • Always returns a double.

      • Math.pow(3, 2.0): Returns 9.0.

    • Math.sqrt(x): Returns the square root of x (int, double, float, or long).

      • Always returns a double.

      • Math.sqrt(9): Returns 3.0.

    • Math.PI: A public field variable (double) representing the mathematical constant Pi.

      • Example: double circumference = 2 * Math.PI * radius;

  • Documentation:

    • Search for "Java [version number] Math" to find the official documentation.