How come printing a string(an Object) in java prints it? - java

When we do:
String string = new String("Ralph");
//This creates a reference called string that points to a sequence of
//characters in memory
This is the same as:
String string = "Ralph";
When we print both, we get the actual value of the string.
If we print any other object in Java, we get an address for that object.
My question is, is there any dereferencing that is taking place behind the scenes?

When you pass an object reference to the System.out.println() method, for
example, the object's toString() method is called, and the returned value of toString() is shown in the following example:
public class HardToRead {
public static void main (String [] args) {
HardToRead h = new HardToRead();
System.out.println(h);
}
}
Running the HardToRead class gives us the lovely and meaningful,
% java HardToRead
HardToRead#a47e0
Now,
Trying to read this output might motivate you to override the toString()
method in your classes, for example,
public class BobTest {
public static void main (String[] args) {
Bob f = new Bob("GoBobGo", 19);
System.out.println(f);
}
}
class Bob {
int shoeSize;
String nickName;
Bob(String nickName, int shoeSize) {
this.shoeSize = shoeSize;
this.nickName = nickName;
}
public String toString() {
return ("I am a Bob, but you can call me " + nickName +". My shoe size is " + shoeSize);
}
}
This ought to be a bit more readable:
% java BobTest
I am a Bob, but you can call me GoBobGo. My shoe size is 19

The class String is a special class in Java.
But it gets out printed the same way every other class does.
If we call System.out.println("Ralph") the function println takes that String and then displays it.
The class Objects toString() method is implemented, so it displays the hash code of the Object, by calling the hashCode() function. If you overwrite the toString() method, it will display something else.
If you take any object other than a String and give it to a method that takes a String (or in fact cast it to a String) java will call the toString()method of that Object, to convert it to a String.
So 'printing' always does the same thing, it's just implemented in different ways, using the toString() method.

new String("Ralph") copies the character data array of the literal string and stores it in the new String instance.
However, you only get the address of an object when you print it because printing uses the toString() method of that object. If that method is not implemented, the default implementation defined in Object is used, which returns the class name plus the hash code (that seems like an address if hashCode() is not implemented).

I believe the primary types are printed with auto dereferencingString, int, float, etc., while the objects other than primary types, only with de-referencing function object.toString() that are implemented on the object level.

Related

