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
ais stored directly in the stack memory.
Similarly,
doubleandbooleanvariables store their values directly on the stack.
Object types (also called reference types) include
String,Array,Scanner, and user-defined types likeDog.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
xandyon 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 tod.Each variable (
aandd) has its own unique value.
Object Type:
Dog z = y;The pointer value of
y(from the stack) is copied and assigned toz.Both
zandynow 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(whereais anintandbis adoublewith the same numerical value): Evaluates totruebecause Java recognizes their mathematical equivalence.x == y(wherexandyareDogobjects pointing to different locations): Evaluates tofalsebecause the pointers are different.y == z(whereyandzareDogobjects pointing to the same location): Evaluates totruebecause the pointers are the same.
Object Equivalence:
Checking if two objects (referenced by
xandy) have equivalent content requires specific methods depending on the object type (it's never==).
Modifying Variables:
Primitive Type:
d = 6;Changes the value of
dwithout affectinga.a == dwould now evaluate tofalse.
Object Type:
Modifying the object itself (e.g., changing
y's color property to blue) affects bothyandzbecause they point to the same object.Reassigning
zto point to a different object doesn't affectybecauseystill 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
LightBulbobject might havecolorandsizeas states andflash(),turnOff(), andswitchColor()as behaviors.
Class: A blueprint or template for creating objects.
Java provides built-in classes like
String,Arrays, andScanner.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
xof typeLightBulband initializes it to point at a newly createdLightBulbobject.
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
colorfield of theLightBulbobject 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
StringandArrayclasses 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 returnedint).
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 fromBakeryclass).
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
StringData Type: Holds text; internally an array ofchar.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(whereaandbpoint to the same string in the pool):truec == d(wherecanddare differentStringobjects with the same value):falseReferential equality checks if variables are pointing at the same memory location.
.equals(): Compares the content of the strings.a.equals(b)(whereaandbhave the same value):truec.equals(d)(wherecanddhave 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, soeandfpoint 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()(wheregis "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 frombeginIndex(inclusive) and ending atendIndex(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 anint).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 ofx(int, double, float, or long).Returns the same data type as the input.
Math.abs(-3.2): Returns 3.2.
Math.pow(x, y): Returnsxraised to the power ofy(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 ofx(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.