Open In App

Program to check if input is an integer or a string

Improve
Improve
Like Article
Like
Save
Share
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++
// CPP program to check if a given string
// is a valid integer
#include <iostream>
using namespace std;

// Returns true if s is a number else false
bool isNumber(string s)
{
    for (int i = 0; i < s.length(); i++)
        if (isdigit(s[i]) == false)
            return false;

    return true;
}

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

    // Function returns 1 if all elements
    // are in range '0-9'
    if (isNumber(str))
        cout << "Integer";

    // Function returns 0 if the input is
    // not an integer
    else
        cout << "String";
}
Java
// Java program to check if a given
// string is a valid integer
import java.io.*;

public class GFG {

    // 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)) == false)
                return false;

        return true;
    }

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

        // Function returns 1 if all elements
        // are in range '0 - 9'
        if (isNumber(str))
            System.out.println("Integer");

        // Function returns 0 if the
        // input is not an integer
        else
            System.out.println("String");
    }
}

// This code is contributed by vt_m.
C#
// C# program to check if a given
// string is a valid integer
using System;

public class GFG {

    // Returns true if s is a
    // number else false
    static bool isNumber(string s)
    {
        for (int i = 0; i < s.Length; i++)
            if (char.IsDigit(s[i]) == false)
                return false;

        return true;
    }

    // Driver code
    static public void Main(String[] args)
    {

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

        // Function returns 1 if all elements
        // are in range '0 - 9'
        if (isNumber(str))
            Console.WriteLine("Integer");

        // Function returns 0 if the
        // input is not an integer
        else
            Console.WriteLine("String");
    }
}

// This code is contributed by vt_m.
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 1 if all elements
    // are in range '0 - 9'
    if (isNumber(str))
      document.write("Integer");

    // Function returns 0 if the
    // input is not an 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]) == false)
            return false;

    return true;
}

// Driver code

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

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

// This code is contributed by ajit
?>
Python 3
# 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 i in range(len(s)):
        if s[i].isdigit() != True:
            return False

    return True


# Driver code
if __name__ == "__main__":

    # Store the input in a str variable
    str = "6790"

    # Function Call
    if isNumber(str):
        print("Integer")

    else:
        print("String")

# This code is contributed by ANKITRAI1

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";

    // Function Call

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

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

    return 0;
}
Java
// Java program to find
// whether the user input
// is int or string type

public class Main {
    // Function to determine whether 
    // the user input is string or
    // integer type
    public static boolean isNumber(Object x) {
        if (x instanceof Integer) {
            return true;
        } else {
            return false;
        }
    }

    // Driver code
    public static void main(String[] args) {
        Object input1 = 122;
        Object input2 = "122";

        // Function Call

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

        // for input2
        if (isNumber(input2)) {
            System.out.println("Integer");
        } else {
            System.out.println("String");
        }
    }
}
C#
using System;

class Program {
    // Function to determine whether the user input is a
    // string or integer
    static bool IsNumber(string input)
    {
        foreach(char c in input)
        {
            if (!Char.IsDigit(c)) {
                return false;
            }
        }
        return true;
    }

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

        // Function Call

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

        // For input2
        if (IsNumber(input2)) {
            Console.WriteLine("Integer");
        }
        else {
            Console.WriteLine("String");
        }
    }
}
Javascript
// JavaScript program to find
// whether the user input
// is int or string type

// Function to determine whether 
// the user input is string or
// integer type
function isNumber(x) {
    if (typeof x === 'number') {
        return true;
    } else {
        return false;
    }
}

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

// Function Call

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

// for input2
if (isNumber(input2)) {
    console.log("Integer");
} else {
    console.log("String");
}
Python3
# Python program to find
# whether the user input
# is int or string type

# Function to determine whether 
# the user input is string or
# integer type
def isNumber(x):
    if type(x) == int:
         return True
    else:
         return False


# Driver Code
input1 = 122
input2 = '122'

# Function Call

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

# for input2
if isNumber(input2):
    print("Integer")
else:
    print("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++
// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Driver code
int main()
{
    striang 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 (invalid_argument const& e) {
        // If an invalid argument exception is caught, print
        // "String"
        cout << "String" << endl;
    }
    catch (out_of_range const& e) {
        // If an out of range exception is caught, print
        // "String" (for values out of int range)
        cout << "String" << endl;
    }

    return 0;
}

// This code is contributed by Susobhan Akhuli
Java
// Java program to check if a given
// string is a valid integer
import java.io.*;

public class GFG {

    // Driver code
    static public void main(String[] args)
    {
        String s = "abc"; //sample input to test
        try{
            Integer.parseInt(s);
            System.out.println("Integer");
        }catch(NumberFormatException e){
            System.out.println("String");
        } 
    }
}

// This code is contributed by shruti456rawal
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);

            // Use the result variable or remove it if not needed
            Console.WriteLine("Converted to Integer: " + result);
        }
        catch (FormatException)
        {
            // If a format exception is caught, print "String"
            Console.WriteLine("String");
        }
        catch (OverflowException)
        {
            // If an overflow exception is caught, print "String" (for values 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
if (isNaN(result)) {
    // If NaN, print "String"
    console.log("String");
} else {
    // Otherwise, print "Integer"
    console.log("Integer");
}
Python3
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 value error is caught, print "String"
    print("String")
except OverflowError:
    # If an overflow error is caught, print "String" (for values out of int range)
    print("String")

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++
// CPP program to check if a given string
// is a valid integer
#include <iostream>
using namespace std;

// Function to check if st is number or not
bool isNumber(string st){
      int i = 0;
    while (st[i] != NULL) {
        if (st[i] < 48 || st[i] > 57)
            return false;
        i++;
    }
    return true;
}

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

    // Function returns true if all elements are in
    // range '0-9'
    if (isNumber(st))
        cout << "Integer";

    // Function returns false if the input is not an
    // integer, a string
    else
        cout << "String";

    return 0;
}

// This code is contributed by Susobhan Akhuli
Java
import java.io.*;

public class GFG {
    // Returns true if st is a number else false
    static boolean isNumber(String st) {
        for (int i = 0; i < st.length(); i++)
            if (st.charAt(i) < 48 || st.charAt(i) > 57)
                return false;
        return true;
    }

    public static void main(String[] args) {

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

        // Function returns true if all elements are in
        // range '0-9'
        if (isNumber(st))
            System.out.println("Integer");

        // Function returns false if the input is not an
        // integer, a string
        else
            System.out.println("String");
    }
}

// This code is contributed by Susobhan Akhuli
C#
using System;

public class Program {
    // Returns true if st is a number else false
    static bool isNumber(string st)
    {
        for (int i = 0; i < st.Length; i++)
            if (st[i] < 48 || st[i] > 57)
                return false;
        return true;
    }

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

        // Function returns true if all elements are in
        // range '0-9'
        if (isNumber(st))
            Console.WriteLine("Integer");

        // Function returns false if the input is not an
        // integer, a string
        else
            Console.WriteLine("String");
    }
}
Javascript
// Javascript program to check if a given string
// is a valid integer

// Function to check if st is number or not
function isNumber(st){
    let i = 0;
    while (st[i] != null) {
        if (st[i] < 48 || st[i] > 57)
            return false;
        i++;
    }
    return true;
}

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

// Function returns true if all elements are in
// range '0-9'
if (isNumber(st))
    console.log("Integer");

// Function returns false if the input is not an
// integer, a string
else
    console.log("String");

  
Python3
# Python program to check if a given string
# is a valid integer

# Function to check if st is number or not
def isNumber(st):
    i = 0
    while i < len(st):
        if ord(st[i]) < ord("0") or ord(st[i]) > ord("9"):
            return False
        i += 1
    return True

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

    # Function returns true if all elements are in
    # range '0-9'
    if isNumber(st):
        print("Integer")

    # Function returns false if the input is not an
    # integer, a string
    else:
        print("String")

# This code is contributed by Susobhan Akhuli

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.

Python3
# Python program to check if a given input
# is a valid integer or a string

# Function to check if st is number or not
def isNumber(st):
    if isinstance(st, int):
        return True
    return False


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")

# This code is contributed by Susobhan Akhuli

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++
// CPP program to check if a given input is a valid integer
// or a string
#include <bits/stdc++.h>
using namespace std;

// Function to check if st is a number or not
bool isNumber(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;
}

// This code is contributed by Susobhan Akhuli
Java
// Java program to check if a given input is a valid integer
// or a string
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");
    }
}

// This code is contributed by Susobhan Akhuli
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 (!Number.isDigit(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");
}
Python3
# Python program to check if a given input
# is a valid integer or a string

# Function to check if st is 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")

# This code is contributed by Susobhan Akhuli

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++
// CPP program to check if a given input is a valid integer
// or a string
#include <iostream>
#include <regex>
#include <string>
using namespace std;

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

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

    // Return true if input is integer
    regex pattern("^-?\\d+$");
    bool result = regex_match(s1, pattern);
    cout << s1 << ": ";
    check(result);

    // Return false if input is integer
    result = regex_match(s2, pattern);
    cout << s2 << ": ";
    check(result);

    return 0;
}

// This code is contributed by Susobhan Akhuli
Java
// Java program to check if a given input is a valid integer
// or a string

public class GFG {
    // Function to print Integer or String according to
    // boolean value
    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";
        String s2 = "122";

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

        // Return false if input is integer
        result = s2.matches("^-?\\d+$"); // False
        System.out.print(s2 + ": ");
        check(result);
    }
}

// This code is contributed by Susobhan Akhuli
C#
// C# program to check if a given input is a valid integer
// or a string
using System;
using System.Text.RegularExpressions;

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

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

        // Return true if input is integer
        Regex pattern = new Regex("^-?\\d+$");
        bool result = pattern.IsMatch(s1);
        Console.Write(s1 + ": ");
        Check(result);

        // Return false if input is integer
        result = pattern.IsMatch(s2);
        Console.Write(s2 + ": ");
        Check(result);
    }
}

// This code is contributed by Susobhan Akhuli
Javascript
<script>
    // Javascript program to check if a given input is a valid integer
    // or a string
    // Function to print Integer or String according to boolean value
    function check(result) {
        if (result) {
            document.write("Integer<br>");
        } else {
            document.write("String<br>");
        }
    }
    
    let s1 = "122B";
    let s2 = "122";
    
    // Return true if input is integer
    let pattern = "^-?\\d+$";
    let result = Boolean(s1.match(pattern));
    document.write(s1 + ": ", end="");
    check(result);
    
    // Return false if input is integer
    result = Boolean(s2.match(pattern));
    document.write(s2 + ": ", end="");
    check(result);
    
    // This code is contributed by Susobhan Akhuli
</script>
Python3
# Python program to check if a given input is a valid integer
# or a string
import re

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


s1 = "122B"
s2 = "122"

# Return true if input is integer
pattern = "^-?\d+$"
result = bool(re.match(pattern, s1))
print(s1 + ": ", end="")
check(result)

# Return false if input is integer
result = bool(re.match(pattern, s2))
print(s2 + ": ", end="")
check(result)

# This code is contributed by Susobhan Akhuli

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);
    }
}
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.

Java
// Java program to check if a given input is a valid integer
// or a string using Integer.valueOf() method

class GFG {
    static void check(String input)
    {
        try {
            Integer.valueOf(input);
            System.out.println(&quot;Integer&quot;);
        }
        catch (NumberFormatException e) {
            System.out.println(&quot;String&quot;);
        }
    }

    public static void main(String[] args)
    {
        String s1 = &quot;122B&quot;;
        String s2 = &quot;122&quot;;
          
        System.out.print(s1 + &quot;: &quot;);
        check(s1);

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

// This code is contributed by Susobhan Akhuli

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++
// CPP program for the above approach
#include &lt;bits/stdc++.h&gt;
using namespace std;

void check(const string&amp; input)
{
    try {
        size_t pos;
        int num = stoi(input, &amp;pos);

        // Check if the entire string is converted to an
        // integer
        if (pos == input.length()) {
            cout &lt;&lt; &quot;Input is an integer&quot; &lt;&lt; endl;
        }
        else {
            cout &lt;&lt; &quot;Input is a string&quot; &lt;&lt; endl;
        }
    }
    catch (invalid_argument&amp; e) {
        // Exception thrown when conversion to integer fails
        cout &lt;&lt; &quot;Input is a string&quot; &lt;&lt; endl;
    }
    catch (out_of_range&amp; e) {
        // Exception thrown when the converted value is out
        // of the range of the target type
        cout &lt;&lt; &quot;Input is a string&quot; &lt;&lt; endl;
    }
}

int main()
{
    string s1 = &quot;122B&quot;;
    string s2 = &quot;122&quot;;

    cout &lt;&lt; s1 &lt;&lt; &quot;: &quot;;
    check(s1);

    cout &lt;&lt; s2 &lt;&lt; &quot;: &quot;;
    check(s2);

    return 0;
}

// This code is contributed by Susobhan Akhuli
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(&quot;Input is an integer&quot;);
        }
        else {
            try {
                String str = String.valueOf(input);
                Integer num = Integer.valueOf(str);
                if (num.equals(input)) {
                    System.out.println(
                        &quot;Input is an integer&quot;);
                }
                else {
                    System.out.println(&quot;Input is a string&quot;);
                }
            }
            catch (NumberFormatException e) {
                System.out.println(&quot;Input is a string&quot;);
            }
        }
    }
    public static void main(String[] args)
    {
        Object s1 = &quot;122B&quot;;
        Object s2 = 122;

        System.out.print(s1 + &quot;: &quot;);
        check(s1);

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

// This code is contributed by Susobhan Akhuli
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(&quot;Input is an integer&quot;);
            }
            else
            {
                Console.WriteLine(&quot;Input is a string&quot;);
            }
        }
        catch (FormatException)
        {
            // Exception thrown when conversion to integer fails
            Console.WriteLine(&quot;Input is a string&quot;);
        }
        catch (OverflowException)
        {
            // Exception thrown when the converted value is out of the range of the target type
            Console.WriteLine(&quot;Input is a string&quot;);
        }
    }

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

        Console.Write(s1 + &quot;: &quot;);
        Check(s1);

        Console.Write(s2 + &quot;: &quot;);
        Check(s2);
    }
}
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(&quot;Input is an integer&quot;);
        } else {
            console.log(&quot;Input is a string&quot;);
        }
    } catch (error) {
        // Exception thrown when conversion to integer fails
        console.log(&quot;Input is a string&quot;);
    }
}

let s1 = &quot;122B&quot;;
let s2 = &quot;122&quot;;

process.stdout.write(s1 + &quot;: &quot;);
check(s1);

process.stdout.write(s2 + &quot;: &quot;);
check(s2);
Python3
# Python program for the above approach
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(&quot;Input is an integer&quot;)
        else:
            print(&quot;Input is a string&quot;)
    except ValueError:
        # Exception thrown when conversion to integer fails
        print(&quot;Input is a string&quot;)

if __name__ == &quot;__main__&quot;:
    s1 = &quot;122B&quot;
    s2 = &quot;122&quot;

    print(s1 + &quot;: &quot;, end=&quot;&quot;)
    check(s1)

    print(s2 + &quot;: &quot;, end=&quot;&quot;)
    check(s2)

# This code is contributed by Susobhan Akhuli

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:

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(&quot;Input is an integer&quot;);
        }
        else {
            try {
                String str = String.valueOf(input);
                if (Integer.compare(Integer.parseInt(str),
                                    (Integer)input)
                    == 0) {
                    System.out.println(
                        &quot;Input is an integer&quot;);
                }
                else {
                    System.out.println(&quot;Input is a string&quot;);
                }
            }
            catch (NumberFormatException e) {
                System.out.println(&quot;Input is a string&quot;);
            }
        }
    }
    public static void main(String[] args)
    {
        Object s1 = &quot;122B&quot;;
        Object s2 = 122;

        System.out.print(s1 + &quot;: &quot;);
        check(s1);

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

// This code is contributed by Susobhan Akhuli

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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 



Last Updated : 26 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads