Reputation: 112
Where is "int size " getting it's value from? I read code like 1000 times,but I still have no clue where is "size" initialized, I am new in java, but I don't understand this one,code is working fine any help would be nice. thanks in advance
public class Study {
public static void main(String[] args) {
Queue queue = new Queue();
for (int i = 0; i <= 20; i++)
queue.enqueue(i);
while (!queue.empty())
System.out.print(queue.dequeue() + " ");
}
}
class Queue {
private int[] elements;
private int size;
public Queue() {
elements = new int[8];
}
public void enqueue(int value) {
if (size >= elements.length) {
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
System.out.println(elements.length);
elements = temp;
}
elements[size++] = value;
}
public int dequeue() {
int v = elements[0];
// Shift all elements in the array left
for (int i = 0; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
size--;
return v;
}
public boolean empty() {
return size == 0;
}
public int getSize() {
return size;
}
}
Upvotes: 1
Views: 299
Reputation: 11487
All instance variables will be assigned a default value by the compiler if you haven't provided one. Snippet from java doc
Default value will be zero or null depending the data types.
The link also has a grid which tells you about the default values for all data types.
Local variables are variables which are used inside a method:
The compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
Upvotes: 0
Reputation: 4692
Default value is 0
for int
.
And size++
and size--
is doing the changes to its value.
For more information refer: Assignment, Arithmetic, and Unary Operators
Upvotes: 5
Reputation: 178
size++
is equal to the statement size = size + 1
, the same for size--
which does size = size - 1
Upvotes: 2