This question already has answers here:
If a char array is an Object in Java, why does printing it not display its hash code?
(6 answers)
Closed 5 years ago.
When I run the following code I get the address of the array:
int arr[] = {2,5,3};
System.out.println(arr); // [I#3fe993
But when I declare a character array and print it the same way it gives me the actual content of the array. Why?
char ch[] = {'a','b','c'};
System.out.println(ch); // abc
Class PrintStream (which is what System.out is) has a dedicated method overload println(char[]) which prints the characters of a char array.
It has no special overloads for other arrays, so when you pass an int[] the called method is println(Object). That method converts the passed object to a string by calling its toString() method.
The toString() method for all arrays is simply the default one inherited from class Object, which displays their class name and default hashcode, which is why it's not so informative. You can use Arrays.toString(int[]) to get a string representation of your int array's contents.
P.S. Contrary to what the doc says, the default hashcode of an object is not typically the object's address, but a randomly generated number.
When you say
System.out.println(ch);
It results in a call to print(char[] s) then println()
The JavaDoc for println says:
Prints a character and then terminate the line. This method behaves as though it invokes print(char) and then println().
A integer variable is not char, so the print(int[] s) get the address of array.
Related
This question already has answers here:
how can I get the String from hashCode
(4 answers)
Closed 3 years ago.
I need to somehow get the text from its hash in java.
I have this code:
String myString = new String("creashaks organzine");
int hashCode = myString.hashCode();
System.out.println("Hash:" + hashCode);
The result of this code will be 0.
But the hash of "pollinating sandboxes" string will also be 0.
There might be collisions, for example with "creashaks organzine" and "pollinating sandboxes" and I want to find collisions like in this case.
Since i don't have enough reputation to add comment, i will quote solution from another question
You know that several objects can have same hash(), as it mentioned in java doc for Object.hashCode()
It is not required that if two objects are unequal
* according to the {#link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {#code hashCode} method on each of the
* two objects must produce distinct integer results.
It's obvious you can't restore different objects from same hash code, so it's impossible at all, simple logic.
how can I get the String from hashCode
This is a very interesting thing. Regarding the specification in https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#hashCode() says that the hashCode is calculated from the string content but the example seems to shows that is not true for the first string:
class Main
{
public static void main(String[] args)
{
String myString1 = "creashaks organzine";
String myString2 = "crsomething else";
String myString3 = "crsomething else";
System.out.println("Hash1:" + myString1.hashCode());
System.out.println("Hash2:" + myString2.hashCode());
System.out.println("Hash3:" + myString3.hashCode());
}
}
Outputs:
Hash1:0
Hash2:444616526
Hash3:444616526
But when I modify the string, then I get a different output:
String myString1 = "creashaks organzine...";
System.out.println("Hash1:" + myString1.hashCode());
Outputs:
Hash1:45678
So it seems that somebody tricked us by giving a very rare example string that produced exactly the "0" as output. Here you see that the hashCode is not very unique, so you cannot use is safely to compare strings.
Coming back to your initial question: The hashCode is a number with reduced details, so you cannot calculate it back to the original string. This applies to all hash codes.
Hash codes are so often used in server side databases instead of real password strings. They can be compared but not reconstructed.
This question already has answers here:
String valueOf vs concatenation with empty string
(10 answers)
Closed 5 years ago.
I want to know the difference in two approaches. There are some old codes on which I'm working now, where they are setting primitive values to a String value by concatenating with an empty String "".
obj.setSomeString("" + primitiveVariable);
But in this link Size of empty Java String it says that If you're creating a separate empty string for each instance, then obviously that will take more memory.
So I thought of using valueOf method in String class. I checked the documentation String.valueOf() it says If the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So which one is the better way
obj.setSomeString("" + primitiveVariable);
obj.setSomeString(String.valueOf(primitiveVariable));
The above described process of is done within a List iteration which is having a size of more than 600, and is expected to increase in future.
When you do "" that is not going to create an Object. It is going to create a String literal. There is a differenc(How can a string be initialized using " "?) actually.
Coming to your actual question,
From String concatenation docs
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
So unnecissarly you are creating StringBuilder object and then that is giving another String object.
However valueOf directly give you a String object. Just go for it.
Besides the performance, just think generally. Why you concatenating with empty string, when actually you want to convert the int to String :)
Q. So which one is the better way
A. obj.setSomeString(String.valueOf(primitiveVariable)) is usually the better way. It's neater and more domestic. This prints the value of primitiveVariable as a String, whereas the other prints it as an int value. The second way is more of a "hack," and less organized.
The other way to do it is to use Integer.toString(primitiveVariable), which is basically the same as String.valueOf.
Also look at this post and this one too
Why does my toString method have an error?
String score1 = Arrays.toString(newGame.top3Score[0]);
I am trying to take out the array value then convert them into strings.
Arrays.toString is expecting an array, yet you are only passing one element, try using:
Arrays.toString(newgame.top3Score)
This question already has answers here:
Reversing a String with Recursion in Java
(17 answers)
Closed 8 years ago.
This piece of code reverses string parameter passed to it. I know that string is immutable. I seem not to understand what is going on. Where does it store the reversed string that it returns.
public static String reverseRecursively(String str) {
//base case to handle one char string and empty string
if (str.length() < 2) {
return str;
}
return reverseRecursively(str.substring(1)) + str.charAt(0);
}
Your reverseRecursively(str.substring(1)) + str.charAt(0) creates a new String object every time it is called.
Where does it store the reversed string that it returns.
As the method shows, it calls itself recursively. Each time it is called it would add entries to the call stack. So, read about how the call stack works if you are concerned with the magic about where these "intermediate" results are stored.
Here is a call diagram that illustrates data flow:
Vector source of the image
Each call returns a copy of string with first character placed last and rest being processed by further calls. References to these strings are stored on stack which grows with each call (more stack space is required to handle longer strings).
Whenever I try to print the char arrays to the console, I'm getting the result in integer format, but whenever I try to print integer arrays to the console, I'm getting the result in hashcode format. Could anyone please tell me why?
char[] arr={'4','5','6'};
System.out.println(arr); //456
int[] arr={4,5,6};
System.out.println(arr) //[I#3e25a5]
java.io.PrintStream (the class of System.out) has a special print-method for char[], but not for int[]. So for the char[], this special method is used, while int[] is printed via the generic version, which prints the hashcode (or, to be more precise, the result of String.valueOf() called with the object as parameter).
Simply because there's no method for which handles int[] specially. It would be printed by String#valueOf() instead which implicitly calls Object#toString(). If the Object#toString() isn't overridden in the given object type, then the following will get printed (as per the aforelinked API).
getClass().getName() + '#' + Integer.toHexString(hashCode())
The int[] class has a name of [I.
To achieve what you want, you need Arrays#toString() instead:
int[] arr = {4, 5, 6};
System.out.println(Arrays.toString(arr)); // [4, 5, 6]
In the first case the character array is just used like a string (which is in fact also just an array of characters).
In the second it has no overload for the type of integer array and just prints out the object reference.
I think that the first one is treated as a CharSequence... like a String.