How to change the displayed name of an object in an ArrayList [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I want to change an element name in an ArrayList, without changing its value.
Like :-
ArrayList<Integer> array1 = new ArrayList<>();
int num = 1;
array1.add(num);
Now I want to change num to number, but it's value will be 1.
(Is it possible?)
I want to display all the elements in a ArrayList in a swing combo box, but some of the variables show strange names, such as "Client#45673...". But I want the user to see a descriptive name. That is why I want to rename the variables.
OK, so you are wandering up the proverbial garden path with your "change the name of a variable".
Firstly, it is not a variable. When you put something into a collection, Java doesn't remember that at one point you had the value in a variable.
Secondly, values in general and objects in particular don't have names ... unless you specifically implemented some kind of "name" field as part the class definition.
But I think the clue is in this sentence:
... but some of the variables show strange names, such as "Client#45673..."
That's not a name! That looks like the output of the default implementation1 of toString that your Client class is inheriting from java.lang.Object.
If you want to print / display something something more meaningful, your Client class needs to override the toString() method with its own implementation.
For example:
public class Client {
private String myDescription;
public Client(...) {
...
myDescription = /* something */
}
#Override
public String toString() {
return myDescription;
}
}
Your toString method can return anything you want it to ... so long as it is represented as a string.
Incidentally, if you were to print the array1 object in your question, you would see the actual value 1 rather than a "name" (as you called it). This is because java.lang.Integer overrides the toString() method.
1 - The default toString() result consists of the internal class name and the object's identity hashcode value. The latter is a magic number that the JVM generates. It is not guaranteed unique, but it is guaranteed that it won't change for the lifetime of the object. At any rate, you cannot alter the string that is generated by that method ... except by overriding it.
What you're talking about is the output when printing an object. Those objects need to override toString() and return whatever string is deemed appropriate that describes the class or the contents thereof.
Try this.
class Foo {
//#Override
//public String toString() {
// return "This is a foo";
//}
}
Foo f = new Foo();
System.out.println(f);
Now uncomment the toString() method and print it again.
To print arrays, one way is to use Arrays.toString()
int[] arr = {1,2,3,4};
System.out.println(Arrays.toString(arr));

After override hashCode, toString() return the same value for the same object but after using "==" return false

As you may know Object has some function,
For example we have toString() from oracle Documentacion we can know by default it's return HexValue of hashCode()
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()
We also can use hashCode() for checking of equality object (of course implementation depends on you)
So I made implementation for my Class Projekt :
public class Projekt {
int i;
public Projekt(int i) {
this.i=i;
// TODO Auto-generated constructor stub
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + i;
return result;
}
}
Test Code:
Projekt projekt = new Projekt(1);
System.out.println(projekt.toString());
System.out.println(projekt.toString() == projekt.toString());
Output:
Projekt#20
false
Also i try to inside value from projekt.toString() in StringPool by writing:
String string = projekt.toString();
String stringABC = projekt.toString();
System.out.println(string == stringABC);
According to PoolString i should have the same reference but outPrint is false.
So this method return different reference value but i can't understand why?
From your comment:
I copied this from diffrent comenatry: But to save memory we're using StringPool. If we have the same value, refereance is also the same it's working just for creating String not by constructor. If i had String s = new String("a"); String s2 = new String("a"); I used 2 space in memory, but when i use String s = "a"; String s2 = "a" I use 1 space in memory. So that's mean toString() return "new String()"?
Your source should have said:
...it's working just for creating String using string literals.
That way it might have been clearer, because there are many ways to create new String objects without directly calling the constructor. String literals are those things surrounded by " (including the quotes), such as "a" or "b" or "Welcome to Stack Overflow".
Only string literals1 are pooled automatically. You can manually put a string into the pool by calling intern().
When you concatenate two strings (e.g. stringA + stringB), a new string is generally created, as described here.
Now let's look at what Object.toString does:
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())
Note that strings are being concatenated here, so a new string object is being created here, hence the output.
And to answer the question of:
So that's mean toString() return "new String()"?
Yes, but not directly. The compiler will turn the + operators in Object.toString into some code using StringBuilder (or rather, "the compiler has turned..." since the Object class has already been compiled). At the end, it will call StringBuilder.toString, and that will create a new String object.
1Constant expressions of strings, to be more accurate.
This is because "toString()" method returns a string. So everytime you call toString() it returns a new reference because Strings are immutable (even if they're the same text)
String class is just a pointer to string (char) data somewhere in the memory. It is a class, it is not a primitive type like boolean, byte, char, short, int, long, float and double.
So, comparing two strings you compare pointers.
You generate two strings in:
String string = projekt.toString();
String stringABC = projekt.toString();
So you have 2 different pointers now. They have the same text inside, but they are in different places in memory.
But you can use equals() method of object:
System.out.println(string.equals(stringABC));

Create an object and print it out but turns out printing the reference. How to solve this?

Hi I was looking at another post on stackoverflow about objects, instances.
I tried out some code.
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println(name);
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy("Tommy");
Puppy myPuppy2 = new Puppy ("Sally");
System.out.println(myPuppy);
}
}
The output is
Tommy
Sally
Puppy#58886ad0
Question:
when I try to print out the object myPuppy in the main method, it prints out its reference instead of the value? How should I solve this?
Also, some mentioned that I did not actually store the puppy's name and I need to write a override toString method to print out the value instead of the reference.
How should I accomplish the above?
Thanks a lot!
You have to implement toString() on Puppy...
#Override
public String toString() {
return "Puppy[name=" + name + "]";
}
Obviously, make the String it returns suit your needs.
Edit: And as others have mentioned, make sure you actually store the name when constructing a Puppy.
Well make sure you're referencing the specific variable within the Puppy so in order to best do this you'll need to make a "name" variable in the puppy class and then System.out.println(myPuppy.name); or somethign to that effect, because as it is you're not actually storing the puppy's name
With that last System.out.println you enter a object as parameter. What you get back (Puppy#58886ad0) is a object reference.
To get value you have to override the toString
Resulting in:
#Override
public String toString() {
return "Puppy's name: " + name;
}
Every object as a toString methode, but this will most of time give a refernce back, by overwriting it java will use your version of toString().

What happens when printing an object in java

class Data {
int a = 5;
}
class Main {
public static void main(String[] args) {
int b=5;
Data dObj = new Data();
System.out.println(dObj);
System.out.println(b);
}
}
I want to know what's happening when printing a object or number or string.
I ran the above code, I'm getting the result as "data#1ae73783" for System.out.println(dObj); and "5" for System.out.println(b);
Then I did debug to check whats really happening when printing a object, there was lot of parameter called in a debug mode(like classloader,theards)
I know for the first print the value represent class name followed by address. But don't know what's really happening in debug mode, for the 2nd print only variable assignment happened in the debug mode i.e b=5.
Please explain whats really happening?
You don't need a debugger to know what's happening. System.out is of type PrintStream. The javadoc of PrintStream.println(Object) says:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
The javadoc of String.valueOf(Object) says:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
And the javadoc of Object.toString() says:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
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())
Please explain whats really happening?
As other have told you, using System.out.println with an object will call to toString method on that object. If the class doesn't have it's own toString method, then it's a call to the super class's toString. If the super class call goes all the way back to java.lang.Object, the default toString method prints the name of the object's type (what class it is), followed by an # sign, and the memory location of the object--the hexidecimal address of where that object is stored in memory.
ClassName#MemoryLocation
when we print object of any class System.out.print() gives string of class name along with memory address of object (ClassName#MemoryAdress)
All objects inherit from java.lang.Object which has a default implementation of toString. If an object overrides this method then out.print (obj) will put something useful on the screen.
Primitive data types are handled by a different, much simpler implementation of println. The println method is overridden for every data type in addition to Object.
First, int isn't an Object. It's primitive type.
Second, when Class haven't overrived toString() method, toString() from Object class is invoked.
data dObj = new data() does not exist in the source code;
you want to print the string value of the object (Data), you have to override the toString method;
try this
public class Program {
public static void main(String[] args) {
Data data = new Data();
System.out.println(data);
}
}
class Data {
int a = 5;
#Override
public String toString() {
return String.valueOf(a);
}
}
In Addition to #JB Nizet answer,
To Provide our own string representation, we have to override toString() in our class which is highly recommended because
There are some classes in which toString() is overridden already to get the proper string representation.
Examle: String, StringBuffer, StringBuilder and all wrapper classes
Integer ob1 = new Integer("10");
String ob2 = new String("Doltan Roy");
StringBuffer ob3 = new StringBuffer("The Rock");
StringBuilder ob4 = new StringBuilder("The Joshua");
System.out.println(ob1);
System.out.println(ob2);
System.out.println(ob3);
System.out.println(ob4);
Output:
10
Doltan Roy
The Rock
The Joshua
Hope this would help!

when to use toString() method

This may sound very basic... can someone please explain the use of the toString() method and when to effectively use this?
Have done a search on google but could not find any good resource.
In most languages, toString or the equivalent method just guarantees that an object can be represented textually.
This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.
Objects often implement custom toString behavior so that the method actually tells you something about the object instance. For example, a Person class might override it to return "Last name, First name" while a Date class will show the date formatted according to some default setting (such as the current user interface culture).
There are several situations in which one would wish to override the toString method of a class (most of which are already mentioned in the existing answers), but one of the most common situations in which I have needed to explicitly call toString on an object is when using StringBuilder to construct a String.
public String createString(final String str) {
final StringBuilder sb = new StringBuilder(str);
sb.append("foo");
sb.append("bar");
return sb.toString();
}
You want to display an object and don't want to check if it is null before.
You want to concat Strings and not thinking about a special attribute, just provide a default one to the programmer.
Thus:
out.println("You are " + user);
will display "You are null" or "You are James" if user is null or toString displays "James" for this (existent) instance.
Assuming .NET or Java:
In general, you should overload ToString() when you want a textual representation of your class (assuming it makes sense for your class).
You can use toString() on an class by overriding it to provide some meaningful text representation of your object.
For example you may override toString() on a Person class to return the first and last name.
To string is should be used when you have a need to change a data type to a string. For built in types like int and such there string representations are what you expect. ie
int i = 5;
string s = i.ToString(); //s now equals "5"
Gives you the character string "5" for most complex types and all user created types you need to overload the tostring method or you will only get the name of the class. To string allows you to use the complex formating build into .net with your own objects. you can provide complex formatters like the datetime class does to give flexibility in using your own types.
toString() can be used to avoid the hexadecimal address, so to overcome this problem you need to override toString() then you will get original text format of data.
When you print reference variable then following task will happen.
if reference variable contains null then null value will be displayed.
if reference variable contains address of an object then toString() Method will be called by the JVM automatically.
By default toString() of Object.class will print:
ClassName#HexadecimalOfHashCode
You can override this method in your class to display some meaningful String.
Usually toString() method is used to print contents of an object.This method is already overridden in many java built-in class like String,StringBuffer,integer etc.
It used when we have to display the field values which we initialize through constructor and what to display without using any getter.
import Test.Date;
public class Employ {
private String firstname;
private String lastname;
private Date DOB;
private Date DOH;
public Employ(String name,String lastname,Date DOB,Date DOH)
{
this.firstname=name;
this.lastname=lastname;
this.DOB=DOB;
this.DOH=DOH;
}
public String toString(){
return String.format("%s %s Birthday %s Hired %s",firstname,lastname,DOB,DOH);
}
public static void main (String args[])
{
Date dob= new Date(12,3,1992);
Date doh= new Date(10,6,2005);
Employ em= new Employ("BOB", "Wrigh", dob,doh);
System.out.println(em);
}
}

Categories

Resources