简体   繁体   中英

evaluating variable int/string

 int x = 20;


 double d = 3.1416;


 String s ="H";

those are my variables and I have to give the type the next lines evaluate to.

d/x + ""; 

is evaluating to double variable type (0.15708), is that correct?

You'd be right if we didn't have that pesky "" at the end!

Add "" to the end of something like this makes it into a String . It can actually be a handy shortcut - instead of having to use something like String.valueOf() , you could just do 4/2 + "" , which makes it into a string.

To reiterate,

d/x would be a double , since you are adding a floating point.

But a double + "" = String .

I hope that helps. Good luck :)

You are wrong. d/x + ""; is a String .

This happens because when you are using the + operator, if any of the 2 sides is a String , then string concatenation happens and of course the result is a String .

By the way you can check that indeed it is a String by using the getClass() method. Note that if you remove the "" and use the getClass() you will get an error. This happens because d/x is a double , ie a primitive type, so it can't use the method getClass() .

In your example:

System.out.println((d/x + "").getClass()); will return java.lang.String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM