jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Bit shifting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Bit shifting" Watch "Bit shifting" New topic

Bit shifting

vinita Kh
Ranch Hand

Joined: Feb 19, 2002
Posts: 49
Marcus Green Test-II
nebody plz explain y 2 and 4 are correct and how
Given the following variables which of the following lines will compile without error?
String s = "Hello";
long l = 99;
double d = 1.11;
int i = 1;
int j = 0;
1) j= i <<s;
2) j= i<<j;
3) j=i<<d;
Mag Hoehme
Ranch Hand

Joined: Apr 07, 2002
Posts: 194
Hi Vinita,
This one is about primitive types.
The rule is very simple:
Both operands must be integral types (see JLS, � 15.19).
1.) second operand is a string - false
2.) both operands are integers - ok
3.) second operand is a double, which is not an integral - false
4.) both operands are integral types (first is integer, second is long) - ok
Integral types are:
  • byte
  • short
  • char
  • integer
  • long
  • All other data types are not integral types.
  • float and long are floating-point types
  • boolean is a type of its own
  • all other types are objects

  • Please correct me, if I've got something wrong.
    [ May 08, 2002: Message edited by: Mag Hoehme ]

    Manish Hatwalne
    Ranch Hand

    Joined: Sep 22, 2001
    Posts: 2591

    When LHS of the shift operator is an int only lower 5 bits of the RHS are used.
    Option 2 as it is is straight forward, and for option 4 if you need to apply the rule above.
    - Manish
    vinita Kh
    Ranch Hand

    Joined: Feb 19, 2002
    Posts: 49
    Hi everybody,
    though its a silly question
    I understand option 1 and 3 are wrong.
    but i can't understand how 2 & 4 are correct.
    If i'm not wrong whenever we left shift a number it gets doubled, so in case of option 4---
    j = i<<1, result that means i<<1 should be 2 , then how its equal to j.
    in option 2--
    j = i<<j, how to calculate this?
    Travis Benning
    Ranch Hand

    Joined: Jan 24, 2002
    Posts: 74
    i don't think it is saying j "equals" i<<l, its saying that j "becomes" i<<l.
    Hope this answers your problem. if not, I must have misunderstood you. Sorry.
    Travis B.

    Sun Certified Programmer for Java 2 Platform
    Mag Hoehme
    Ranch Hand

    Joined: Apr 07, 2002
    Posts: 194
    Hi Vinita,
    the question of the Marcus Green exam is about types allowed in shift operations.
    Are you sure that you do not mix up EQUALS (==) and ASSIGNMENT operators (=)?
    I agree. Here's the link: http://aspose.com/file-tools
    subject: Bit shifting
    It's not a secret anymore!