JAVA BASICS IN DETAIL
Java new keyword
The keyword new tells Java to create a new object or array. Simply put, a declaration gives a variable a name, while new prepares actual storage for the data.
Creating a new object
Let's create an everyday object: a cup with a color.
class Puodelis {
String spalva;
Puodelis(String spalva) {
this.spalva = spalva;
}
}
Puodelis manoPuodelis = new Puodelis("mėlynas");
System.out.println(manoPuodelis.spalva);mėlynas
Puodelisis a class: a description of the future object.manoPuodelisis a variable that will store a reference to the object.new Puodelis("mėlynas")creates a newPuodelisobject.- The value in parentheses goes to the constructor, which sets the object's color.
- The operator
=stores the reference in the variablemanoPuodelis.
A declaration does not create an object
Puodelis puodelis;
// The object has not been created yet.
puodelis = new Puodelis("žalias");This code prints nothing. It first declares a variable and only later creates an object.
The line Puodelis puodelis; resembles an empty name label. Only after executing new Puodelis(...) does an object exist for that label to refer to.
new with an array
For an array, specify the number of element slots after the type:
int[] pazymiai = new int[3];
pazymiai[0] = 8;
pazymiai[1] = 10;
System.out.println(pazymiai.length);
System.out.println(pazymiai[0]);
System.out.println(pazymiai[2]);3
8
0
new int[3]creates three numbered slots:0,1and2.- Java initially fills every slot of a new
intarray with the number0. - We assign the first two slots
8and10. - The third slot is unchanged, so it retains its initial value,
0.
What do the parentheses after a class name mean?
Knyga knyga = new Knyga("Mažasis princas");Knyga specifies the class of the value being created, while Knyga("Mažasis princas") calls its matching constructor. The constructor prepares the object's initial state.
Each new usually creates a separate object
Puodelis pirmas = new Puodelis("baltas");
Puodelis antras = new Puodelis("baltas");
System.out.println(pirmas == antras);
System.out.println(pirmas.spalva.equals(antras.spalva));false
true
- Each line creates a separate cup object.
pirmas == antraschecks whether both references point to the same object, so the result isfalse.- Both objects have the same color text, so
equals()returnstrue.
What happens to memory?
Java manages object memory automatically. When an object becomes unreachable by the program, it may later be removed by the garbage collector (garbage collector). Programmers do not need to free memory manually after each new.
What should you remember?
newcreates a new object or array.- Creating an object calls its constructor.
- The variable stores a reference to the object, not the object itself.
- Declaring a reference variable alone is not enough to create an object.
new int[3]creates exactly three array element slots.- Java automatically manages the memory of unused objects.