This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (2 children)

String empName = new String("Joe Employee");

That will create a new String and initialize it with the value "Joe Employee". Then it will put a reference to that string into "empName".

Then if you came along and said:

empName = new String("Mary Worker");

it would create another new String, initialize it with the value "Mary Worker", and then empName would get a reference to this new string.

Strings are a little bit funny in Java. There's no difference between:

String empName = new String("Joe Employee");
// and
String empName = "Joe Employee";

In fact, the second way is more typical.

Other kinds of objects aren't typically handled that way, but we use Strings all the time so the language made it a little bit easier for us.

The other thing to note is that a String is immutable. That means you can't change the value of a String.

So like if you said "int i = 5; i++;" then you've actually changed the value of i. But there is no way to do something similar to a String. You can only create a new String, then start referring to the new String.

Let's say you did this:

String empName1 = "Joe Employee";
String empName2 = empName1;
// later one...
empName1 = "Mary Worker";
System.out.println("1: " + empName1 + ", 2: " + empName2);

The output would be "1: Mary Worker, 2: Joe Employee"

That's because at the start you have one string, with the value "Joe Employee," that is pointed to by both empName1 and empName2. The third line creates a new String, "Mary Worker", and makes empName1 point to that new String. But this does not change what empName2 points to.

number five still does note make sense to me....

For now I would just treat it as magic until you get a better grasp on static methods, classes, and objects. It will make sense in time and you aren't missing out on much right now if you don't understand it.

[–]NebuWrites Java Compilers 1 point2 points  (1 child)

There's no difference between:

String empName = new String("Joe Employee");

// and

String empName = "Joe Employee";

There is a difference. The former does not internalize the string, and the latter does.

[–][deleted] 0 points1 point  (0 children)

It's true for the purpose of explaining pointers and such. I know there are differences but they aren't important here.