int value converted to Integer Wrapper class object with System.out.println? - java

This more of a clarity than a doubt. In the following :
int a = 10;
System.out.println(a);
What I conclude is that variable 'a' of the primitive type int is first converted to the Integer Wrapper class object and then toString method is invoked for that Integer object which returns the integer value in String form to the println method. Is my understanding correct? If not what is the correct explanation?

You're wrong. It can handle int, see the docs*:
public void println(int x)
* Always :)

If you check the type of System.out, you'll see it's a PrintStream. Read the docs.
Quote:
public void println(int x)
Prints an integer and then terminate the line. This method behaves
as though it invokes print(int) and then println().
Parameters:
x - The int to be printed.
So, no, no conversion to Integer is done. The int matches the signature of the above method exactly, so that method is called. What happens internally is unspecified, but it probably calls Integer.toString() directly, with out a conversion to Integer.

No i think it's not the way you explained.
System.out is a static reference of PrintStream class (present in java.io package) which has methods to print primitives directly!!!

To be precise, it actually uses the String.valueOf(int) method.
This is the source code, from PrintStream
/**
* Prints the string representation of the int {#code i} followed by a newline.
*/
public void println(int i) {
println(String.valueOf(i));
}

Related

Why does the new Integer act as value type int?

public static void main(String []args){
Integer a = new Integer(9);
d(a);
System.out.print(a) ;
}
public static void d(int z){
z=z+2;
}
or suppose I write
public static void main(String []args){
int a = 9;
d(a);
System.out.print(a) ;
}
public static void d(int z){
z=z+2;
}
but the output is the same for both: 9. Can anyone explain me in detail why?
Because JAVA is PASS BY VALUE not PASS BY REFERENCE.
Let us understand it this way,
Your main function has a local variable z whose scope is limited to main only
and your d function has another local variable z whose scope is limited to d only
So, in your d fucntion, you are basically creating a new integer literal 11 and putting it to local variable z whose scope is limited to d function only and not the variable z of main.
In your code with Integer a process called unboxing occurs. The Integer-instance is unboxed to a primitive int when calling your method d. See this to better understand how autoboxing and unboxing works.
As for your z=z+2 inside the method d. Java objects are passed-by-reference, but Java primitives or Immutable objects (like Strings) are passed-by-value. Since your method d has a primitive parameter int it's passed-by-value in this case. Your z=z+2 isn't returned however.
If you would add System.out.println(z); right after z=z+2 it will indeed print 11. So why isn't the a in your main-method changed to 11 and how can you accomplish this? As I mentioned, it's passed-by-value for primitives. You'll need to return the new value and set the a in the main method with it. If you change your code to this it will work:
public static void main(String []args){
int a = 9;
a = d(a);
System.out.print(a);
}
public static int d(int z){
return z+2;
}
Try it online.
As you can see, the void d is changed to int d, and we return the result of z+2. We then overwrite the value of a with this new result with a = d(a); in the main-method.
Java has a concept of AutoBoxing and Auto unboxing for primitive datatypes.
Since primitves like int, float double, long etc are technically not objects, they have their corresponding Classes which can be instantiated with the primitive value to treat them as objects.
So to reduce the pain, java automatically converts int to Integer and Integer to int where ever applicable.
If you are wondering why the addition value has not reflected, though it is an Integer object on performing addition, a new int object will be resulted. so it wont reflect directly. You can return the value from the method you call and assign to it.
Java passes variables by value, not by reference. If you think that passing an object and changing the value of its data member would work, it won't. In that case, too, a copy of that object will be passed, not the original object. The only solution is to declare the variable as static that can be changed from anywhere.
it's all because of Autoboxing and Unboxing feature of java which provide the functionality of converting primitive to object(Wrapper) type and vice-versa. for better understanding you can check here
. I hope it will clear all your doubts.

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!

What is the exact difference between out.write() and out.print()

