Parse Unsigned Integer

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to parse a string value as an unsigned decimal Integer using the parseUnsignedInt() method in Java. We will go through the syntax, parameters, and return types of the method, and learn how to use it with the help of some examples.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/recursion("`Recursion`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/recursion -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/scope -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/generics -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/class_methods -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/exceptions -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/modifiers -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/oop -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/packages_api -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/user_input -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/wrapper_classes -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/identifier -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/comments -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/data_types -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/for_loop -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/operators -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/output -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/strings -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/variables -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/string_methods -.-> lab-117944{{"`Parse Unsigned Integer`"}} java/system_methods -.-> lab-117944{{"`Parse Unsigned Integer`"}} end

Create a new Java file

First, we need to create a new Java file in the ~/project directory. We can do this by opening the terminal and typing:

touch ~/project/UnsignedIntegerParser.java

This will open up a blank Nano editor window.

Import the Integer class

We need to import the Integer class of the java.lang package, as it contains the parseUnsignedInt() method. We can do this by adding the following code inside our file:

import java.lang.Integer;

Parse unsigned integer from a string value

Now, let's learn how to use the parseUnsignedInt() method. We can call this method on a string value and it will return its equivalent unsigned decimal Integer object. Here's an example:

String s = "123";
int n = Integer.parseUnsignedInt(s); //Converts the passed string as unsigned integer
System.out.println(n);

The output of this code will be 123.

Handling invalid input

If we provide invalid input to parseUnsignedInt() method, it will throw a NumberFormatException. We can handle this exception using a try-catch block. Here's an example:

try {
  String s = "-123";
  int n = Integer.parseUnsignedInt(s); //Converts the passed string as unsigned integer
  System.out.println(n);
} catch(NumberFormatException ex) {
  System.out.println("Invalid input.");
}

In this code, we are trying to parse a negative integer, which is invalid. The parseUnsignedInt() method will throw a NumberFormatException, which is caught by the catch block. The output of this code will be Invalid input..

Reading input from console

We can also read input from the console and parse it as an unsigned integer. Here's an example:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
String s = scanner.nextLine();
try {
  int n = Integer.parseUnsignedInt(s); //Converts the passed string as unsigned integer
  System.out.println(n);
} catch(NumberFormatException ex) {
  System.out.println("Invalid input.");
}

In this code, we are using the Scanner class to read input from the console. We are then parsing the input string as an unsigned integer using the parseUnsignedInt() method. Finally, we are catching any exceptions that may occur while parsing the input.

To run this code in the terminal, we need to first compile it using the command:

javac UnsignedIntegerParser.java

Then, we can run it using the command:

java UnsignedIntegerParser

Parsing unsigned integers from a list of strings

We can also parse unsigned integers from a list of strings. Here's an example:

List<String> stringList = Arrays.asList("123", "456", "789");
for (String s : stringList) {
  try {
    int n = Integer.parseUnsignedInt(s); //Converts the passed string as unsigned integer
    System.out.println(n);
  } catch(NumberFormatException ex) {
    System.out.println("Invalid input: " + s);
  }
}

In this code, we are iterating over a list of strings and parsing each string as an unsigned integer using the parseUnsignedInt() method. If the string is not a valid unsigned integer, we catch the exception and print an error message.

Using a helper function

To avoid repeating the same try-catch block every time we parse an unsigned integer, we can create a helper function that takes a string as input and returns an unsigned integer. Here's an example:

public static int parseUnsignedInt(String s) {
  try {
    return Integer.parseUnsignedInt(s); //Converts the passed string as unsigned integer
  } catch(NumberFormatException ex) {
    return -1; //Return -1 for invalid input
  }
}

In this code, we are defining a parseUnsignedInt() function that takes a string as input and returns an unsigned integer. If the input is not a valid unsigned integer, the function returns -1. We can then use this function to parse unsigned integers without worrying about exceptions. Here's an example of how to use the function:

String s = "123";
int n = parseUnsignedInt(s);
System.out.println(n); //Output: 123

s = "-123";
n = parseUnsignedInt(s);
System.out.println(n); //Output: -1

Handling larger unsigned integers

If we need to parse larger unsigned integers, we can use the parseUnsignedInt() method of the UnsignedInteger class instead of the Integer class. This method returns a long instead of an int. Here's an example:

String s = "4294967295"; //Maximum value of an unsigned 32-bit integer
long n = Long.parseUnsignedLong(s);
System.out.println(n); //Output: 4294967295

Using Radix

If we want to parse a string that represents a number in a radix other than 10, we can use the parseInt() method that takes an extra radix parameter. Here's an example:

String s = "1101"; //Binary representation of 13
int n = Integer.parseUnsignedInt(s, 2); //Parse as binary
System.out.println(n); //Output: 13

Exiting Nano and running the code

To exit Nano, press Ctrl+X, then press Y to save the file, and then press Enter.

To run the code in the terminal, we can compile it using the command:

javac UnsignedIntegerParser.java

Then, we can run it using the command:

java UnsignedIntegerParser

Summary

In this lab, we learned how to parse a string value as an unsigned decimal Integer using the parseUnsignedInt() method in Java. We also learned how to handle invalid input, read input from the console, parse unsigned integers from a list of strings, and use helper functions. We also learned how to parse larger unsigned integers, use radix, and run our code in the terminal.

Other Java Tutorials you may like