Objects
/**
* To use an object you must declare a reference variable.
* JVM allocates space for the object.
*
* The reference variable is forever of that type.
* You cannot assign an object to another type.
* myDog = new Cat(); // ❌ Type mismatch error
*/
package com.minte9.basics.objects;
public class Objects {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.size = 40;
myDog.bark();
}
}
class Dog {
int size;
void bark() {
System.out.println("Ham Ham"); // Ham Ham
}
}
References
/**
* A reference to an object can be overridden
*
* After a overrites b, the b reference to object 2 is destroyed
* Eligible for Garbage Collection
*/
package com.minte9.basics.objects;
public class References {
public static void main(String[] args) {
Book a = new Book("A");
Book b = new Book("B");
System.out.printf("%s%s /", a, b); // AB
Book c = b; // refc, objB
System.out.printf("%s%s%s /", a, b, c); // ABB
b = a; // refb, objA, objB destroyed
System.out.printf("%s%s%s /", a, b, c); // AAB
}
}
class Book {
String name;
public Book(String name) { // contructor
this.name = name;
}
public String toString() {
return name;
}
}
Autoboxing
/**
* Java has a two-part type system, primitives (int, double, boolean, etc) and
* reference types (String, List, etc). Every primitive type has a corresponding
* reference type, called boxed primitive (Integer, Double, Boolean, etc).
* Autoboxing reduces the verbosity, bot not the danger, of using boxed primitives.
* Unboxing is the automatic conversion of objects into their coresponding primitives.
*/
package basics;
import java.util.List;
import java.util.ArrayList;
public class Autoboxing {
public static void main(String[] args) {
List<Integer> li = new ArrayList<>();
// --- Autoboxing ---
for (int i=0; i<10; i++) {
li.add(i); // autoboxing (i is primitive)
}
System.out.println(li); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println(li.get(0).getClass().getName()); // java.lang.Integer
// --- Unboxing ---
int b = li.get(0); // unboxing (element is Integer)
System.out.println(b); // 0 (primitive int)
// --- Integer cache ---
// Java caches boxed Integer values from -128 to 127 and reuses those instances.
Integer c = 100, d = 100;
System.out.println(c == d); // true -- both come from the cache
Integer e = 200, f = 200;
System.out.println(e == f); // false -- outside the cache, different objects
System.out.println(e.equals(d)); // true -- always compare wrapper values with equals
int g = 200, h = 200;
System.out.println(g == h); // true
}
}