Implement the Code
In this step, we will write code to demonstrate the working of the reverseBytes()
method.
Add the following code inside the main()
method to demonstrate the working of the method:
int a = 342;
int b = -23;
System.out.println("Original Number = " + a);
System.out.println("Binary Representation is = " + Integer.toBinaryString(a));
System.out.println("Number after reversal " + Integer.reverseBytes(a));
System.out.println("\nOriginal Number = " + b);
System.out.println("Binary Representation is = " + Integer.toBinaryString(b));
System.out.println("Number after reversal = " + Integer.reverseBytes(b));
We first define two integer variables, a
and b
. We then print out the original number, its binary representation, and the number obtained after reversing its bytes using the reverseBytes()
method. We do this for both a
and b
.
Next, we will take user input to demonstrate the reverseBytes()
method for user-defined values. Add the following code inside the main()
method:
try {
System.out.print("Enter Original Value: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Actual Number = " + i);
System.out.println("Binary Representation = " + Integer.toBinaryString(i));
System.out.println("After reversing = " + Integer.reverseBytes(i));
} catch(Exception e) {
System.out.println("Invalid Input");
}
Here, we define a try-catch
block to handle any exceptions that may arise. We take user input using the Scanner
class, print out the original number entered by the user, its binary representation, and the number obtained after reversing its bytes using the reverseBytes()
method.