+ 3
BagJava
Please can who explain code below Why output 7? String a = "101"; String b= "010"; Int a1 = Integer.parseInt(a, 2); Int a2 = Integer.parseInt(b, 2); in sum = a1 + b1; System.out.println(sum);
1 Answer
+ 2
Integer.parseInt(a,2);
^That is taking 101 and parsing it as base 2 / binary, which returns a value of 5. Likewise, the line below it is parsing 010 in the same way, and it is returning a value of 2. 5 + 2 is 7.
----------------------------------------
public class Program
{
public static void main(String[] args) {
String a = "101";
String b= "010";
int a1 = Integer.parseInt(a, 2);
int a2 = Integer.parseInt(b, 2);
int sum = a1 + a2;
System.out.println("(string) A = " + a);
System.out.println("(string) B = " + b);
System.out.println("(int) a1 = " + a1);
System.out.println("(int) a2 = " + a2);
System.out.println("a1 + a2 = " + sum);
}
}
OUTPUT::::::
(string) A = 101
(string) B = 010
(int) a1 = 5
(int) a2 = 2
a1 + a2 = 7