TransWikia.com

What does the & symbol mean here and whats going on here?

Stack Overflow Asked by Aarat Chopra on December 13, 2020

I was going through a java file and saw this block of code and can’t really understand what’s happening here. What does the & symbol means here and when I run this, I get the values 2 and 8 respectively.

package com.company;

public class Question_2 {

    public static void main(String[] args) {
        int mask = 0x000F;
        int value = 0x2222;
        int f = 90;
        int h = 9;
        System.out.println(value & mask);
        System.out.println(f & h);
    }
}

This is The output I get:

2
8

4 Answers

& is a bit wise operation

& is 1 if both bit at the same position is 1 otherwise 0

Also, to perform this operation, your operands will be converted to base 2

90 = 0101 1010 in base 2
09 = 0000 1001 in base 2
     _________
     0000 1000 which is 8 convert to decimal


  000f in hexadecimal =  0000 0000 0000 1111
  2222 in hexadecimal =  0010 0010 0010 0010
  using & on this is     0000 0000 0000 0010 which is 2 convert to decimal

That is how basic & operator works.

Answered by akeempositive on December 13, 2020

& is used as a relational operator to check a conditional statement just like && operator. but there is a small change in how & takes care of conditional statement. && would first check the first data, if its true then it checks the next one and son on.. but in case of single & character, it just evaluate all conditions even if previous one is a failed one. Thus, any change in the data values due to the conditions will only be reflected in this case.

& can also be used as bitwise operator

println(f & h ) ->

01011010

& 00001001 00001000 -> 8 in decimal

Answered by ashu on December 13, 2020

& is the bitwise AND operation.

System.out.println(value & mask);

outputs the hex representation of bitwise ANS.

System.out.println(f & h);

outputs the decimal representation of the bitwise AND.

& is smart enough to return the result of the same representation as it's arguments.

Answered by Edik Mkoyan on December 13, 2020

& refers to Bitwise AND operation.

the mask variable used to enable specific bit and disable the others.

in this code,

System.out.println(value & mask);

the mask keeps the first (from right to left) 4 bits and unsets the others, so always the value of the bitwise AND between the mask variable and any value will be less than 15 because 0x000F -> 0000 0000 0000 1111

mathematically: since the mask is 0x000F if the value of & between the mask and any value is zero then the number is dividable by 16 otherwise it's not dividable by 16

Answered by Waleed Jubeh on December 13, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP