Write Java program to Convert string into a short integer


This is a Java program that demonstrates how to convert a string to a short integer using two different methods: Short.valueOf().shortValue() and Short.parseShort().

  • In this program, a Scanner object named input is created to read input from the user. The program prompts the user to enter a number and reads the input as a string using the Scanner.next() method. The string is then printed using the System.out.println() method.
  • Next, a short integer variable short_val is initialized to 0.
  • The program then uses the Short.valueOf().shortValue() method to convert the string to a short integer. This method first calls the Short.valueOf() method, which returns a Short object that represents the value of the string.
  • The Short.shortValue() method is then called on the returned object to get the short integer value. The short integer value is then assigned to the short_val variable, and the value is printed using the System.out.println() method.
  • Finally, the program uses the Short.parseShort() method to convert the string to a short integer. This method directly parses the string and returns the short integer value. The short integer value is then assigned to the short_val variable, and the value is printed using the System.out.println() method.

Source Code

import java.util.Scanner;
public class StringTo_ShortInt
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Number : ");
		String str = input.next();
		System.out.println("String Value : " + str);
 
		short short_val = 0;
 
		//shortValue() Method 1
		short_val = Short.valueOf(str).shortValue();
		System.out.println("Short Value Using shortValue() method : " + short_val);
 
		//parseShort() Method 2
		short_val = Short.parseShort(str);
		System.out.println("Short Value Using parseShort() method : " + short_val);
	}
}

Output

Enter the Number : 3234
String Value : 3234
Short Value Using shortValue() method : 3234
Short Value Using parseShort() method : 3234