In my servlet I gave both out.print and out.write. but both prints in the browser.
What is the exact difference between these two and when to use out.print and out.write ?
The short answer is that out.write() explodes if you pass it a null:
String s = null;
out.print(s); // outputs the text "null"
out.write(s); // NullPointerException
The more complete answer is that out in servlets is a PrintWriter whose overloaded write() methods only accept a few basic types but do the work of outputting bytes to the underlying OutputStream.
The print() method is a convenience wrapper method that wraps calls to write() to provide custom behaviour for its numerous overloaded implementations. For example:
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
public void print(Object obj) {
write(String.valueOf(obj));
}
public void print(double d) {
write(String.valueOf(d));
}
etc for all the primitive types.
There are three major differences:
1) If you try to print a null value of a String with out.write() , It will throw NullPointerException while out.print() will simply print NULL as a string.
String name = null;
out.write(name); // NullPointerException
out.print(name); // 'Null' as text will be printed
2) out.print() can print Boolean values but out.write() can not.
boolean b = true;
out.write(b); // Compilation error
out.print(b); // 'true' will be printed
3) If you are using out.write(), you simply can not place arithmetic operation code but out.print() provides the support.
out.write(10+20); // No output will be displayed.
out.print(10+20); // Output '30' will be displayed.
PrintWriter:
public void write(String s)
Write a string. This method cannot be inherited from the Writer class
because it must suppress I/O exceptions.
print method has higher level of abstraction.
public void print(String s)
Print a string. If the argument is null then the string "null" is
printed. Otherwise, the string's characters are converted into bytes
according to the platform's default character encoding, and these
bytes are written in exactly the manner of the write(int) method.
Hope this helps.
The out variable in your case is most likely refers to a PrintWriter
Just compare the description of write...
public void write(String s)
Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.
... with the description of println ...
public void println(String x)
Print a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
... and print ...
public void print(String s)
Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
All in all I'd say that the print methods work on a higher level of abstraction and is the one I prefer to work with when writing servlets.
PrintWriter's implementation communicates the difference better than javadoc
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
First thing is you can't use javax.​servlet.​jsp.​JspWriter out in a servlet. It has to be used in a .jsp file, because out is a method local variable in _jspService(...) method of your .jsp file.
There is no difference in the purpose of using out.print() and out.write(). Both are used to write the String version of the given object to JspWriter's buffer.
However, JspWriter.print() is capable of taking many types of arguments than Writer.write().
JspWriter.print()
Object
String
boolean
char
char[]
double
float
int
long
Writer.write()
String
char
int
write() method only writes characters to stream(or console) but does not print, while print() method writes and print it on stream (or console).
System.out.write(97);
System.out.print('j');
first statement writes character 97 i.e 'a' on console but does not print, while second statement prints 'a' which is written already on stream and 'j' which is passed in print() method.
I simply know it as like this:
out.println() is method of javax.​servlet.​jsp.​JspWriter
out.write() is method of java.io.Writer
out.write(-) vs out.print(-)
One more difference is out.write(-)
method just write data or object to browser like a file. You can not write any statement like out.write(10*20); but we do this with out.print(10*20);

Convert Integer, Double to String in Java

