﻿ Java exercises: Convert a binary number to decimal number - w3resource # Java Exercises: Convert a binary number to decimal number

## Java Basic: Exercise-22 with Solution

Write a Java program to convert a binary number to decimal number.

Binary number: A binary number is a number expressed in the base-2 numeral system or binary numeral system. This system uses only two symbols: typically 1 (one) and 0 (zero).

Decimal number: The decimal numeral system is the standard system for denoting integer and non-integer numbers. It is also called base-ten positional numeral system.

Pictorial Presentation: Binary to Decimal number Sample Solution:

Java Code:

``````import java.util.Scanner;
public class Exercise22 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
long binaryNumber, decimalNumber = 0, j = 1, remainder;
System.out.print("Input a binary number: ");
binaryNumber = sc.nextLong();

while (binaryNumber != 0)
{
remainder = binaryNumber % 10;
decimalNumber = decimalNumber + remainder * j;
j = j * 2;
binaryNumber = binaryNumber / 10;
}
System.out.println("Decimal Number: " + decimalNumber);
}
}
```
```

Sample Output:

```Input a binary number: 100
Decimal Number: 4
```

Flowchart: Java Code Editor:

What is the difficulty level of this exercise?

﻿

## Java: Tips of the Day

initial:

Returns all the elements of an array except the last one. Use Arrays.copyOfRange() to return all except the last one

```public static <T> T[] initial(T[] elements) {
return Arrays.copyOfRange(elements, 0, elements.length - 1);
}
```

Ref: https://bit.ly/3zEKw9u