I\'m new to Java. What does the below mean?
(addition) + sign in println
System.out.println ("Count is: " + i);
In that context, the +
operator is acting as the string concatenation operator. It acts as a different operator in the context of two integral types, where addition will be performed.
Assuming i
is an integral type, it'll be converted to a String
and then added on to the end of a new string beginning with "Count is: "
. That new string is then printed.
ie. If i
had the value 0
, it'd be the same as:
"Count is: " + "0"
Which would be:
"Count is: 0"
It does exactly what it does outside the println method, id adds to objects:
if the objects are Strings it concatenates them:
"hello" + "world" --> "helloworld"
if the objects are numbers it adds the UNLESS there's a String to the left (or at least a String with higher precedence).
2 + 4 + "hello" --> "6hello"
"hello" + 2 + 4 --> "hello24"
"hello" + (2 + 4) --> "hello6"
if the object is any thing else it will treat them as Strings using the toString()
method
+
is string concatenation operator and it is used for conversion
of other objects to strings (based upon the implementation of toString() method) and also concatenate
two strings.
String str1="Hello";
String str2="World"
String result=str1 + " " + str2;
The + sign in the context of strings is the concatenation operator. It joins two strings together.
E.g.
String str = "hello" + "world";
would result in a String object called str, with a value of "helloworld".
The plus operator has a double meaning. Its a concatination operator as well. As the "Count is:" is of type String
the "i" (Integer
?) is converted to a String
as well.
I haven't read it as I prefer reference books, however some really like the Book Head First Java as it seems to explain concepts.
The + in arithmetic adds 2 numbers together, like this:
2 + 2 = 4
now apply the same thing to a string:
"hello " + "world!" = "hello world!"
now adding strings and variables will do this:
int number = 4;
String string = "what was the number? oh yeah: "+number;
System.out.println(string);
if all goes well you should get "what was the number? oh yeah: 4"
Java took the value of the variable and put it into the string for you, hope this helped!