Introduction
The Java Long.toString()
method is used to convert a Long
object to its equivalent string representation. This lab will guide us on how to use the Long.toString()
method in our Java programs.
The Java Long.toString()
method is used to convert a Long
object to its equivalent string representation. This lab will guide us on how to use the Long.toString()
method in our Java programs.
Declare a variable of type Long
and initialize it with a value.
Long longValue = 123456789L;
Use the Long.toString()
method to convert the Long
variable to a string representation.
String strValue = Long.toString(longValue);
Print the string representation of the Long
variable using the System.out.println()
method.
System.out.println("String representation of longValue: " + strValue);
Save the file and navigate to the ~/project
directory in the terminal. Compile the program using the following command:
javac LongToString.java
Execute the program using the following command:
java LongToString
The output should be:
String representation of longValue: 123456789
Update the program to use user input to assign a value to the Long
variable.
Scanner scanner = new Scanner(System.in);
Long longValue = scanner.nextLong();
String strValue = Long.toString(longValue);
System.out.println("String representation of longValue: " + strValue);
Save the updated file and compile the program using the following command:
javac LongToString.java
Execute the program using the following command:
java LongToString
Enter a long value when prompted and verify that the program outputs the correct string representation of that value.
Update the program to use a negative value and verify that the output is correct.
Long longValue = -123456789L;
String strValue = Long.toString(longValue);
System.out.println("String representation of longValue: " + strValue);
Save the updated file and compile the program using the following command:
javac LongToString.java
Execute the program using the following command:
java LongToString
Verify that the program outputs the correct string representation of the negative value.
Update the program to use the maximum and minimum values of a Long
and verify that the output is correct.
Long maxValue = Long.MAX_VALUE;
Long minValue = Long.MIN_VALUE;
String strMaxValue = Long.toString(maxValue);
String strMinValue = Long.toString(minValue);
System.out.println("String representation of maxValue: " + strMaxValue);
System.out.println("String representation of minValue: " + strMinValue);
Save the updated file and compile the program using the following command:
javac LongToString.java
Execute the program using the following command:
java LongToString
Verify that the program outputs the correct string representation of the maximum and minimum values.
Congratulations! You have successfully learned how to use the Long.toString()
method in your Java programs. The Long.toString()
method is a useful utility method to convert a Long
object to its string representation.