Why would you do this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why would you do this?

I want to comment on some of Java challenge questions. Why would you ever do this: String s = new String("a"); instead of String s = "a"; And the same goes for integers, doubles ect. I think its just wrong to do this. Why do we make these wierd questions with code that would work but you would never actually do it that way?

14th Apr 2017, 10:23 PM
Martin Soukup
Martin Soukup - avatar
5 Answers
+ 11
It is not wrong, meaning the code compiles and runs without any errors. But it is not recommended for well known reasons. I'm shaking my head when I see this at challenges, but I don't report because there is no error in it.
14th Apr 2017, 10:51 PM
Tashi N
Tashi N - avatar
+ 5
@martin thank you for that explanation. i tried it in code playground and its true what you said about using new String creates a different memory address. i did not know that before so thanks
15th Apr 2017, 12:43 AM
Edward
+ 4
Sometimes they're written in seemingly strange ways so that you get a chance to be exposed to and understand something you may not have seen before. If you're going to be working in a professional environment some day, chances are you're going to be working with other people's code. Being able to read valid code is just as important as being able to write it. The challenges aren't meant to be practical; they're meant to challenge your knowledge of the language.
14th Apr 2017, 11:21 PM
Squidy
Squidy - avatar
+ 3
I don t think it s silly... String a = "hello"; String b = "hello"; "hello" is already a String so what you do is you re only assign "hello" to String a and String b and both atributtes refer to same memory address so basicly you only create "pointer" to that value but if you create String a = new String("a") and the same for String b you create separate objects and now every string is reffered from other memory location so yes in Java it is probably not the best to call new String() but it s not exactly the same.
14th Apr 2017, 11:27 PM
Martin Ďurčo
Martin Ďurčo - avatar
+ 2
@martin but what you are suggesting is still unnecesarry, even if your a and b strings point to the same object in memory, what is the problem of that? You never compare them with "==", you compare them with "equals" and if you then do a = "hi"; it will not affect the value of b
15th Apr 2017, 10:07 AM
Martin Soukup
Martin Soukup - avatar