Array reference explanation - java

For the code
int []arr = new int[4];
System.out.println(arr);
The output looks something like
[I#54640b25
What exactly is the compiler printing out? The memory address of arr? Unlike C, Java does not seem to equate the array name (in isolation) with the first position of the array.

In Java, each object has toString() method, and arrays are objects. The default is displaying the class name representation, then adding "#" and then the hashcode:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object
Try to print the following line and you should get the same output:
int[] arr = new int[5];
System.out.println(arr.getClass().getName() + "#" + Integer.toHexString(arr.hashCode()));

Use the following in order to print the value of array:
Arrays.toString(arr);
Using System.out.println(arr) directory will print use the default toString method which returns:
object.getClass().getName() + "#" + Integer.toHexString(object.hashCode())

Related

How to convert weird output of an array which printed to a file to its original value?

I have a char array that wrote in a file without any converting. the printed value to my file is [C#252ccf04 now I'm reading the file and this thing is being read as a string. now the retrieved data is [C#252ccf04 but this time it's a string. my problem is I want to assign it to another char array so I can read it using the Arrays.toString() method to reach the original value which is 123456 how can I accomplish that?
char[] pass = (data.substring(data.lastIndexOf(',') + 1).replaceAll(" ", "")).toCharArray();
System.out.println(Arrays.toString(pass));
// now the is: [[, C, #, 2, 5, 2, c, c, f, 0, 4]
and also I want to know what is this value what should I call it, is this a hashcode?
The value is the hashcode(as hex) plus the name of the class. According to the default toString() implementation:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
You can't convert it back to the original character array. The hash code identifies the object while it is alive in memory. Once the program ends and the object dies, you can't get it back from the hashcode.
You should have saved the actual data as a String, or encrypted it yourself.

In Java, why the output of int a=('a'+'b'+'c'); are different form System.out.println('a'+'b'+'c'+"")

the original question is like this.
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3' + "";
System.out.println(i);
}
}
and this gives me an error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to int
then I changed the code like this:
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3';
System.out.println(i);
}
}
the out put is 150.
but when I write my code like this:
public class test {
public static void main(String[] args){
System.out.println('a'+'b'+'c'+"");
}
}
the output become 294.
I wonder why.
The first one does not compile, because you concatenate a String at the end which cause the value to be a String which can't be converted directly to int.
The output of the second one is 150, because ASCII value for character 1,2,3 are 49,50,51 which return 150 when doing the addition.
The output of the last one is 294, because you are doing an addition of char values in the ASCII table (97+98+99)
You can verify the values here for a,b and c (or any other character).
Edit : To explain why the last one output the correct value instead of throwing an error, you first sum all the values as explained before, then convert it to a String adding "" to the sum of the ASCII values of the chars. However, the println method expect a String which is why it does not throw any error.
The first one would work if you would do Integer.parseInt('1' + '2' + '3' + "");
When you do this
int i = '1' + '2' + '3';
the JVM sums the ASCII codes of the given numbers. The result is 150.
When you add the empty String, you are trying to sum an int/char with a String. This is not possible. You can implicitly convert char to int and vice versa because they are primitive types. You cannot do this with String objects because they are not primitives but references. That's why you get an error.
When you do the println the primitive values are firstly summed and the automatically boxed into reference type so the sum is boxed into a Character object. The empty String is converted to a Character and then is added to the first one. So the result is a Character object that has an ASCII code 294. Then the toString method of the Character is called because that's what the println(Object) method does. And the result is 294
I hope this will help you to understand what is happening :)
The first is impossible because you can't convert String to int this way.
The second works because chars are kind of numbers, so adding chars is adding the numbers they really are. Char '1' is the number 49 (see ASCII table), so the sum is 49+50+51 which is 150.
The third works this way because + is a left parenthesized operator, which means that 'a'+'b'+'c'+"" should be read as (('a'+'b')+'c')+"". 'a' has ASCII code 97, so you have 294+"". Then Java knows that is should convert the value to a String to be able to catenate the two strings. At the end you have the the string 294. Modify your last code to the following System.out.println('a'+'b'+('c'+"")); and you will see that the result will be 195c.
You must note that System.out.println is a method that is used to convert values (of different types) to their String representation. This is always possible as every int can be converted to a String representation of it, but not the converse; not every String is a representation of an int (so Java will not let you do it so simply).
First: [int i = '1' + '2' + '3' + "";]
If you concat an empty string value, you convert it to a String object, and then String objects can't convert to int.
Second: [int i = '1' + '2' + '3';]
The binary arithmetic operations on char promote to int. It's equal to:
[int i = 49 + 50 + 51] - total: 150.
Third: [System.out.println('a'+'b'+'c'+"");]
At this case you convert 'a' + 'b' + 'c' (that is 294) to String (+"") and then print the result like a String value and that works ok.

