The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Marcus exam question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Marcus exam question" Watch "Marcus exam question" New topic

Marcus exam question

kevin goon
Ranch Hand

Joined: Jun 12, 2001
Posts: 62
Hi, I have two Questions
Question 1)
This may be a trivial question but can somesome explain why below would work? (i thought 1 is int and since int is 32 bits, how can it fit without cast?)
char c = 1;
Also, explain below problem.
String s = "hello";
long L = 99;
double d = 1.11;
int i = 1;
int j = 0;
which work and WHY??
1. j=i << s;
2. j=i << j;
3. j=i << d;
4. j = i << L;
ans was 1&4 but please explain someone, what general rules are needed in bit shifting different types??
Thank you so much =)
Steven YaegerII
Ranch Hand

Joined: May 31, 2000
Posts: 182
A1) char c = 1; works cause a char is 16 bits and will fit into
a 32 bit int without the explicit cast. A smaller will
automatically fit into a bigger, but you must explicitly
(cast) a bigger into a smaller.
Question 2 looks like one that I have to study. Some links:

[This message has been edited by Steven YaegerII (edited June 14, 2001).]
[This message has been edited by Steven YaegerII (edited June 14, 2001).]
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
I think your mistaken, Kevin isn't putting a smaller char into an int he's putting the larger int into a smaller char.
Kevin, the reason it works is because in the code you have you're using a literal int value so at compile time the compiler knows that this will fit into the char c. The same thing with final variables. Look at the code below and it'll show some other examples that might clear it up...

Check out this in the jls section 5.2
In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:
The expression is a constant expression of type byte, short, char or int.
The type of the variable is byte, short, or char.
The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

hope that helps

[This message has been edited by Dave Vick (edited June 14, 2001).]

Bin Wang
Ranch Hand

Joined: May 01, 2001
Posts: 82
The answer for you second question is: 2 & 4.
String can not be the operand of bitshift operator.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
And a double must be cast to an int for (3) to work.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: Marcus exam question
It's not a secret anymore!