• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Green Exam 2 question 48

 
Leon Webster
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the question:
Question 48)
Given the following variables
char c = 'c';
int i = 10;
double d = 10;
long l = 1;
String s = "Hello";
Which of the following will compile without error?
1)c=c+i;
2)s+=i;
3)i+=s;
4)c+=s;

Marcus says the only correct answer is 2. However, I am also able to successfully compile and execute answer 1. When I run it, I get the answer "m". Am I missing anything here?
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried some test code just to double check and Marcus is correct.
1. False, c gets promoted to an int and then you try to assign back to a char.
2. True
3. False, trying to make string into an int
4. False, trying to make a string into a char
Try this code and see what you get:

If you are making it work, then post your code that is doing it so we can take a look at it.
Bill
 
Leon Webster
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OOPs.
I saw (and coded) "c += i" rather than c = c+i;
Here is the code:
public class MyTest{
char c = 'c';
int i = 10;
public static void main(String[] args){
MyTest mt = new MyTest();
mt.c += mt.i;
System.out.println(mt.c);
}
}
Sorry for the confusion.
Leon
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No problem, easy one to make a mistake. Points out how += has an implicit cast back to the original value so char += int will work becuase it is the same as saying char = (char)(char + int)

Bill
 
sthorat
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However the string concatenation operator works only for string objects. Can you use it for concatening string and integer as in
s+=i?
Thanks
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sthorat,
You can use the shortcut += with String objects as long as you are forcing it back to a String so you can say:
String += int
but you can't say:
int += String
The reason is that whenever you use the "+" operator with a String object you get a String object as a result and you can cast a primitive to an object.
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic