Home »
Java Programs »
Java Conversion Programs
Java program to convert a string into a short integer
Given/input a string, we have to convert it into a short integer.
Submitted by Nidhi, on March 15, 2022
Problem statement
In this program, we will read a numeric string from the user and convert the input string into a short integer using 2 different methods.
Java program to convert a string into a short integer
The source code to convert a string into a short integer is given below. The given program is compiled and executed successfully.
// Java program to convert a string
// into a short integer
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner X = new Scanner(System.in);
String str;
System.out.print("Enter string: ");
str = X.next();
short shortVal = 0;
//Using shortValue() method.
shortVal = Short.valueOf(str).shortValue();
System.out.println("Short value: " + shortVal);
//Using parseShort() method.
shortVal = Short.parseShort(str);
System.out.println("Short value: " + shortVal);
}
}
Output
Enter string: 28125
Short value: 28125
Short value: 28125
Explanation
In the above program, we imported java.util.Scanner to read input from the user. And, created a Main class that contains a method main().
The main() method is the entry point for the program, here we read a string from the user using the Scanner class. Then we converted the input string into a short integer using two different methods and printed the result.
Java Conversion Programs »