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.
Program/Source Code:
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().
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.
Program/Source Code:
The source code to convert a string into a short integer is given below. The given program is compiled and executed successfully.
Output:
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().