int i; // automatically i = 0
int
, long
, double
, boolean
, …new
)String
, Person
, …zahrnují typy celočíselné (byte , short , int a long) a typ char
float a double
boolean
Dle Java Language Specification: Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
byte
, the default value is zero, that is, the value of (byte)0
.short
, the default value is zero, that is, the value of (short)0
.int
, the default value is zero, that is, 0
.long
, the default value is zero, that is, 0L
.float
, the default value is positive zero, that is, 0.0f
.double
, the default value is positive zero, that is, 0.0d
.char
, the default value is the null character, that is, '\u0000'
.boolean
, the default value is false
.null
int i; // automatically i = 0
Více informací najdete na: The Java Tutorials: Primitive Data Types. |
private int bigNumber = 123_456_789;
Výchozí hodnota objektového typu je null
— tzv. "ukazatel na nic".
Person p; // p is null automatically
p = new Person(); // now p references to an object
new
.Základní rozdíl je v práci s proměnnými.
přímo obsahují danou hodnotu
obsahují pouze odkaz na příslušný objekt
double a = 1.23456;
double b = a;
a += 2;
// a is 3.23456
// b is 1.23456
public class Counter {
private double value;
public Counter(double v) {
value = v;
}
public void add(double v) {
value += v;
}
}
...
Counter c1 = new Counter(1.23456);
Counter c2 = c1;
c1.add(2);
// c1 has value 3.23456
// c2 has value 3.23456
==
1 == 1 // true
1 == 2 // false
Counter c1 = new Counter(1.23456);
Counter c2 = c1;
c1 == c2 // true
c1 == new Counter(1.23456) // false
equals
, probereme později.int[] array = new int[2];
array[0] = 1;
array[1] = 4;
System.out.println("First element is: " + array[0]);
new
typ [velikost];Person[] p = new Person[3];
int[] array = new int[] {1, 4, 7};
int[] array2 = array;
array[1] = 100;
System.out.println(array[1]); // prints 100
System.out.println(array2[1]); // prints 100
Provedeme-li vytvoření nového pole, pak array2 obsahuje kopii (duplikát) původního pole.
int[] array = new int[] {1, 4, 7};
int[] array2 = Arrays.copyOf(array, array.length);
array[1] = 100;
System.out.println(array[1]); // prints 100
System.out.println(array2[1]); // prints 4
Metoda copyOf
bere dva parametry — původní pole a počet prvků, kolik se má nakopírovat.
Person[] people = new Person[] { new Person("Jan"), new Person("Adam")};
Person[] people2 = Arrays.copyOf(people, people.length);
people[1] = new Person("Pepa");
System.out.println(people[1].getName()); // prints Pepa
System.out.println(people2[1].getName()); // prints Adam
Person[] people = new Person[] { new Person("Jan"), new Person("Adam")};
Person[] people2 = Arrays.copyOf(people, people.length);
people[1].setName("Pepa"); // changes Adam to Pepa
System.out.println(people[1].getName()); // prints Pepa
System.out.println(people2[1].getName()); // prints Pepa
/