ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.