📌  相关文章
📜  如何通过示例在Java中将 Short 值转换为 String 值

📅  最后修改于: 2022-05-13 01:54:54.978000             🧑  作者: Mango

如何通过示例在Java中将 Short 值转换为 String 值

在Java中给定一个 Short 值,任务是将这个 short 值转换为字符串类型。

例子:

Input: 1
Output: "1"

Input: 3
Output: "3"

方法 1:(使用 +运算符)
一种方法是创建一个字符串变量,然后将短值附加到字符串变量。这将直接将短值转换为字符串并将其添加到字符串变量中。

下面是上述方法的实现:

示例 1:

// Java Program to convert short value to String value
  
class GFG {
  
    // Function to convert short value to String value
    public static String
    convertShortToString(short shortValue)
    {
  
        // Convert short value to String value
        // using + operator method
        String stringValue = "" + shortValue;
  
        return (stringValue);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // The short value
        short shortValue = 1;
  
        // The expected string value
        String stringValue;
  
        // Convert short to string
        stringValue
            = convertShortToString(shortValue);
  
        // Print the expected string value
        System.out.println(
            shortValue
            + " after converting into string = "
            + stringValue);
    }
}
输出:
1 after converting into string = 1

方法2:(使用 String.valueOf() 方法)
最简单的方法是使用Java.lang 包中 String 类的valueOf() 方法。此方法采用要解析的短值并从中返回字符串类型的值。

句法:

String.valueOf(shortValue);

下面是上述方法的实现:

示例 1:

// Java Program to convert short value to String value
  
class GFG {
  
    // Function to convert short value to String value
    public static String
    convertShortToString(short shortValue)
    {
  
        // Convert short value to String value
        // using valueOf() method
        return String.valueOf(shortValue);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // The short value
        short shortValue = 1;
  
        // The expected string value
        String stringValue;
  
        // Convert short to string
        stringValue
            = convertShortToString(shortValue);
  
        // Print the expected string value
        System.out.println(
            shortValue
            + " after converting into string = "
            + stringValue);
    }
}
输出:
1 after converting into string = 1