Q:

Java program to convert a string into a short integer

belongs to collection: Java Conversion Programs

0

Java program to convert a string into a short integer

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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().

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to convert byte into the string... >>
<< Java program to convert string to byte...