Introduction
This lab demonstrates the usage of the Java Long class' signum() method. The method returns the signum function value of a given long value.
This lab demonstrates the usage of the Java Long class' signum() method. The method returns the signum function value of a given long value.
Create a new Java file named SignumDemo.java and open it in a code editor.
touch ~/project/SignumDemo.java
In this step, you need to import the java.lang package to use the Long class. Add the following code to your SignumDemo.java file:
import java.lang.Long;
In this step, you will define a main method that will prompt the user to enter a long value and display its signum value. Add the following code to your SignumDemo.java file:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a long value: ");
long num = input.nextLong();
System.out.println("Signum value of " + num + " is " + Long.signum(num));
}
In this step, you need to compile the SignumDemo.java file using the javac command. Run the following command in your terminal:
javac SignumDemo.java
In this step, you will execute the program using the java command in the terminal. Run the following command in your terminal:
java SignumDemo
In this step, you can test the signum() method by entering different values of long. The program will display the signum value for the entered number.
For example, if you enter 7 as input, the program will display the following output:
Enter a long value: 7
Signum value of 7 is 1
Modify the code to include a loop that will prompt the user to enter a long value until they enter 0. Add the following code to your main() method:
long num = 1;
while (num != 0) {
System.out.print("Enter a long value (enter 0 to exit): ");
num = input.nextLong();
if (num == 0) {
continue;
}
System.out.println("Signum value of " + num + " is " + Long.signum(num));
}
Review the complete code for the SignumDemo.java file.
import java.lang.Long;
import java.util.Scanner;
public class SignumDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = 1;
while (num != 0) {
System.out.print("Enter a long value (enter 0 to exit): ");
num = input.nextLong();
if (num == 0) {
continue;
}
System.out.println("Signum value of " + num + " is " + Long.signum(num));
}
input.close();
}
}
Compile and Run the Java code by running the following command:
javac SignumDemo.java && java SignumDemo
In this lab, you learned how to use the Java Long class' signum() method. The method returns the signum function value of a given long value. The output of the method is 1, 0, or -1, for positive, zero, and negative numbers, respectively.