IntelliJ Java IDE
The moose likes Mock Exam Errata and the fly likes Marcus Green Exam 2 question 48 Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Mock Exam Errata
Reply Bookmark "Marcus Green Exam 2 question 48" Watch "Marcus Green Exam 2 question 48" New topic
Author

Marcus Green Exam 2 question 48

Leon Webster
Greenhorn

Joined: Dec 06, 2000
Posts: 10
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

Joined: Jun 30, 2000
Posts: 1070
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

Joined: Dec 06, 2000
Posts: 10
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

Joined: Jun 30, 2000
Posts: 1070
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

Joined: Dec 26, 2000
Posts: 5
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

Joined: Jun 30, 2000
Posts: 1070
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
 
 
subject: Marcus Green Exam 2 question 48
 
Threads others viewed
why not i += s?
java
Marcus G exam 2 -33,48
primitive assignment
c+=i != c=c+i
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com