r/javahelp • • Nov 15 '22

Simple java question I didn't know how to google.

I had someone ask me what is the difference between below code.

String x = new String("name");
String y = "name";

x.equals("name");
y.equals("name");

Basically someone asked me what is the difference between x and y and I couldn't tell.

37 Upvotes

22 comments sorted by

•

u/AutoModerator Nov 15 '22

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:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

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.

26

u/midnight_babyyy Nov 15 '22

The first one creates a new String instance every time the statement is invoked. The second one is just a String instance that gets assigned an address in the String Pool, and this instance reuse that same String literal everytime that it is executed.

14

u/pereza0 Nov 15 '22

Yep.

Basically, the first one is bad and unnecessary and can cause problems within loops because you are needlessly creating a bunch of new objects

13

u/p0pkern Nov 15 '22

Yeah this question seems to be focused on the String pool and the nuances of it.

This is creating a new String object on the heap.

String x = new String("name");

This is checking the String pool (a specialized area of memory to store Strings for referencing) for any literal that matches "name". If it is found y will reference the current address in the pool of "name" or it will be created and stored in the pool.

String y = "name";

Both of these will evaluate to true due to equals internally comparing each character.

y.equals("name");

x.equals("name:);

If you want a literal comparison between Strings then you'll want to default to using the .equals() method.

If you were to try to use the == comparator. They would evaluate to false because the address of x and y are different.

If interviewers really want to mess with you. They would throw .intern() into the mix. Intern is similar to creating a String literal. It will check the String pool for the existing String, and create it if it does not exist.

Thus

String x = new String("name");
String y = "name";
String z = x.intern();

y == z // true due to being a reference to the same area of String pool.
x == z // false one is an object on the heap, the other is the String pool.
x.equals(z) // true

3

u/iamk1ng Nov 16 '22

First time seeing the intern method, is there any real world uses to it?

2

u/roberp81 Nov 16 '22

if you want make sure you are no generating new string in memory yes. but intern is slow because need to search for that string in all string pool. so in most cases nobody have to use intern

2

u/p0pkern Nov 17 '22

Very niche cases where a) there are a lot of String values referenced and some are used repeatedly and you need space on the heap. b) performance issues that need to benefit from comparing Strings with == as opposed to .equals()

There are definite trade offs for ‘abusing’ the String pool. So it will be when performance/space is a bigger issue.

2

u/msx Nov 15 '22

there's no real difference, both equals return true. When creating X you're instantiatin an extra "String" object (internally pointing to the same data of "name" string), which is completely unnecessary. Since strings are immutable, it is semantically identical to writing x = "name".

Now if instead of "equals" you test for identity (with == ) things change a bit. But you should never test strings for identity.

3

u/D_Flavio Nov 15 '22

Strange cause it was a question at an interview from a java web app dev position from the team lead with apparently 15 years of java exp.

Im sure I got the code right since it was such a simple thing. I told him that I think the end result is the same, however him so specifically asking made me question myself(I said the end part aswell).

The question was probably more about what is happening in the bwckground and about memory allocation and stuff.

0

u/shishir-nsane Nov 15 '22

On a side note, if you don’t know how to search answer to your question then you haven’t understood your question.

4

u/D_Flavio Nov 15 '22

Im not ashamed to admit I did not understand hes question.

-1

u/shishir-nsane Nov 15 '22

The questions here you have is to know the difference between “string with constructor vs assignment”. And to know what happens with “object.equals”.

Both of these are important things to understand to program good.

While you learn about these, also learn the contract of “equals and hashcode”.

You can do a Google search now, perhaps.

1

u/Mammoth-Brilliant303 Nov 17 '22

Don't know why the downvotes because I agree with this and you aren't being mean or sassy here.

1

u/[deleted] Nov 15 '22

x.equals("name");

as a statement does absolutely nothing. the .equals() method is for comparison, not assignment.

for example, If you were to run this snippet what would you expect to happen?

String x = "meow";

x.equals("woof");

System.out.println(x);

hint: it doesn't print woof.

Also, creating a String with the new operator is bad form and should be avoided.

0

u/catladywitch Nov 15 '22

if you do String x = "name"; String y = "name"; then x == y is true, but if you do String x = new String("name"); String y = "name" then it's not.

2

u/your-fan888 Nov 15 '22

== is used for reference comparison. It doesn't compare the value. In second case value is false because of difference in memory locations

1

u/[deleted] Nov 30 '22

[removed] — view removed comment

1

u/D_Flavio Nov 30 '22

It was for a senior java software dev position at a huhe it consultancy company.

1

u/[deleted] Nov 30 '22

[removed] — view removed comment

1

u/D_Flavio Nov 30 '22

I think it was about how java handles memory and memory allocation. There are small differences there.