Java Int To String


Problem Overview

Original Problem: Java Int To String | Hackerrank

Difficulty: Easy

Category: Data Type Conversion

Description: We are given a single integer and our task is to convert this into a string and print a message depending on the success of the conversion.

Understanding the Problem

The task is straightforward: convert an integer into its equivalent string representation. Since Java provides built-in ways to convert an integer to a string, the task mainly tests understanding of basic type conversion and exception handling.

Input:

An integer between the values of -100 and 100

Output:

If the conversion to a string is successful, output “Good job”, otherwise “Wrong answer”

Initial Reasoning

Since Java allows direct reading of input using a Scanner, we could technically read the integer as a string. But this would bypass the purpose of practicing type conversion.

So instead, we will:

  • Read the integer as an int

  • Convert it to a String

  • Convert that String back to an int

  • Compare it to the original input

  • If both values match, the conversion is considered successful.

Pseudocode

// Main function:
	Read the integer 
	Convert the integer to a string 
	Convert the string to an integer 
	If the new integer and original integer are the same 
		Print “Good Job”
	Else 
		Print “Wrong Answer”

Solution Code

// Note this is one of many possible solutions
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read the integer input
        int number = scanner.nextInt();
        scanner.close();
        
        // Convert the integer to a string
        String string = Integer.toString(number);
        
        // Validate the conversion
        if (number == Integer.parseInt(string)) {
            // If the converted string correctly converts back to the original integer
            System.out.println("Good job");
        } else {
            System.out.println("Wrong answer");
        }
    }
}

Commenting on Alterations

While we have done our best to maintain similarity to the template code provided in the original problem, the following changes have been made to follow best practices:

  • Altered the program structure:

    The provided template code for this problem doesnt provide much explanation for the sections of code that a user is unable to edit. The original solution can be solved by providing a line such as the following in the editable section:

    • String s = Integer.toString(n);