Introduction
In this lab, you will learn about the Java compareUnsigned() method of the Long class. This method is used to compare the unsigned value of two long values passed to find which one is greater than the other. You will learn to use the compareUnsigned() method step-by-step with practical examples.
Creating a Long Array
Create a Long array with four elements and initialize them with some values.
long[] numbers = { 100L, -200L, 300L, 100L };
Calling the compareUnsigned() Method
Call the compareUnsigned() method with the first two elements of the array numbers.
int result = Long.compareUnsigned(numbers[0], numbers[1]);
Displaying the Result
Display the result returned by the compareUnsigned() method on the console.
System.out.println("Result: " + result);
Repeating the Process
Repeat steps 2-3 using different pairs of elements from the array.
result = Long.compareUnsigned(numbers[1], numbers[2]);
System.out.println("Result: " + result);
result = Long.compareUnsigned(numbers[2], numbers[3]);
System.out.println("Result: " + result);
Accepting Input from the User
Accept two long values from the user using the Scanner class.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
long num1 = scanner.nextLong();
System.out.print("Enter second number: ");
long num2 = scanner.nextLong();
Comparing the Unsigned Values
Compare the unsigned values of num1 and num2 using the compareUnsigned() method.
result = Long.compareUnsigned(num1, num2);
Displaying the Result
Display the result of the comparison on the console.
if (result == 0) {
System.out.println("Both numbers are equal.");
} else if (result > 0) {
System.out.println("First number is greater.");
} else {
System.out.println("Second number is greater.");
}
Handling Exceptions
Use a try-catch block to handle exceptions that may occur while accepting input from the user.
try {
// Accept input and compare the values
} catch (Exception e) {
System.out.println("Invalid input: " + e.getMessage());
}
Compiling and Running the Code
Compile and run the CompareUnsigned.java file in the terminal to execute the program.
javac CompareUnsigned.java && java CompareUnsigned
Summary
In this lab, you learned how to use the Java compareUnsigned() method of the Long class to compare the unsigned values of two long values. You also learned how to use the Scanner class to accept user input, handle exceptions, and compile and run the program in the terminal.



