Open In App

Program to check if input is an integer or a string

Last Updated : 24 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a function to check whether a given input is an integer or a string.

Definition of an integer : 
Every element should be a valid digit, i.e ‘0-9’.

Definition of a string : 
Any one element should be an invalid digit, i.e any symbol other than ‘0-9’.

Examples: 

Input : 127
Output : Integer
Explanation : All digits are in the range '0-9'.
Input : 199.7
Output : String
Explanation : A dot is present.
Input : 122B
Output : String
Explanation : A alphabet is present.

Method 1: The idea is to use isdigit() function and is_numeric() function.. 

Algorithm:

1. Take input string from user.

2. Initialize a flag variable “isNumber” as true.

3. For each character in the input string:
              a. If the character is not a digit, set the “isNumber” flag to false and break the loop.

4. If the “isNumber” flag is true, print “Integer.”

5. If the “isNumber” flag is false, print “String.”

Pseudocode:

inputString = readString()
isNumber = true
for character in inputString:
if !isdigit(character):

isNumber = false
break
if isNumber:
print "Integer"
else:
print "String"

Below is the implementation of the above idea. 

C++
#include <iostream>
#include <string>
using namespace std;

// Returns true if s is a number else false
bool isNumber(const string& s)
{
    for (char c : s) {
        if (!isdigit(c)) {
            return false;
        }
    }
    return true;
}

// Driver code
int main()
{
    // Saving the input in a string
    string str = "6790";

    // Function returns true if all characters
    // are in the range '0-9'
    if (isNumber(str)) {
        cout << "Integer";
    } else {
        cout << "String";
    }

    return 0;
}
Java
public class Main {

    // Returns true if s is a number else false
    static boolean isNumber(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (!Character.isDigit(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    // Driver code
    public static void main(String[] args) {
        // Saving the input in a string
        String str = "6790";

        // Function returns true if all characters
        // are in the range '0' - '9'
        if (isNumber(str)) {
            System.out.println("Integer");
        } else {
            System.out.println("String");
        }
    }
}
Python
# Python 3 program to check if a given string
# is a valid integer

# This function returns True if s is a number else False
def isNumber(s):
    for char in s:
        if not char.isdigit():
            return False
    return True

# Driver code
if __name__ == "__main__":
    # Store the input in a variable named 'str_input' (avoid using 'str' as it's a built-in type)
    str_input = "6790"

    # Function Call
    if isNumber(str_input):
        print("Integer")
    else:
        print("String")
C#
using System;

public class GFG
{
    // Returns true if s is a number else false
    static bool IsNumber(string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c))
            {
                return false;
            }
        }
        return true;
    }

    // Main method
    static public void Main(string[] args)
    {
        // Saving the input in a string
        string str = "6790";

        // Function returns true if all elements
        // are in the range '0' - '9'
        if (IsNumber(str))
        {
            Console.WriteLine("Integer");
        }
        else
        {
            Console.WriteLine("String");
        }
    }
}
JavaScript
<script>
    // JavaScript program to check if a given
    // string is a valid integer

    // Returns true if s is a
    // number else false
    function isNumber(s) {
        for (let i = 0; i < s.length; i++) {
            if (s[i] < '0' || s[i] > '9') {
                return false;
            }
        }
        return true;
    }

    // Saving the input in a string
    let str = "6790";

    // Function returns true if all elements
    // are in range '0' - '9'
    if (isNumber(str)) {
        document.write("Integer");
    } else {
        document.write("String");
    }
</script>
PHP
<?php
// PHP program to check if a 
// given string is a valid integer

// Returns true if s 
// is a number else false
function isNumber($s)
{
    for ($i = 0; $i < strlen($s); $i++) {
        if (!is_numeric($s[$i])) {
            return false;
        }
    }
    return true;
}

// Driver code

// Saving the input
// in a string
$str = "6790";

// Function returns 
// true if all elements
// are in range '0-9'
if (isNumber($str)) {
    echo "Integer";
} else {
    echo "String";
}

// This code is contributed by ajit
?>

Output
Integer

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 2: Using special built-in type() function:

type() takes object as parameter and returns its class type as its name says.

Below is the implementation of the above idea:

C++
#include <iostream>
#include <string>

using namespace std;

// Function to determine whether
// the user input is string or integer type
bool isNumber(const string& input) {
    for (char c : input) {
        if (!isdigit(c)) {
            return false;
        }
    }
    return true;
}

// Driver code
int main() {
    string input1 = "122";
    string input2 = "abc123";

    // Checking input1
    if (isNumber(input1)) {
        cout << "Integer" << endl;
    } else {
        cout << "String" << endl;
    }

    // Checking input2
    if (isNumber(input2)) {
        cout << "Integer" << endl;
    } else {
        cout << "String" << endl;
    }

    return 0;
}
Java
import java.util.Scanner;

public class Main {

    // Function to determine whether 
    // the user input is string or
    // integer type
    public static boolean isNumber(String input) {
        try {
            // Attempt to parse the input as an integer
            Integer.parseInt(input);
            return true;
        } catch (NumberFormatException e) {
            // If parsing fails, it's not an integer
            return false;
        }
    }

    // Driver code
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Getting user input as strings
        System.out.print("Enter input1: ");
        String input1 = scanner.nextLine();

        System.out.print("Enter input2: ");
        String input2 = scanner.nextLine();

        scanner.close();

        // Function Call

        // for input1
        if (isNumber(input1)) {
            System.out.println("Input1 is Integer");
        } else {
            System.out.println("Input1 is String");
        }

        // for input2
        if (isNumber(input2)) {
            System.out.println("Input2 is Integer");
        } else {
            System.out.println("Input2 is String");
        }
    }
}
Python
# Function to determine whether 
# the user input is string or
# integer type
def isNumber(x):
    if isinstance(x, int):
        return True
    elif isinstance(x, str) and x.isdigit():
        return True
    else:
        return False

# Driver Code
input1 = 122
input2 = '122'

# Function Call

# for input1
if isNumber(input1):
    print("Input1 is Integer")
else:
    print("Input1 is String")

# for input2
if isNumber(input2):
    print("Input2 is Integer")
else:
    print("Input2 is String")
C#
using System;

class Program {
    // Function to determine whether the user input is a
    // string or integer
    static bool IsInteger(string input)
    {
        // Attempt to parse the input as an integer
        if (int.TryParse(input, out int result))
        {
            return true; // Input is a valid integer
        }
        else
        {
            return false; // Input is not a valid integer
        }
    }

    static void Main()
    {
        string input1 = "122";
        string input2 = "abc123";

        // Function Call

        // For input1
        if (IsInteger(input1)) {
            Console.WriteLine("Input1 is Integer");
        }
        else {
            Console.WriteLine("Input1 is String");
        }

        // For input2
        if (IsInteger(input2)) {
            Console.WriteLine("Input2 is Integer");
        }
        else {
            Console.WriteLine("Input2 is String");
        }
    }
}
JavaScript
// Function to determine whether 
// the user input is string or
// integer type
function isNumber(x) {
    return !isNaN(x) && !isNaN(parseInt(x));
}

// Driver Code
let input1 = 122;
let input2 = '122';

// Function Call

// for input1
if (isNumber(input1)) {
    console.log("Input1 is Integer");
} else {
    console.log("Input1 is String");
}

// for input2
if (isNumber(input2)) {
    console.log("Input2 is Integer");
} else {
    console.log("Input2 is String");
}

Output
Integer
String

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 3: Using Integer.parseInt() in Java

The parseInt() method of Integer class is used to parse a given string into an integer provided that the string contains a valid integer. In case, the string doesn’t contain a valid integer, it throws a NumberFormatException. The idea is to parse the given string using the same. If an exception is found, then the given string will not be a valid integer and vice-versa.

Below is the implementation of the above idea:

C++
#include <iostream>
#include <string>

using namespace std;

// Driver code
int main()
{
    string s = "abc"; // Sample input to test

    try {
        // Attempt to convert the string to an integer
        int result = stoi(s);

        // If successful, print "Integer"
        cout << "Integer" << endl;
    }
    catch (const invalid_argument& e) {
        // If an invalid argument exception is caught, print
        // "String" (non-numeric characters)
        cout << "String" << endl;
    }
    catch (const out_of_range& e) {
        // If an out of range exception is caught, print
        // "String" (for values out of int range)
        cout << "String" << endl;
    }

    return 0;
}
Java
public class Main {

    public static void main(String[] args) {
        String s = "abc"; // Sample input to test

        try {
            // Attempt to parse the string as an integer
            Integer.parseInt(s);

            // If successful, print "Integer"
            System.out.println("Integer");
        } catch (NumberFormatException e) {
            // If parsing fails, print "String"
            System.out.println("String");
        }
    }
}
Python
s = "abc"  # Sample input to test

try:
    # Attempt to convert the string to an integer
    result = int(s)

    # If successful, print "Integer"
    print("Integer")
except ValueError:
    # If a ValueError is caught, print "String" (invalid conversion)
    print("String")
except OverflowError:
    # If an OverflowError is caught, print "String" (value out of int range)
    print("String")
C#
using System;

class Program
{
    static void Main()
    {
        string s = "abc"; // Sample input to test

        try
        {
            // Attempt to convert the string to an integer
            int result = int.Parse(s);

            // If conversion is successful, this line can be used to work with the integer result
            Console.WriteLine("Converted to Integer: " + result);
        }
        catch (FormatException)
        {
            // If a FormatException is caught, print "String" (invalid format)
            Console.WriteLine("String");
        }
        catch (OverflowException)
        {
            // If an OverflowException is caught, print "String" (value out of int range)
            Console.WriteLine("String");
        }
    }
}
JavaScript
// Sample input to test
let s = "abc";

// Attempt to convert the string to an integer
let result = parseInt(s);

// Check if the result is NaN (indicating failed conversion)
if (isNaN(result)) {
    // If NaN, print "String"
    console.log("String");
} else {
    // Otherwise, print "Integer"
    console.log("Integer");
}

Output
String

Time Complexity: O(N) where N is the length of the string.
Auxiliary Space: O(1)

Method 4: Traverse and check if ASCII range falls under (0-9)

This method/algo is that traverse through the string and checks if ASCII range of every character falls under (0-9) or not. If every character is in range (48-57) then it prints that the string is an integer otherwise it is a string.

C++
#include <iostream>
#include <string>
using namespace std;

// Function to check if a string represents a valid integer
bool isNumber(const string& st) {
    // Loop through each character in the string
    for (char c : st) {
        // Check if the character is not a digit
        if (!isdigit(c)) {
            return false; // If any non-digit character is found, it's not a valid integer
        }
    }
    return true; // If all characters are digits, it's a valid integer
}

int main() {
    // Saving the input in a string
    string st = "122B";

    // Function returns true if all characters are digits
    if (isNumber(st)) {
        cout << "Integer" << endl;
    } else {
        cout << "String" << endl;
    }

    return 0;
}
Java
import java.io.*;

public class GFG {
    // Function to determine if a string is a valid integer
    static boolean isNumber(String st) {
        try {
            // Attempt to parse the string as an integer
            Integer.parseInt(st);
            return true; // If no exception is thrown, it's a valid integer
        } catch (NumberFormatException e) {
            return false; // If an exception is caught, it's not a valid integer
        }
    }

    public static void main(String[] args) {
        // Saving the input in a string
        String st = "122B";

        // Check if the input string is a valid integer
        if (isNumber(st))
            System.out.println("Integer");
        else
            System.out.println("String");
    }
}
Python
def isNumber(st):
    # Check if the string consists of only numeric characters
    return st.isdigit()

if __name__ == "__main__":
    # Saving the input in a string
    st = "122B"

    # Check if the input string is a valid integer
    if isNumber(st):
        print("Integer")
    else:
        print("String")
C#
using System;

class Program
{
    // Function to check if a string represents a valid integer
    static bool IsNumber(string st)
    {
        foreach (char c in st)
        {
            // Check if the character is not a digit
            if (!char.IsDigit(c))
            {
                return false; // If any non-digit character is found, it's not a valid integer
            }
        }
        return true; // If all characters are digits, it's a valid integer
    }

    static void Main(string[] args)
    {
        // Saving the input in a string
        string st = "122B";

        // Function returns true if all characters are digits
        if (IsNumber(st))
        {
            Console.WriteLine("Integer");
        }
        else
        {
            Console.WriteLine("String");
        }
    }
}
JavaScript
// Function to check if a string represents a valid integer
function isNumber(st) {
    for (let c of st) {
        // Check if the character is not a digit
        if (!/\d/.test(c)) {
            return false; // If any non-digit character is found, it's not a valid integer
        }
    }
    return true; // If all characters are digits, it's a valid integer
}

// Saving the input in a string
let st = "122B";

// Function returns true if all characters are digits
if (isNumber(st)) {
    console.log("Integer");
} else {
    console.log("String");
}

Output
String

Time Complexity: O(N) where N is the length of the string.
Auxiliary Space: O(1)

Method 5: Using isinstance() in Python

The isinstance() method is a built-in function in Python that checks whether an object is an instance of a specified class. It returns a boolean value, True if the object is an instance of the class, False otherwise. It takes two arguments, the object and the class, and returns True or False depending on the object’s class.
For example, isinstance(3, int) will return True, while isinstance(‘abc’, int) will return False.

C++
#include <iostream>
#include <string>

// Function to check if st is a number or not
bool isNumber(const std::string& st)
{
    for (char c : st) {
        if (!isdigit(c)) {
            return false;
        }
    }
    return true;
}

int main()
{
    // Saving the input as strings
    std::string st = "122B";
    std::string pt = "122";

    std::cout << st << ": ";
    // Function returns true if st is a number
    if (isNumber(st)) {
        std::cout << "Integer" << std::endl;
    }
    else {
        std::cout << "String" << std::endl;
    }

    // For "122"
    std::cout << pt << ": ";
    if (isNumber(pt)) {
        std::cout << "Integer" << std::endl;
    }
    else {
        std::cout << "String" << std::endl;
    }

    return 0;
}
Java
public class Main {
    // Function to check if st is a number or not
    public static boolean isNumber(Object st)
    {
        if (st instanceof Integer) {
            return true;
        }
        return false;
    }

    public static void main(String[] args)
    {
        // Saving the input as objects
        Object st = "122B";
        Object pt = 122;

        System.out.print(st + ": ");
        // Function returns true if st is a number
        if (isNumber(st)) {
            System.out.println("Integer");
        }
        else {
            System.out.println("String");
        }

        // For 122
        System.out.print(pt + ": ");
        if (isNumber(pt)) {
            System.out.println("Integer");
        }
        else {
            System.out.println("String");
        }
    }
}
// This code is contributed by Adarsh.
Python
# Function to check if st is number or not
def isNumber(st):
    if isinstance(st, int):  # Check if the input is already an integer
        return True
    try:
        int(st)  # Try to convert the input to an integer
        return True  # If successful, it's a valid integer
    except ValueError:
        return False  # If conversion fails, it's not a valid integer

if __name__ == "__main__":
    # Saving the input in a string
    st = "122B"
    pt = 122

    # Check for st
    print(st, end=': ')
    if isNumber(st):
        print("Integer")
    else:
        print("String")

    # Check for pt
    print(pt, end=': ')
    if isNumber(pt):
        print("Integer")
    else:
        print("String")
JavaScript
// Function to check if st is a number or not
function isNumber(st) {
    return typeof st === 'number' && !isNaN(st);
}

// Main function
function main() {
    // Saving the input as objects
    let st = "122B";
    let pt = 122;

    process.stdout.write(`${st}: `);
    // Function returns true if st is a number
    if (isNumber(st)) {
        console.log("Integer");
    } else {
        console.log("String");
    }

    // For 122
    process.stdout.write(`${pt}: `);
    if (isNumber(pt)) {
        console.log("Integer");
    } else {
        console.log("String");
    }
}

// Call the main function
main();

Output
122B: String
122: Integer

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 6: Using isnumeric() in Python

The isnumeric() method returns True if all the characters in a string are numeric characters. This includes any characters that can be used to form the base 10 numeric system, such as digits 0 to 9, negative sign, decimal point, etc. It returns False if any character is not a numeric character.

C++
#include <iostream>
#include <string>
using namespace std;

// Function to check if st is a number or not
bool isNumber(const string& st) {
    for (char c : st) {
        if (!isdigit(c)) {
            return false;
        }
    }
    return true;
}

// Main function
int main() {
    // Saving the input as a string
    string st = "122B";
    string pt = "122";

    // For 122B
    cout << st << ": ";
    if (isNumber(st))
        cout << "Integer" << endl;
    else
        cout << "String" << endl;

    // For 122
    cout << pt << ": ";
    if (isNumber(pt))
        cout << "Integer" << endl;
    else
        cout << "String" << endl;

    return 0;
}
Java
public class GFG {
    // Function to check if st is a number or not
    static boolean isNumber(String st) {
        for (char c : st.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    // Main function
    public static void main(String[] args) {
        // Saving the input as a string
        String st = "122B";
        String pt = "122";

        // For 122B
        System.out.print(st + ": ");
        if (isNumber(st))
            System.out.println("Integer");
        else
            System.out.println("String");

        // For 122
        System.out.print(pt + ": ");
        if (isNumber(pt))
            System.out.println("Integer");
        else
            System.out.println("String");
    }
}
Python
# Function to check if st is a number or not
def isNumber(st):
    return st.isnumeric()

if __name__ == "__main__":
    # Saving the input in a string
    st = "122B"
    pt = "122"

    print(st, end=': ')
    # Function returns true if st is number
    if isNumber(st):
        print("Integer")
    # Function returns false if st is not number
    else:
        print("String")

    # For 122
    print(pt, end=': ')
    if isNumber(pt):
        print("Integer")
    else:
        print("String")
C#
using System;

class Program {
    // Function to check if st is a number or not
    static bool IsNumber(string st) {
        foreach(char c in st) {
            if (!Char.IsDigit(c))
                return false;
        }
        return true;
    }

    static void Main(string[] args) {
        // Saving the input as a string
        string st = "122B";
        string pt = "122";

        // For 122B
        Console.Write(st + ": ");
        if (IsNumber(st))
            Console.WriteLine("Integer");
        else
            Console.WriteLine("String");

        // For 122
        Console.Write(pt + ": ");
        if (IsNumber(pt))
            Console.WriteLine("Integer");
        else
            Console.WriteLine("String");
    }
}
JavaScript
// Function to check if a string consists of digits only
function isNumber(st) {
    // Iterate through each character in the string
    for (const c of st) {
        // Check if the character is a digit
        if (isNaN(parseInt(c))) {
            return false;
        }
    }
    return true;
}

// Main function
const st = "122B";
const pt = "122";

// For 122B
console.log(`${st}: `);
// Check if the string consists of digits only
if (isNumber(st)) {
    console.log("Integer");
} else {
    console.log("String");
}

// For 122
console.log(`${pt}: `);
// Check if the string consists of digits only
if (isNumber(pt)) {
    console.log("Integer");
} else {
    console.log("String");
}

Output
122B: String
122: Integer

Time Complexity: O(N), where N is the length of the input string.
Auxiliary Space: O(1)

Method 7: Using Regular Expressions

Regular expressions can be used to check if a given string is a valid integer. Regular expressions allow you to define a pattern of characters and then check if a string matches that pattern. If the string matches the pattern, it is a valid integer.

C++
#include <iostream>
#include <regex>
#include <string>
using namespace std;

// Function to print "Integer" or "String" based on boolean result
void check(bool result)
{
    if (result) {
        cout << "Integer" << endl;
    }
    else {
        cout << "String" << endl;
    }
}

int main()
{
    string s1 = "122B"; // Sample input to test (contains non-numeric characters)
    string s2 = "122";  // Sample input to test (contains only numeric characters)

    // Define a regular expression pattern to match integers (allowing optional negative sign)
    regex pattern("^-?\\d+$");

    // Check if s1 is an integer
    bool result1 = regex_match(s1, pattern);
    cout << s1 << ": ";
    check(result1);

    // Check if s2 is an integer
    bool result2 = regex_match(s2, pattern);
    cout << s2 << ": ";
    check(result2);

    return 0;
}
Java
public class Main {
    // Function to print "Integer" or "String" based on boolean result
    static void check(boolean result) {
        if (result)
            System.out.println("Integer");
        else
            System.out.println("String");
    }

    public static void main(String[] args) {
        String s1 = "122B"; // Sample input to test (contains non-numeric characters)
        String s2 = "122";  // Sample input to test (contains only numeric characters)

        // Check if s1 is an integer
        boolean result1 = s1.matches("^-?\\d+$"); // true if input is an integer
        System.out.print(s1 + ": ");
        check(result1);

        // Check if s2 is an integer
        boolean result2 = s2.matches("^-?\\d+$"); // true if input is an integer
        System.out.print(s2 + ": ");
        check(result2);
    }
}
Python
import re

# Function to print "Integer" or "String" based on boolean result
def check(result):
    if result:
        print("Integer")
    else:
        print("String")

# Sample input strings to test
s1 = "122B"  # Contains non-numeric characters
s2 = "122"   # Contains only numeric characters

# Define the regular expression pattern to match integers (with optional negative sign)
pattern = r'^-?\d+$'

# Check if s1 is an integer
result1 = bool(re.match(pattern, s1))
print(s1 + ": ", end="")
check(result1)

# Check if s2 is an integer
result2 = bool(re.match(pattern, s2))
print(s2 + ": ", end="")
check(result2)
C#
using System;
using System.Text.RegularExpressions;

class Program
{
    // Function to print "Integer" or "String" based on boolean result
    static void Check(bool result)
    {
        if (result)
        {
            Console.WriteLine("Integer");
        }
        else
        {
            Console.WriteLine("String");
        }
    }

    static void Main(string[] args)
    {
        string s1 = "122B"; // Sample input to test (contains non-numeric characters)
        string s2 = "122";  // Sample input to test (contains only numeric characters)

        // Define the regular expression pattern to match integers (with optional\\
      //negative sign)
        Regex pattern = new Regex(@"^-?\d+$");

        // Check if s1 is an integer
        bool result1 = pattern.IsMatch(s1);
        Console.Write(s1 + ": ");
        Check(result1);

        // Check if s2 is an integer
        bool result2 = pattern.IsMatch(s2);
        Console.Write(s2 + ": ");
        Check(result2);
    }
}
JavaScript
// Function to print "Integer" or "String" according to boolean result
function check(result) {
    if (result) {
        document.write("Integer<br>");
    } else {
        document.write("String<br>");
    }
}

let s1 = "122B";  // Sample input to test (contains non-numeric characters)
let s2 = "122";   // Sample input to test (contains only numeric characters)

// Define the regular expression pattern to match integers (with optional negative sign)
let pattern = /^-?\d+$/;

// Return true if input is an integer (matches the pattern)
let result = Boolean(s1.match(pattern));
document.write(s1 + ": ");
check(result);

// Return false if input is not an integer (does not match the pattern)
result = Boolean(s2.match(pattern));
document.write(s2 + ": ");
check(result);

Output
122B: String
122: Integer

Time Complexity: O(N), where N is the length of the input.
Auxiliary Space: O(1)

Method 8: Using Java instanceof operator

The instanceof operator is used to check if an object is an instance of a particular type. It takes two parameters: the object to be checked and the type to be checked against. It returns a boolean value indicating whether the object is an instance of the specified type.

C++
#include <iostream>
#include <string>
#include <type_traits> // Include the type_traits header for type traits functionality

// Function to print Integer or String according to type
template<typename T>
void check(const T& obj)
{
    // Check if the type T is the same as int
    if (std::is_same<T, int>::value) {
        std::cout << "Integer" << std::endl; // If T is int, print "Integer"
    }
    // Check if the type T is the same as std::string
    else if (std::is_same<T, std::string>::value) {
        std::cout << "String" << std::endl; // If T is std::string, print "String"
    }
    else {
        std::cout << "Other Type" << std::endl; // If T is neither int nor std::string, print "Other Type"
    }
}

int main()
{
    std::string s1 = "122B";
    int s2 = 122;

    std::cout << s1 << ": ";
    // Print according to type
    check(s1); // Call check function with s1

    std::cout << s2 << ": ";
    // Print according to type
    check(s2); // Call check function with s2

    return 0;
}
Java
public class GFG {
    // Function to print Integer or String according to
    // instanceof
    static void check(Object obj)
    {
        if (obj instanceof Integer) {
            System.out.println("Integer");
        }
        else if (obj instanceof String) {
            System.out.println("String");
        }
        else {
            System.out.println("Other Type");
        }
    }
    public static void main(String[] args)
    {
        Object s1 = "122B";
        Object s2 = 122;

        System.out.print(s1 + ": ");
        // Print according to instanceof
        check(s1);

        System.out.print(s2 + ": ");
        // Print according to instanceof
        check(s2);
    }
}
Python
# Function to check if an input is an Integer or a String
def check(obj):
    if isinstance(obj, int):
        return "Integer"
    elif isinstance(obj, str):
        return "String"
    else:
        return "Other Type"

# Main function
def main():
    s1 = "122B"
    s2 = 122

    # Concatenate the results and print them
    print(str(s1) + ": " + check(s1))
    print(str(s2) + ": " + check(s2))

# Call the main function to test the inputs
main()
JavaScript
// Function to check if an input is an Integer or a String
function check(obj) {
    if (typeof obj === 'number' && Number.isInteger(obj)) {
        return "Integer";
    } else if (typeof obj === 'string') {
        return "String";
    } else {
        return "Other Type";
    }
}

// Main function
function main() {
    var s1 = "122B";
    var s2 = 122;

    // Concatenate the results and print them
    console.log(s1 + ": " + check(s1));
    console.log(s2 + ": " + check(s2));
}

// Call the main function to test the inputs
main();

Output
122B: String
122: Integer

Time Complexity: O(1), because there is no loop or recursion in the code. The code is a simple if-else statement which takes a constant amount of time to execute.
Auxiliary Space: O(1), because there is no extra space required to execute this code. The only variables used in this code are s1, s2, and obj, and they all take constant space.

Method 9: Using Java Integer.valueOf() method

The Integer.valueOf() method is used to check if the given input is an integer or a string. If the input is an integer, then it will return the integer value, otherwise it will throw a NumberFormatException, which can be caught and used to determine that the input is a string.

C++
#include <iostream>
#include <sstream>
#include <string>

void check(const std::string& input)
{
    try {
        size_t pos;
        std::stoi(input, &pos);
        if (pos == input.length()) {
            std::cout << "Integer" << std::endl;
        }
        else {
            std::cout << "String" << std::endl;
        }
    }
    catch (const std::invalid_argument& e) {
        std::cout << "String" << std::endl;
    }
    catch (const std::out_of_range& e) {
        std::cout << "String" << std::endl;
    }
}

int main()
{
    std::string s1 = "122B";
    std::string s2 = "122";

    std::cout << s1 << ": ";
    check(s1);

    std::cout << s2 << ": ";
    check(s2);

    return 0;
}

// This code is contributed by shivamgupta0987654321
Java
class GFG {
    static void check(String input)
    {
        try {
            Integer.valueOf(input);
            System.out.println("Integer");
        }
        catch (NumberFormatException e) {
            System.out.println("String");
        }
    }

    public static void main(String[] args)
    {
        String s1 = "122B";
        String s2 = "122";

        System.out.print(s1 + ": ");
        check(s1);

        System.out.print(s2 + ": ");
        check(s2);
    }
}

// This code is contributed by Susobhan Akhuli
Python
class GFG:
    @staticmethod
    def check(input):
        try:
            int(input)
            print("Integer")
        except ValueError:
            print("String")

if __name__ == "__main__":
    s1 = "122B"
    s2 = "122"

    print(s1 + ": ", end="")
    GFG.check(s1)

    print(s2 + ": ", end="")
    GFG.check(s2)
JavaScript
// Function to check if a given input is a valid integer or a string
function check(input) {
    try {
        // Attempt to convert the input to an integer
        parseInt(input);
        console.log(input + ": Integer");
    } catch (error) {
        // If an error occurs, it's not a valid integer
        console.log(input + ": String");
    }
}

// Main function
function main() {
    // Test inputs
    var s1 = "122B";
    var s2 = "122";
      
    check(s1);
    check(s2);
}

// Run the main function
main();

Output
122B: String
122: Integer

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 10: Using Java Integer.equals() method

The Integer.equals() method is used to check if the given input is an integer or a string.

Steps:

To check if an input is an integer or a string using the Integer.equals() method in Java, you can follow these steps:

  1. Create an Object variable to store the input value.
  2. Use the instanceof operator to check if the input is an instance of Integer. If it is, then the input is an integer.
  3. If the input is not an instance of Integer, convert it to a string using the String.valueOf() method.
  4. Use the try-catch block to parse the input string into an integer using the Integer.parseInt() method. If the input string is not a valid integer, catch the NumberFormatException.
  5. Create an Integer object with the parsed integer using the Integer.valueOf() method.
  6. Check if the Integer object is equal to the input object using the Integer.equals() method. If they are equal, then the input is an integer. If they are not equal, then the input is a string.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if the input string is an integer or a
// string
void check(const string& input)
{
    try {
        size_t pos; // Variable to store the position of the
                    // first non-numeric character
        int num = stoi(
            input,
            &pos); // Convert the input string to an integer

        // Check if the entire string is converted to an
        // integer (no non-numeric characters)
        if (pos == input.length()) {
            cout << "Input is an integer" << endl;
        }
        else {
            cout << "Input is a string" << endl;
        }
    }
    catch (invalid_argument& e) {
        // Exception thrown when conversion to integer fails
        // (input contains non-numeric characters)
        cout << "Input is a string" << endl;
    }
    catch (out_of_range& e) {
        // Exception thrown when the converted value is out
        // of the range of the target type (integer
        // overflow)
        cout << "Input is a string" << endl;
    }
}

int main()
{
    string s1 = "122B"; // Sample input to test (contains
                        // non-numeric characters)
    string s2 = "122"; // Sample input to test (contains
                       // only numeric characters)

    cout << s1 << ": ";
    check(s1); // Check if s1 is an integer or a string

    cout << s2 << ": ";
    check(s2); // Check if s2 is an integer or a string

    return 0;
}
Java
public class GFG {
    static void check(Object input) {
        if (input instanceof Integer) {
            // If the input is an instance of Integer, it's considered an integer
            System.out.println("Input is an integer");
        } else {
            try {
                // Attempt to convert the input to a String and then to an Integer
                String str = String.valueOf(input);
                Integer num = Integer.valueOf(str);
                
                // Check if the Integer representation matches the original input
                if (num.equals(input)) {
                    System.out.println("Input is an integer");
                } else {
                    System.out.println("Input is a string");
                }
            } catch (NumberFormatException e) {
                // Catch NumberFormatException when input cannot be converted to Integer
                System.out.println("Input is a string");
            }
        }
    }

    public static void main(String[] args) {
        Object s1 = "122B";  // Sample input to test (String)
        Object s2 = 122;     // Sample input to test (Integer)

        System.out.print(s1 + ": ");
        check(s1);  // Check if s1 is an integer or a string

        System.out.print(s2 + ": ");
        check(s2);  // Check if s2 is an integer or a string
    }
}
Python
def check(input_str):
    try:
        num = int(input_str)
        
        # Check if the entire string is converted to an integer
        if str(num) == input_str:
            print("Input is an integer")
        else:
            print("Input is a string")
    except ValueError:
        # Exception thrown when conversion to integer fails
        print("Input is a string")

if __name__ == "__main__":
    s1 = "122B"  # Sample input to test (string)
    s2 = "122"   # Sample input to test (integer)

    print(s1 + ": ", end="")
    check(s1)  # Check if s1 is an integer or a string

    print(s2 + ": ", end="")
    check(s2)  # Check if s2 is an integer or a string
C#
using System;

class Program {
    // Function to check if input is an integer or a string
    static void Check(string input)
    {
        try {
            // Try to parse the string to an integer
            int num = int.Parse(input);

            // Check if the entire string is converted to an
            // integer
            if (num.ToString() == input) {
                Console.WriteLine("Input is an integer");
            }
            else {
                Console.WriteLine("Input is a string");
            }
        }
        catch (FormatException) {
            // Exception thrown when conversion to integer
            // fails
            Console.WriteLine("Input is a string");
        }
        catch (OverflowException) {
            // Exception thrown when the converted value is
            // out of the range of the target type
            Console.WriteLine("Input is a string");
        }
    }

    static void Main(string[] args)
    {
        string s1 = "122B";
        string s2 = "122";

        Console.Write(s1 + ": ");
        Check(s1); // Check if s1 is an integer or a string

        Console.Write(s2 + ": ");
        Check(s2); // Check if s2 is an integer or a string
    }
}
JavaScript
function check(input_str) {
    try {
        let num = parseInt(input_str);

        // Check if the entire string is converted to an integer
        if (String(num) === input_str) {
            console.log("Input is an integer");
        } else {
            console.log("Input is a string");
        }
    } catch (error) {
        // Exception thrown when conversion to integer fails
        console.log("Input is a string");
    }
}

let s1 = "122B";
let s2 = "122";

process.stdout.write(s1 + ": ");
check(s1);

process.stdout.write(s2 + ": ");
check(s2);

Output
122B: Input is a string
122: Input is an integer

Time Complexity: O(N), where N is the length of the input string, because it performs string operations such as converting the input to a string and parsing the string into an integer.
Auxiliary Space: O(N), as it uses a string variable to store the input as a string and an Integer object to store the input as an integer.

Method 11: Using Java Integer.compare() Method

The Integer.compare() method is used to check if the given input is an integer or a string.

Steps:

To check if an input is an integer or a string using the Integer.compare() method in Java, we can do the
following:

  1. Convert the input to a string using the String.valueOf() method.
  2. Compare the input string to the string representation of its integer value using the Integer.compare() method. 
    • If the two strings are equal, then the input is an integer.
    • If the two strings are not equal, then the input is a string.

Below is the implementation of the above approach:

C++
#include <iostream>
#include <string>
#include <typeinfo>

void check(const std::string& input) {
    try {
        // Try to convert the input string to an integer
        int number = std::stoi(input);
        std::cout << "Input is an integer" << std::endl;
    } catch (const std::invalid_argument& e) {
        // Catch invalid_argument exception if input is not a valid integer
        std::cout << "Input is a string" << std::endl;
    } catch (const std::out_of_range& e) {
        // Catch out_of_range exception if the integer is out of range
        std::cout << "Input is a string" << std::endl;
    }
}

int main() {
    std::string s1 = "122B";
    int s2 = 122;

    std::cout << s1 << ": ";
    check(s1);

    // Convert integer to string to use the same check function
    std::string s2_str = std::to_string(s2);
    std::cout << s2_str << ": ";
    check(s2_str);

    return 0;
}

// This code is contributed by Shivam
Java
// Java program to check if a given input is a valid integer
// or a string using integer.equals() method
public class GFG {
    static void check(Object input)
    {
        if (input instanceof Integer) {
            System.out.println("Input is an integer");
        }
        else {
            try {
                String str = String.valueOf(input);
                if (Integer.compare(Integer.parseInt(str),
                                    (Integer)input)
                    == 0) {
                    System.out.println(
                        "Input is an integer");
                }
                else {
                    System.out.println("Input is a string");
                }
            }
            catch (NumberFormatException e) {
                System.out.println("Input is a string");
            }
        }
    }
    public static void main(String[] args)
    {
        Object s1 = "122B";
        Object s2 = 122;

        System.out.print(s1 + ": ");
        check(s1);

        System.out.print(s2 + ": ");
        check(s2);
    }
}

// This code is contributed by Susobhan Akhuli
Python
# Function to check if a given input is a valid integer or a string
def check(input):
    if isinstance(input, int):
        print(f"{input}: Input is an integer")
    else:
        try:
            if int(str(input)) == input:
                print(f"{input}: Input is an integer")
            else:
                print(f"{input}: Input is a string")
        except ValueError:
            print(f"{input}: Input is a string")

# Main function
def main():
    s1 = "122B"
    s2 = 122

    check(s1)
    check(s2)

# Call the main function
main()

# This code is contributed by shivamgupta0987654321
JavaScript
// Function to check if a given input is a valid integer or a string
function check(input) {
    if (Number.isInteger(input)) {
        console.log(`${input}: Input is an integer`);
    } else {
        try {
            let str = String(input);
            if (parseInt(str) === input) {
                console.log(`${input}: Input is an integer`);
            } else {
                console.log(`${input}: Input is a string`);
            }
        } catch (error) {
            console.log(`${input}: Input is a string`);
        }
    }
}

// Main function
function main() {
    let s1 = "122B";
    let s2 = 122;

    check(s1);
    check(s2);
}

// Call the main function
main();

Output
122B: Input is a string
122: Input is an integer

Time Complexity: O(n), where n is the length of the input string, because it performs string operations such as converting the input to a string and comparing two strings.
Auxiliary Space: O(n), as it uses a string variable to store the input as a string.

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. 



Next Article
Article Tags :
Practice Tags :

Similar Reads