Results 1 to 5 of 5
- 08-01-2012, 11:43 PM #1
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
Why does adding 1 to a int var within a println method treat as if they were string?
Why does this...
Add the 1 to i as if it was strings? I tried (i+1) also and still same result.Java Code:System.out.println("Die " + i + 1 + ": " + dieArray[i]);
So I tried this and it worked....Java Code:Die 01: 4 Die 11: 6 Die 21: 6 Die 31: 6 Die 41: 4
does this....Java Code:System.out.printf("\nDie %d: %d", i+1, dieArray[i]);
Java Code:Die 1: 4 Die 2: 5 Die 3: 2 Die 4: 1 Die 5: 6
- 08-01-2012, 11:54 PM #2
Student
- Join Date
- Jul 2012
- Location
- United States
- Posts
- 328
- Rep Power
- 1
Re: Why does adding 1 to a int var within a println method treat as if they were stri
This code should add the integer value of i to the integer value of 1 and print that value out:
I think that you may have mistyped something when you tried it before. I recommend that you try it again.Java Code:System.out.println("Die " + (i + 1) + ": " + dieArray[i]);"Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill
- 08-02-2012, 01:47 AM #3
Re: Why does adding 1 to a int var within a println method treat as if they were stri
Get in the habit of using standard Java naming conventions!
-
Re: Why does adding 1 to a int var within a println method treat as if they were stri
To answer your question, you need to dive into the Java Language Specification, or JLS, and in particular Section 5.4 on String conversion which states:
String conversion applies only to an operand of the binary + operator which is not a String when the other operand is a String.
In this single special case, the non-String operand to the + is converted to a String (§5.1.11) and evaluation of the + operator proceeds as specified in §15.18.1.
- 08-05-2012, 04:11 AM #5
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
Similar Threads
-
Why my cast has to be in println() method ?
By fatabass in forum New To JavaReplies: 6Last Post: 03-03-2012, 10:11 PM -
System.println(new String("Hi gang!"));
By LinuxDev@Flanders in forum IntroductionsReplies: 6Last Post: 02-18-2012, 09:28 AM -
How does System.out.println() method work?
By fatabass in forum New To JavaReplies: 4Last Post: 01-17-2012, 11:04 AM -
Converting a println out in to a method
By gcclinux in forum New To JavaReplies: 9Last Post: 04-01-2011, 10:02 AM -
difference between system.out.println() & out.println()
By wickedrahul9 in forum Advanced JavaReplies: 5Last Post: 10-18-2008, 11:06 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks