Objects and Classes
Create an object
Primitive and reference types
How primitive types and reference types are passed to a method
- When a primitive type is passed to a method, it is passed by value. That means the method can't change the value of the variable itself. Instead, the method must return a new value that gets stored in the variable.
- When a reference type (an object) is passed to a method, it is passed by reference. That means that the method can change the data in the object itself, so a new value doesn't need to be returned by the method.
Primitive types are passed by value.
A method that changes the value of a double type
static double increasePrice(double price) // returns a double { return price *= 1.1; }Code that calls the method
double price = 49.5; price = increasePrice(price); // reassignment statement System.out.println("price: " + price); Result price: 54.45
Objects are passed by reference.
A method that changes a value stored in a Product object
static void increasePrice(Product product) // no return value { double price = product.getPrice(); product.setPrice(price *= 1.1); }Code that calls the method
Product product = ProductDB.getProduct("java"); System.out.println("product.getPrice(): " + product.getPrice()); increasePrice(product); // no reassignment necessary System.out.println("product.getPrice(): " + product.getPrice()); Result product.getPrice(): 49.5 product.getPrice(): 54.45