Java - accessing characters in a string in a 2D-array-like manner?

Is there a more or less easy way (without having to implement it all by myself) to access characters in a string using a 2D array-like syntax?
For example:
"This is a string\nconsisting of\nthree lines"
Where you could access (read/write) the 'f' with something like myString[1][12] - second line, 13th row.
You can use the split() function. Assume your String is assigned to variable s, then
String[] temp = s.split("\n");
That returns an array where each array element is a string on its own new line. Then you can do
temp[1].charAt(3);
To access the 3rd letter (zero-based) of the first line (zero-based).
You could do it like this:
String myString = "This is a string\nconsisting of\nthree lines";
String myStringArr[] = myString.split("\n");
char myChar = myStringArr[1].charAt(12);
To modify character at positions in a string you can use StringBuffer
StringBuffer buf = new StringBuffer("hello");
buf.insert(3, 'F');
System.out.println("" + buf.toString());
buf.deleteCharAt(3);
System.out.println("" + buf.toString());
Other than that splitting into a 2D matrix should be self implemented.
Briefly, no. Your only option is to create an object that wraps and interpolates over that string, and then provide a suitable accessor method e.g.
new Paragraph(myString).get(1,12);
Note that you can't use the indexed operator [number] for anything other than arrays.

string to char array, showing silly characters

It is a really simple question but I need an another eye to look at my code:
String strtr = "iNo:";
char[] queryNo = strtr.toCharArray();
System.out.println(queryNo + " =this is no");
and the output is:
[C#177b4d3 =this is no
What are these characters, do you have any idea?
That's how toString() is implemented for arrays.
The [C denotes that is a char array, 177b4d3 is its hashcode.
You may want to look at
System.out.println(Arrays.toString(queryNo) + " =this is no");
if you want to see your original String again, you need this:
System.out.println((new String(queryNo)) + " =this is no");
Arrays do not override toString(), it is inherited from Object.toString as
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
you are printing the object
queryno, as queryno is a character array of on dimension and java is an object oriented language which holds every thing in the form of classes it gives the class name [C to your array where [ denotes total dimension and C denotes character type of array, Rest is the hashcode of the object.
You are trying to print the array and that is the reason you get gibberish. Try using Arrays.toString(queryNo) and you will see what you expected.

What does the output of a printed character array mean?

I'm moving from C to Java now and I was following some tutorials regarding Strings. At one point in the tutorials they showed instantiating a new string from a character array then printing the string. I was following along, but I wanted to print both the character array and the string so I tried this:
class Whatever {
public static void main(String args[]) {
char[] hello = { 'h', 'e', 'l', 'l', 'o', '.'};
String hello_str = new String(hello);
System.out.println(hello + " " + hello_str);
}
}
My output was something like this:
[C#9304b1 hello.
Clearly, this is not how you would print a character array in Java. However I'm wondering if I just got garbage? I read on some site that printing a character array give you an address, but that doesn't look like an address to me... I haven't found a lot online about it.
So, what did I just print?
and bonus questions:
How do you correctly print a character array in java?
However I'm wondering if I just got garbage?
No, you got the result of Object.toString(), which isn't overridden in arrays:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
So it's not garbage, in that it has a meaning... but it's not a particularly useful value, either.
And your bonus question...
How do you correctly print a character array in java?
Call Arrays.toString(char[]) to convert it to a string... or just
System.out.println(hello);
which will call println(char[]) instead, which converts it into a string. Note that Arrays.toString will build a string which is obviously an array of characters, whereas System.out.println(hello) is broadly equivalent to System.out.println(new String(hello))

Categories

Resources