Why won't my array print out correctly? [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I am trying to write a simple program using the code below to make a single dimensional array that you can then call a value from using the index numbers. I am using java and eclipse as my compiler. Whenever I try to debug or run the program, the full array prints out as this: [I#1fa8d3b.
class Array
{
public static void main(String[] args)
{
int[] MyArray = new int[] {15, 45, 34, 78, 65, 47, 90, 32, 54, 10};
System.out.println("The full array is:");
System.out.println(MyArray);
System.out.println("The 4th entry in the data is: " + MyArray[3]);
}
}
The correct data entry prints out when it is called though. I have tried to look for answers online as to what I should do, but I could not find anything that actually works. I am just starting to learn Java so there could be a very simple answer to this that I am just overlooking. If anyone has any ideas, I would be greatly appreciative.

Java is an object oriented language. When you are calling System.out.print(MyArray); in Java you are actually printing the address of the object on the heap in memory the toString code from it's parent class Object, the code is shown below contributed by the comment from EngFouad, sorry for misspeaking. The weird String you see printed out is the reference the computer uses to find your data when you ask for something associated with the variable MyArray.
As stated by the other answers, to print out the data of your object you can use the Array class's built in .toString() method. This will print the data from the object instead of just the object reference.
System.out.println(Arrays.toString(MyArray);
Correction
Actually it is toString() of the class Object: getClass().getName() + "#" + Integer.toHexString(hashCode()). – Eng.Fouad
Mistake above was corrected thanks for the comments, hate to give the wrong information. I misunderstood it myself. Here is the API reference to see the code:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#toString()

Use:
System.out.println(Arrays.toString(MyArray));
In order to print the array elements.
In your case you used the default Object.toString() implementation, which is not so informative...

Use this instead:
System.out.println(Arrays.toString(MyArray));
API Reference: Arrays.toString(int[])

to print the array you need to use the loop. for example:
for (int i: MyArray){
System.out.print(i + " ")}

Related

Why does the output for while (arar==arr){ arr[0]=2; } display this ([I#60e53b93)? [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 1 year ago.
I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.
What I do not understand is, if the compiler goes on and compiles it but displays [I#60e53b93 (which seems to me to be an address),
is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?
So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.
So what I basically did was:
int [] arr = {1,2,3,4,5,6};
int[]arar={1,2,3,4,5,6};
while (arar==arr){
arr[0]=2;
}
System.out.println(arr);
and so I was basically expecting a red flag but then the code ran and displayed [I#60e53b93 which I did not understand why?
Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?
Two things are going on here:
arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.
You can solve both problems by using static methods from Arrays:
while (Arrays.equals(arr, arar)) {
...
}
System.out.println(Arrays.toString(arr));
Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)
Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.
If you want to display the array contents, you have to loop over the array:
for(int elem : arr) {
System.out.println(elem);
}

Computing the nth Fibonacci number using linear recursion [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 3 years ago.
I have tried binary recursion to find the nth Fibonacci number (or the whole Fibonacci series by using a for loop in main()) but according to Data Structures and Algorithms in Java (6th Edition) by Michael T. Goodrich; it is a terribly inefficient method as it requires an exponential number of calls to the method. An efficient recursion technique is linear recursion given as follows;
/**Returns array containing the pair of Fibonacci numbers, F(n) and F(n-1)*/
public static long[] fibonacciGood(int n) {
if(n<=1) {
long[] answer = {n,0};
return answer;
}else {
long[] temp = fibonacciGood(n-1); //returns {F(n-1), F(n-2)
long[] answer = {temp[0]+temp[1], temp[0]}; //we want {F(n), F(n-1)}
return answer;
}
}
Whenever I run the code it returns a reference as
[J#15db9742
which is not the desired answer. What should I write in main() so that i can have the desired answer?
Try the one below. You can refer the api here.
public static void main(String[] args) {
System.out.println(Arrays.toString(fibonacciGood(4)));
}
You are trying to print out an array to the console, this is causing the memory address of the array to be output. You may want to iterate through the array returned, printing every element to get the desired output.
Here you are printing the array object, so you are getting these results. Internally it calls toString method of the object, which return getClass().getName() + "#" + Integer.toHexString(hashCode());. So you are getting value as [J#15db9742.
You can use convert is directly as below (Working in Java version 5 and above)
System.out.println(Arrays.toString(fibonacciGood(4)));
You can print it by converting it to list as below (in Java 8 or above) (Not Preferable to use streams here, but just for knowledge):
System.out.println(Arrays.stream(fibonacciGood(4)).boxed().collect(Collectors.toList()));

Weird output from array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I've come across what appears to be an interesting bug...
For one of my classes, I need to write a program that simulates the old "x students going down a hallway closing lockers every x interval" scenario. However, an interesting twist is that the question requires there to be an equal number of students and lockers up to 100. So I decided to use an array, where the user input a number - which is then used to set up the array size, for-loop conditions, etc. etc... you get the picture, right?
Anyway, my code compiles, but when run it puts out something like:
[I#36ae2282
Someone (in another thread/question/whatever-you-call-it) stated that this is the physical location of the array in the system memory, and to get the actual numbers from the array the .getNums() method would be required. My problem is: the .getNums() method doesn't seem to exist in Java (perhaps it's part of another language?), so what is the next best alternative or solution?
You're printing out the int array, and that's a traditional array's .toString() representation. You may want to use Arrays.toString() for nicer looking output instead.
To print the content of an array either iterate over each element in the array:
int[] array = new int[10];
for(int s : array) System.out.println(s);
// or
for(int i = 0; i < array.length; i++) System.out.println(array[i]);
or use Arrays.toString():
int[] array = new int[10];
System.out.println(Arrays.toString(array));
which will print something like:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Anyway, my code compiles, but when run it puts out something like:
[I#36ae2282
I assume you are trying to print the array like this:
int[] array = new int[10];
System.out.println(array);
array is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The array's toString() is similar to Object's toString():
getClass().getName() + "#" + Integer.toHexString(hashCode());
So the output would be something like:
[I#756a7c99
where [ represnts the depth of the array, and I refers to int. 756a7c99 is the value returned from hashCode() as a hex number.
Read also Class.getName() JavaDoc.

Problems with a Simple Array

I'm writing a very simple method for my programming class and ran in to an issue I can't find the resolution for in my notes.
You see I'm supposed to create a method that generates an array of an arbitrary length that has each consecutive value be a multiple of the last (interest rates). The problem is I can't find why my code doesn't work, it compiles but doesn't print what I'd like.
Instead of printing an array with something like (made up values):
[1, 5, 25, 125]
It prints out obscure text like:
[D#64bd4e3c or [D#7041a12f
Can someone please help? Below is a link to an image of my code:
My Code
System.out.print(Statements)
is essentially System.out.println(Statements.toString()) ;
It prints the address that Statements points to.
[D#64bd4e3c" or "[D#7041a12f" As you may have observed changes because the location of the array in memory changes. Hence the address is different or may be the same if reused.
You need to iterate through Statements.
In pseudocode:
for i to Statements.length
print Statements[i]
Here is a nice link to help you.
For printing arrays in java, use:
System.out.println(java.util.Arrays.toString(Statements));
Hope this helps!

How can I copy an array by value in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Make copy of array Java
I'm a beginner at Java and I need to copy the contents of one array into another variable. However, Java always passes the array by reference instead of by value.
Here's what I mean if that was confusing:
int test[]={1,2,3,4};
int test2[];
test2=test;
test2[2]=8;
for(int i=0;i<test2.length;i++)
System.out.print(test[i]); // Prints 1284 instead of 1234
In this example, I don't want the value of test to change. Is this possible without using any of the more advanced features of Java such as ArrayList and Vectors?
Edit: I tried System.ArrayCopy and test.clone(), but they still don't seem to work.
Here's my actual code:
temp_image=image.clone();
for(int a=0;a<image.length;a++)
for(int b=0;b<image[0].length;b++)
image[a][b]=temp_image[image.length-1-a][b];
Basically I'm trying to flip the "image" upside down. Is there an error somewhere in the code?
You need to clone your array.
test2=test.clone();
Starting in Java 6 you can use Arrays.copyOf:
test2 = Arrays.copyOf(test, test.length);
For what you're looking to do, test.clone() is fine. But if you wanted to do a resize, copyOf allows you to do that. I think in terms of performance it
System.arraycopy would give even more options if you needed them.
Because test and test2 are both pointers to the same array, you are changing the value of both test and test2 with your statement test2[2]=8
A solution would be to copy the contents of test into test 2 and change the value at the specific index of test2.
for (int i=0,i<test.length,i++)
test2[i]=test[i]
//Now both arrays have the same values
test2[2]=8
for (int j=0,j<test.length,j++)
System.out.print(test[i])
System.out.println()
System.out.print(test2[i])
Will output
1 2 3 4
1 2 8 4

Categories