Which of the following ways is better to convert Integer, Double to String in Java.
String.valueOf(doubleVal)
doubleVal + ""
doubleVal.toString()
Thanks.
doubleVal + "" is most likely the worst since it has to do a concatanation with an empty string. However, the other two are equivalent. The source code from OpenJDK:
// java.lang.String
public static String valueOf(double d) {
return Double.toString(d);
}
// java.lang.Double
public static String toString(double d) {
return new FloatingDecimal(d).toJavaFormatString();
}
I don't think there's a performance difference. Go for the most readable!
The first one is exactly equivalent to doublevar.toString() (check the javadoc). The second one is more suited for concatenating longer strings.
If you need to format the way your number is represented as a String, you anyway need to look into other classes
The first and the third are good, the second is bad.
The reason that the second is bad is because the code doesn't show what you want to do. The code says that you want to concatentate the value with an empty string, when you actually want only the conversion that happens before the concatenation.
I prefer to use Integer.toString(int), when you use String.valueOf(int), it internally calls to Integer.toString(int) (same with long, float and double). But for readability, it would be better to use String.valueOf()
There are slight semantic differences depending on whether you're using the primitive double type, or its object wrapper Double.
Anything that will work for a primitive double will also work for the object wrapped Double, but the opposite will not work. (That is, a primitive double will not be accepted if the parameter is of type Double.)
Also, the Double type's value may be null, but the primitive double type cannot.
Beyond that, there isn't much difference at all. For the code snippets you've provided, there isn't any worth really talking about.
i) String.valueOf(int i)
ii) Integer.toString(int i)
After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)
Just two different ways of doing the same thing
In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for double
Double.toString(dobule d)
and so on
In my opinion this is not some historical thing, but is more useful for developer to use the method valueOf from String class than from proper type, because is less changes to make when we want to change the type that we operate on.
Sample 1:
public String doStaff(int num) {
//Do something with num
return String.valueOf(num);
}
Sample2:
public String doStaff(int num) {
//Do somenthing with num
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
My conclusion is that using the valueOf method from String class is more flexible and that why is available there.
From the official source:
public static String valueOf(double d) {
return Double.toString(d);
}
So the first and the third are not really different, as long as doubleVal is double and not Double. This is because in the case of a Double, you will call
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
The second is certainly worse because of the need to concatenate.
CONCLUSION:
Following the question, I must assume that the most efficient way is to call the toString() method.
Java string.valueOf() method converts different types of value such as long,int,double,float into String.
Double double_val=45.9;
String string_conversion=String.valueOf(double_val);

Integer.toString(int i) vs String.valueOf(int i) in Java

I am wondering why the method String.valueOf(int i) exists ? I am using this method to convert int into String and just discovered the Integer.toString(int i) method.
After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)
In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for integers we have
Integer.toString(int i)
for double
Double.toString(double d)
and so on
In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf from the String class than from the proper type, as it leads to fewer changes for us to make when we want to change the type that we are operating on.
Sample 1:
public String doStuff(int num) {
// Do something with num...
return String.valueOf(num);
}
Sample2:
public String doStuff(int num) {
// Do something with num...
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
In my conclusion, using the valueOf method from String class is more flexible and that's why it is available there.
One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.
Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).
The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.
NB Profiling results
Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)
public class StringIntTest {
public static long intToString () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = Integer.toString(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static long stringValueOf () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = String.valueOf(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static void main(String[] args) {
long intToStringElapsed = 0;
long stringValueOfElapsed = 0;
for (int i = 0; i < 10; i++) {
intToStringElapsed += intToString();
stringValueOfElapsed+= stringValueOf();
}
System.out.println("Average intToString = "+ (intToStringElapsed /10));
System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
}
}
From the Java sources:
/**
* Returns the string representation of the {#code int} argument.
* <p>
* The representation is exactly the one returned by the
* {#code Integer.toString} method of one argument.
*
* #param i an {#code int}.
* #return a string representation of the {#code int} argument.
* #see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
So they give exactly the same result and one in fact calls the other. String.valueOf is more flexible if you might change the type later.
If you look at the source code for the String class, it actually calls Integer.toString() when you call valueOf().
That being said, Integer.toString() might be a tad faster if the method calls aren't optimized at compile time (which they probably are).
The implementation of String.valueOf() that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString() method of one argument."
To answer the OPs question, it's simply a helper wrapper to have the other call, and comes down to style choice and that is it. I think there's a lot of misinformation here and the best thing a Java developer can do is look at the implementation for each method, it's one or two clicks away in any IDE. You will clearly see that String.valueOf(int) is simply calling Integer.toString(int) for you.
Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object). Only difference is one extra call, which the compiler eliminates to a single call anyway.
So it matters not which you call, other than maybe code-consistency. As to the comments about nulls, it takes a primitive, therefore it can not be null! You will get a compile-time error if you don't initialize the int being passed. So there is no difference in how it handles nulls as they're non-existent in this case.
You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.
Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String, then various calls to String.valueOf(SomeType) may be more readable than various SomeType.toString calls.
my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.
There have no differences between Integer.toString(5) and String.valueOf(5);
because String.valueOf returns:
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String valueOf(float f) {
return Float.toString(f);
}
etc..
Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :
static String valueOf()
using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..
Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string.
So, its better to use String.valueOf() for such convertions.
If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.
String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..
So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.
Conclusion: String.valueOf() method has its importance just at cost of one more call.

Categories

Resources