r/javahelp • u/LantumoMatrixer • Apr 16 '21
Unsolved I would like to know: why is there automatic conversion from string to int in Java when using the + operator?
You can see an example in the following video (second Java example)
6
u/whizvox Graduate and Tutor Apr 16 '21
Are you referring to
int y = 3;
String x = "5" + y;?
2
u/LantumoMatrixer Apr 16 '21
Yeah, exactly
8
u/whizvox Graduate and Tutor Apr 16 '21
Okay, because your title is backwards.
In any case, anything that isn't a string is automatically converted to one. I don't know exactly what is called, but I suspect it's
String.valueOf(Object).1
2
u/BS_in_BS Extreme Concrete Code Factorylet Apr 16 '21
officially it's documented as "string conversion": https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.11
The rules are, for any value:
primatives are boxed into references by calling the constructor of the wrapper class
reference have toString() called on them
if the reference or the output of toString() was
nullthen use the String"null"I haven't looked at generated bytecode to see if there's any optimizations.
0
u/ObscureCulturalMeme Apr 16 '21 edited Apr 17 '21
There is no such implicit string->int conversion defined in the language.
If you think that's what you're seeing, please post some code. I'm not going to a goddamn youtube video just to read text.
Be aware that + on string values is implemented with the String Builder class under the hood.
2
3
u/TheYTG123 Apr 16 '21
iirc since Java 9 it uses indy stuff instead of StringBuilder
1
1
u/wildjokers Apr 16 '21
Indy?
1
u/morhp Professional Developer Apr 17 '21
Abbreviation of "invoke dynamic", which is a new(ish) byte code.
0
u/khmarbaise Apr 17 '21
This is simply wrong because BS_in_BS has already mentioned the JLS references to that.
Furthermore the title is misleading...
If you take a deeper look at the code:
int y = 3; String x = "3" + y;What exactly will happen here? First you define an int and set the value to 3. Afterwards the string
xis defined where to add theint(y) to it. There is an implicit conversion (boxing called) for primitive types used like this it will result into calling thetoString()of the class which is implicitly the wrapper classIntegerwhich results in the following final result ofxwhich is equal to33which means it's in the end a string concatenation but not a conversion from string to int. The variableyis converted into a string.BTW: The constructor of more less all wrapper classes (JDK9+) are defined deprecated and should be replaced by calls to
Wrapper.valueOf(..)instead.1
u/ObscureCulturalMeme Apr 17 '21 edited Apr 17 '21
You are replying to the wrong person. What's more, none of that is a string to int conversion, which is what OP asked in the title and is what I answered. You seem to have reading comprehension problems. I'm putting you on ignore; stop pestering me.
1
u/HotRodLincoln Apr 16 '21
You mean why isn't there?
First, the Python style is un-tenable because all functions belong to objects in Java. They could've made the cast more featured, but they didn't. I assume the reason is casts must be verifiable at compile time, and a string isn't necessarily a valid Integer.
Also, by convention things get promoted to larger types that don't lose data automatically, and must be explicitly cast to smaller types that do lose data. So, "7" + 7 = 77 in a lot of languages. JavaScript returns CSS properties this way, so think Opacity += 0.1 and you end up trying to set it to 0.10.1 and causing error handling. The flip side is equally annoying: "High Score: " + Score throwing an invalid number Exception. You can only have one; so you pick your poison.
-8
u/TheYTG123 Apr 16 '21
There is no automatic conversion from String to int. There is automatic conversion from int to String though ("a" + 1).
Java is weakly typed. This is the nature of these kinds of languages, automatic conversions happen everywhere (though in Java 8 that’s implemented by StringBuilder, like u/ObscureCulturalMeme said).
6
u/Poddster Apr 16 '21
Since when is Java considered weekly typed?
(Also there are very few automatic conversions in Java. Only Strings and integer promotion come to mind.)
3
u/Roachmeister Java Dev Apr 16 '21
Java is absolutely not "weakly typed", is is the opposite. It is one of the most strongly typed languages that exist.
0
u/TheYTG123 Apr 16 '21
You might be confusing strongly typed and statically typed
1
u/Roachmeister Java Dev Apr 16 '21
There is no universally agreed definition for what "strongly typed" means, and it isn't really a binary distinction, it's more of a spectrum. That being said, a Google search for "is Java strongly typed" will return a yes answer from many sources.
1
•
u/AutoModerator Apr 16 '21
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.