Java Integer toUnsignedString Method

JavaJavaBeginner
Practice Now

Introduction

In Java, the Integer.toUnsignedString() method is used to convert an integer value into its equivalent unsigned String representation. This method returns the unsigned base 10 equivalent of the integer value passed as a parameter as a String.

Declare the UnsignedString class

In the UnsignedString.java file, declare the UnsignedString class:

public class UnsignedString {

}

Declare the main method

Declare the main method inside the UnsignedString class:

public static void main(String[] args) {

}

Declare an integer variable

Declare an integer variable inside the main method. This variable will hold the integer value that we want to convert to an unsigned String representation.

int num = 2147483647;

Convert integer to unsigned String

Use the Integer.toUnsignedString() method to convert the integer value to its equivalent unsigned String representation:

String unsignedNum = Integer.toUnsignedString(num);

Print the unsigned String

Print the unsigned String to the console:

System.out.println("Unsigned String value of " + num + " is " + unsignedNum);

Compile and run the program

Compile the UnsignedString.java file using the following command:

javac UnsignedString.java

Run the program using the following command:

java UnsignedString

Test with different values

Modify the value of num to test the Integer.toUnsignedString() method with different values.

int num = -2147483648;
String unsignedNum = Integer.toUnsignedString(num);
System.out.println("Unsigned String value of " + num + " is " + unsignedNum);

Test with user input

Modify the program to accept user input:

Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer value: ");
int num = sc.nextInt();
String unsignedNum = Integer.toUnsignedString(num);
System.out.println("Unsigned String value of " + num + " is " + unsignedNum);

Compile and run the program with user input

Compile and run the program with the following commands:

javac UnsignedString.java
java UnsignedString

When prompted, enter an integer value to test the Integer.toUnsignedString() method.

Summary

In this lab, we learned how to use the Integer.toUnsignedString() method in Java to convert an integer value to its equivalent unsigned String representation. We also learned how to test the method with different values and user input.

Other Java Tutorials you may like