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;
}
}
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
size++ is equal to the statement size = size + 1, the same for size-- which does size = size - 1
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.
Related
This question already has answers here:
Uninitialized variables and members in Java
(7 answers)
Closed 5 years ago.
Couldn't find an explicit description of what's happening so thought i'd bring this up to the community.
public class Temp {
static int i;
int j;
int sum = i+j;
}
public class Main{
public static void main(String[] args){
Temp obj = new Temp();
obj.i = 1;
obj.j = 2;
System.out.println(obj.sum); //returns '0'
}}
Is it because both integers i and j were empty during instantiation that the 'sum' variable is empty?
Thanks in advance!
Temp obj = new Temp(); // creates an instance of object type Temp
Here, data members, i, j, and sum are initialized to 0
obj.i = 1; // assigns value of Temp data member, i to 1
obj.j = 2; // assigns value of Temp data member, j to 2
Note that the value of data member sum of Temp Object obj is still 0.
To make, sum = i + j, you need to initialize it to i + j when i and j are initialized.
Simply write obj.setSum() method to set the value of sum and obj.getSum() after that to retrive the updated value of it.
public class Temp {
static int i;
int j;
int sum = i+j;
public void setSum(){
sum = i + j;
}
public int getSum(){
return sum;
}
}
public class Main{
public static void main(String[] args){
Temp obj = new Temp();
obj.i = 1;
obj.j = 2;
obj.setSum();
System.out.println(obj.sum); //OR obj.getSum()
}
}
Is it because both integers i and j were empty during instantiation
that the 'sum' variable is empty?
Yes, i+j is assigned to 'sum' when the Object is instantiated. By default java assign 0 to int values when you don't assign a value.
You need to update the sum variable by directly assigning the value to it.
obj.i = 1;
obj.j = 2;
obj.sum = obj.i + obj.j.
A workaround is to create a getter method in your Temp class instead of the variable sum:
public class Temp {
static int i;
int j;
public int getSum() {
return i + j;
}
}
Then to print the sum :
System.out.println(obj.getSum());
When you create another class that will be use by the main method
numeric data fields are set to zero
Character fields are set to Unicode \u0000
Boolean fields are set to false
Fields that are object references are set to null or (empty) for example String data fields
In the main, whenever I call this method to sort the array, it stops as if it's waiting for a response. Any idea why it's not working?
public void bubbleSort(){
boolean finished = false;
boolean swapOccurred = false;
int i = 0;
int next = i + 1;
while (finished == false)
{
for (; i < theArray.length - 1; i++)
{
if (theArray[i] > theArray[next])
{
swapValues(theArray[i], theArray[next]);
swapOccurred = true;
}
}
if (swapOccurred == false)
{
finished = true;
}
}
}
private void swapValues(int i, int next) {
int temp;
temp = i;
i = next;
next = temp;
}
If it is java, then
The next index is never updated so it stays 1 all the time.
The swap method has no side effect, you want to swap the elements in theArray, but in java methods arguments are passed as values so the next and i variables change the value only inside the swap method, they have nothing to do with the cells of theArray array.
The problem is with your swap.
In C, arguments are passed by value, so when you do the swap, the values being passed in aren't affected, so nothing is happening. You need to pass in pointers to the numbers instead (and then dereference them inside):
private void swapValues(int *i, int *next) {
int temp;
temp = *i;
*i = *next;
*next = temp;
}
And then call it with the address of the variables to swap:
swapValues(&theArray[i], &theArray[next]);
Edit: Ha - #Zielu saw Java, I saw C. Same problem in both cases, and as #Zielu points out, you also need to increment next. I believe you actually just want to use [i+1] as your index in place of next.
I used an ArrayList at first. But then my course teacher told me that I can't use ArrayList in my program. He said that I can only use arrays.
The problem is when I add an integer to array, it just puts zero on the first index.
Here is the code :
int[] Bag = new int[1];
boolean isit = true;
do {
int[] NewBag = new int[Bag.length + 1];
String name = scanner.next();
if (name.equals("A")){
int number = scanner.nextInt();
for (int i = 0; i < Bag.length; i++) {
NewBag[NewBag.length - 1] = number;
NewBag[i] = Bag[i];
}
Bag = NewBag;
System.out.println(number + " added to Bag.");
}
} while (isit == true);
Please help me guys. I can't make Minimum and Size operations without the correct Add operation.
You start with a single-element array, and immediately add a second element to it:
int[] NewBag = new int[Bag.length + 1];
Thus by the time you've read one number your array already contains two elements (i.e. one element too many).
To correct this, you need to change the
int[] Bag = new int[1];
to
int[] Bag = new int[0];
If this looks odd, see Why does Java allow arrays of size 0?
You'll also need to move
NewBag[NewBag.length - 1] = number;
out of the loop.
I don't know what you want to do with your array, but if you want to wrap an array into something, that has similar methods to an ArrayList, you could do something like this (mind, that once it reaches the array's size, int wont grow.):
class MyArray {
private final int[] mArray;
private int mSize = 0;
public MyArray(final int maxSize) {
mArray = new int[maxSize];
}
public void add(final int element) {
if (mSize < mArray.length) {
mArray[mSize++] = element;
} else {
throw new IndexOutOfBoundsException("No more room");
}
}
public int get(final int index) {
return mArray[index];
}
public int size() {
return mSize;
}
}
Then you could do your logic:
int maxSize = scanner.nextInt();
MyArray array = new MyArray(maxSize);
for(int i=0; i<maxSize; i++) {
array.add(scanner.nextInt());
}
I have a simple converter method for an array from boolean to int:
public static int[] convert1dToInt (boolean[] x) {
int la = x.length;
int[] y = new int[la];
for (int a = 0; a < la; a++) {
if (x[a]) {
y[a] = 1;
} else {
y[a] = 0;
}
}
return y;
}
Now I have the same method for 2-dimensional arrays:
public static int[][] convert2dToInt (boolean[][] x) {
int la = x.length;
int lb = x[0].length;
int[][] y = new int[la][lb];
for (int a = 0; a < la; a++) {
for (int b = 0; b < lb; b++) {
if (x[a][b]) {
y[a][b] = 1;
} else {
y[a][b] = 0;
}
}
}
return y;
}
How can I generalize those methods for arrays of arbitrary dimension without writing all the methods by hand?
This is possible, but reflection and recursion are both inevitable:
import java.lang.reflect.Array;
public class ArrayTransfer {
private static int getArrayDimension(Object array) {
Class<?> clazz = array.getClass();
int dimension = 0;
while (clazz.isArray()) {
clazz = clazz.getComponentType();
dimension += 1;
}
if (clazz != boolean.class) {
throw new IllegalArgumentException("Base array type not boolean");
}
return dimension;
}
// Transfers a boolean array of the specified dimension into an int
// array of the same dimension.
private static Object transferToIntArray(Object booleanArray, int dimension) {
if (booleanArray == null) {
return null;
}
// Determine the component type of the new array.
Class<?> componentType;
if (dimension == 1) {
componentType = int.class;
} else {
// We have a multidimensional array; the dimension of the component
// type is one less than the overall dimension. Creating the class
// of an array of an unknown dimension is slightly tricky: we do
// this by creating a 0 x 0 x ... x 0 array (with dimension - 1
// zeros) and then getting the class of this array. Handily for us,
// int arrays are initialised to all zero, so we can create one and
// use it straight away.
int[] allZeroDimensions = new int[dimension - 1];
componentType = Array.newInstance(int.class, allZeroDimensions).getClass();
}
// Create the new array.
int length = Array.getLength(booleanArray);
Object newArray = Array.newInstance(componentType, length);
// Transfer the elements, recursively if necessary.
for (int i = 0; i < length; ++i) {
if (dimension == 1) {
Boolean value = (Boolean)Array.get(booleanArray, i);
Array.set(newArray, i, (value.booleanValue()) ? 1 : 0);
}
else {
Object oldChildArray = Array.get(booleanArray, i);
Object newChildArray = transferToIntArray(oldChildArray, dimension - 1);
Array.set(newArray, i, newChildArray);
}
}
return newArray;
}
// Transfers a boolean array of some dimension into an int
// array of the same dimension.
public static Object transferToIntArray(Object booleanArray) {
if (booleanArray == null) {
return null;
}
int dimension = getArrayDimension(booleanArray);
return transferToIntArray(booleanArray, dimension);
}
}
This should work with any number of dimensions up to 255 - I gave it a quick test with 5 and it seemed to work. It should also work with 'jagged' arrays, and with nulls.
To use it, call ArrayTransfer.transferToIntArray(...) with your boolean array, and it will return the corresponding int array. You will of course need to cast the return value of this method to the relevant int array type.
There's certainly scope for improving this. In particular, it would be nicer if some cache of the various array classes was kept, rather than having to instantiate empty arrays just to get their class.
You can use a conditional recursivity on the type of the passed parameter and you use convert1dToInt for the dimension one , then you collect the result in one object, in the given context you will be forced to pass just an object of type Object and return an Object then you cast it , here is a small code that present idea of the recursive function that just print the value of the elements in the array :
public static void convertDimN(Object o) {
if (o.getClass().isArray() && Array.get(o, 0).getClass().isArray()) {
// is o a two dimentional array
for (int i = 0; i < Array.getLength(o); i++) {
convertDimN(Array.get(o, i));
}
} else
for (int i = 0; i < Array.getLength(o); i++) {
System.out.println(Array.get(o, i));
}
}
This would be your first method:
public static int[] convert1dToInt (boolean[] x) {
//int la = x.length; is useless since you are accessing an object member and not a method
int[] y = new int[x.length];
for (int a = 0; a < x.length; a++) {
y[a] = x[a] ? 1 :0;
}
return y;
}
Simply reuse your code - I had not much time since it is my lunch break so I don#t know if all is correct but the way should fit:
public static int[][] convert2dToInt (boolean[][] x) {
int[][] y = new int[x.length][];
for (int a = 0; a < x.length; a++) {
y[a] = convert1dToInt (x[a]) ;
}
return y;
}
Ok, this solution was not the answer for the problem since I did not read exactly what has been asked. Sorry for that. As far as I know a generalized method is not possible as long as you are working with primitive datatypes. This is because you can't add an int[] as a member for an int[]. So you should then work with Object[], Boolean[] and Integer[] but I don't know how you want to work with that. I don't think it is sensible to write such a method because when you are able to convert such a data-structure how do you want the targets to be accessed. Since you do not know how many dimensions your array will have you can't write generic methods to access the members. I will try to write a solution for that since I want to know if I find an other possible solution. Am I right that the question is, if it is possible and not if it is reasonable?
I think we can find the best solution for that if you tell us the usecase you want to have this code for. As I said, when I have more time later on I'll try to find another solution.
I am just consfused on how to implement these two methods like how call them or use them? Since the first one is void how does it work?
someone please use and an array and implement this for me or help me understand how the first void method works?
public static void insertionsort(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int copyNumber = numbers[i];
int j = i;
while (j > 0 && copyNumber < numbers[j-1]) {
numbers[j] = numbers[j-1];
j--;
}
numbers[j] = copyNumber;
}
}
public int[] InsertionSort(int[] data){
int len = data.length;
int key = 0;
int i = 0;
for(int j = 1;j<len;j++){
key = data[j];
i = j-1;
while(i>=0 && data[i]>key){
data[i+1] = data[i];
i = i-1;
data[i+1]=key;
}
}
return data;
}
A function with return type does something (executes code) and returns some result back to the code that called that function. A function without return type executes some code but does not return a result ( because it is not needed in most cases )
Consider this two functions:
public static int withResult( int someParameter)
{
//execute some code here
int someReturnValue = //result of the code above
return someReturnValue;
}
public static void withoutResult( int someParameter)
{
//execute some code here which produces no result which could be of interest to the caller (calling code)
} //end the function without returning anything
You would call it like this:
int result;
result = withResult( 1234 );//executes the function and stores its return type in 'result'
withResult( 468 );//executes the function but does not store the return type anywhere ("throws it away")
withoutResult ( 1234 );//simply executes the function
result = withoutResult ( 5678 ); //this makes no sense because the function does not return anything
In java everything is passed by value, including references. In your void method, the value of a reference to the array is passed. So while you cannot assign a new int [] to numbers, you are able to change the ints in numbers.
The first method, returning void (i.e., not returning anything) is passed an array as a parameter. What is passed is a reference to an array that is declared and for which memory is allocated outside the method. The method sorts that information in place; when the method returns, the data in that array is then sorted.
int[] myArray = getArrayInfo(); // assume this gets data in an array
WhateverClass.insertionSort(myArray); // this will sort that data
// at this point, myArray will be sorted