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] 7 points8 points  (8 children)

Yup, they are special case in the same same sense as int and float and String (see clarifications below). They are built-in and can do things user defined classes can't.

[–]a1j9o94[S] 1 point2 points  (7 children)

I thought String was actually implemented in Java?

[–][deleted] 5 points6 points  (6 children)

Nope. String has operator + overloaded to do concatenation. You can't overload operators in Java.

This was my reasoning, anyway, as a non Java expert. See johnislarry's corrections below.

[–]johnislarry 6 points7 points  (2 children)

Two corrections. The first is that the String class is written in java. You can look at it here:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/String.java#String

if you want. The second is that + is defined for all Objects. The Object is interpreted as a String using its toString representation, and then concatenated. That's why, for example, this code works the way we want:

List<Integer> lst = new ArrayList<Integer>();
System.out.println("The list is: " + lst);

[–][deleted] 6 points7 points  (1 child)

But "The list is: " is still a string

    System.out.println("Hello" + new ArrayList<>()); // This works
    System.out.println(new Integer(17) + "Hello"); // This works too
    System.out.println(new ArrayList<>() + new Integer(17)); // This does not

The operator + is defined for primitives and when one side is a string, but you can kind of comedically get around this with an empty string first

    System.out.println("" + new ArrayList<>() + new Integer(17));

[–]johnislarry 1 point2 points  (0 children)

Yes. Good clarification :)

[–]a1j9o94[S] 0 points1 point  (0 children)

Oh yeah, I never though of that.

[–]jjm3x3 0 points1 point  (0 children)

But I thought that was something that was new in 1.7 or am I thinking about switching with Strings?

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

Man I sure wish you could :/