zoukankan      html  css  js  c++  java
  • Data Types II

    In this part of the Java tutorial, we continue covering data types of Java. We cover wrapper classes, boxing and unboxing, default values, conversions, and promotions.

    Java Wrapper Classes

    Wrapper classes are object representations of primitive data types. Wrapper classes are used to represent primitive values when an Object is required. For example, Java collections only work with objects. They cannot take primitive types. Wrapper classes also include some useful methods. For example, they include methods for doing data type conversions. Placing primitive types into wrapper classes is called boxing. The reverse process is called unboxing.

    包装器类是原始数据类型的对象表示。当需要Object时,包装器类用于表示原始值。例如,Java集合仅适用于对象。它们不能采用原始类型。包装器类还包括一些有用的方法。例如,它们包括进行数据类型转换的方法。将原始类型放入包装器类称为装箱。反向过程称为拆箱。

    As a general rule, we use wrapper classes when we have some reason for it. Otherwise, we use primitive types. Wrapper classes are immutable. Once they are created, they cannot be changed. Primitive types are faster than boxed types. In scientific computing and other large scale number processing, wrapper classes may cause significant performance hit.

    通常,在有某种特殊的情况下,我们使用包装器类。否则,我们使用原始类型。包装器类是不可变的。创建它们后,就无法更改它们。基本类型比装箱类型更快。在科学计算和其它大规模数字处理中,包装类可能会严重影响性能。

    Primitive type Wrapper class Constructor arguments
    byte Byte byte or String
    short Short short or String
    int Integer int or String
    long Long long or String
    float Float float, double or String
    double Double double or String
    char Character char
    boolean Boolean boolean or String

    Table: Primitive types and their wrapper class equivalents

    The Integer class wraps a value of the primitive type int in an object. It contains constants and methods useful when dealing with an int.

    Integer类将原始类型int的值包装在对象中。它包含在处理int时有用的常量和方法。

    com/zetcode/IntegerWrapper.java
    
    package com.zetcode;
    
    public class IntegerWrapper {
    
        public static void main(String[] args) {
    
            int a = 55;
            Integer b = new Integer(a);
    
            int c = b.intValue();
            float d = b.floatValue();
    
            String bin = Integer.toBinaryString(a);
            String hex = Integer.toHexString(a);
            String oct = Integer.toOctalString(a);
    
            System.out.println(a);
            System.out.println(b);
            System.out.println(c);
            System.out.println(d);
    
            System.out.println(bin);
            System.out.println(hex);
            System.out.println(oct);
        }
    }
    

    This example works with the Integer wrapper class.

    本示例适用于Integer包装器类

    int a = 55;
    

    This line creates an integer primitive data type.

    该行创建一个整数原始数据类型

    Integer b = new Integer(a);
    

    An Integer wrapper class is created from the primitive int type.

    从原始int类型创建一个Integer包装器类

    int c = b.intValue();
    float d = b.floatValue();
    

    The intValue() method converts the Integer to int. Likewise, the floatValue() returns a float data type.

    intValue()方法将Integer转换为int。同样,floatValue()返回一个float数据类型

    String bin = Integer.toBinaryString(a);
    String hex = Integer.toHexString(a);
    String oct = Integer.toOctalString(a);
    

    These three methods return a binary, hexadecimal, and octal representation of the integer.

    这三种方法返回整数的二进制,十六进制和八进制表示形式

    This is the program output.

    $ java IntegerWrapper.java
    55
    55
    55
    55.0
    110111
    37
    67
    

    Collections are powerful tools for working with groups of objects. Primitive data types cannot be placed into Java collections. After we box the primitive values, we can put them into collections.

    集合是用于处理对象组的强大工具。原始数据类型不能放入Java集合中。将原始值装箱后,可以将它们放入集合中

    com/zetcode/Numbers.java
    
    package com.zetcode;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Numbers {
    
        public static void main(String[] args) {
            
            List<Number> ls = new ArrayList<>();
            
            ls.add(1342341);
            ls.add(new Float(34.56));
            ls.add(235.242);
            ls.add(new Byte("102"));
            ls.add(new Short("1245"));
            
            for (Number n : ls) {
                
                System.out.println(n.getClass());
                System.out.println(n);
            }
        }
    }
    

    In the example, we put various numbers into an ArrayList. An ArrayList is a dynamic, resizable array.

    在示例中,我们将各种数字放入ArrayList中。ArrayList是可调整大小的动态数组。

    List<Number> ls = new ArrayList<>();
    

    An ArrayList instance is created. In angle brackets we specify the type that the container will hold. The Number is an abstract base class for all five numeric primitive types in Java.

    创建一个ArrayList实例。在尖括号中,我们将指定容器容纳的类型。Number是Java中所有五种数字基本类型的抽象基类。

    ls.add(1342341);
    ls.add(new Float(34.56));
    ls.add(235.242);
    ls.add(new Byte("102"));
    ls.add(new Short("1245"));
    

    We add five numbers to the collection. Notice that the integer and the double value are not boxed; this is because for integer and double types the compiler performs autoboxing.

    我们将五个数字添加到集合中。请注意,整数和双精度值未装箱;这是因为对于整数和双精度类型,编译器将执行自动装箱。

    for (Number n : ls) {
    
        System.out.println(n.getClass());
        System.out.println(n);
    }
    

    We iterate through the container and print the class name and its value of each of the elements.

    我们遍历容器并打印类名称及其每个元素的值

    $ java Numbers.java
    class java.lang.Integer
    1342341
    class java.lang.Float
    34.56
    class java.lang.Double
    235.242
    class java.lang.Byte
    102
    class java.lang.Short
    1245
    

    The com.zetcode.Numbers program gives this output. Note that the two numbers were automatically boxed by the compiler.

    com.zetcode.Numbers程序提供此输出。注意,整数和双精度是由编译器自动装箱的

    Java boxing

    Converting from primitive types to object types is called boxing. Unboxing is the opposite operation. It is converting of object types back into primitive types.

    从原始类型转换为对象类型的过程称为装箱。拆箱是相反的操作。它正在将对象类型转换回原始类型

    com/zetcode/BoxingUnboxing.java
    
    package com.zetcode;
    
    public class BoxingUnboxing {
        
        public static void main(String[] args) {
    
            long a = 124235L;
            
            Long b = new Long(a);
            long c = b.longValue();
            
            System.out.println(c);
        }
    }
    

    In the code example, we box a long value into a Long object and vice versa.

    Long b = new Long(a);
    

    This line performs boxing.

    long c = b.longValue();
    

    In this line we do unboxing.

    Java autoboxing

    Java 5 introduced autoboxing. Autoboxing is automatic conversion between primitive types and their corresponding object wrapper classes. Autoboxing makes programming easier. The programmer does not need to do the conversions manually.

    Java 5引入了自动装箱。自动装箱是原始类型及其对应的对象包装器类之间的自动转换。自动装箱使编程更加容易。程序员不需要手动进行转换。

    Automatic boxing and unboxing is performed when one value is primitive type and other is wrapper class in:

    当一个值是原始类型而另一个值是包装器类时,将执行自动装箱和拆箱:

    • assignments
    • passing parameters to methods (将参数传递给方法)
    • returning values from methods (从方法返回值)
    • comparison operations (比较操作)
    • arithmetic operations (算术运算)
    Integer i = new Integer(50);
    
    if (i < 100) {
       ...
    }
    

    Inside the square brackets of the if expression, an Integer is compared with an int. The Integer object is transformed into the primitive int type and compared with the 100 value. Automatic unboxing is done.

    在if表达式的方括号内,将一个Integer与一个Int进行比较。将Integer对象转换为原始int类型,并与100值进行比较。自动取消装箱

    com/zetcode/Autoboxing.java
    
    package com.zetcode;
    
    public class Autoboxing {
    
        private static int cube(int x) {
    
            return x * x * x;
        }
        
        public static void main(String[] args) {
            
            Integer i = 10;
            int j = i;
            
            System.out.println(i);
            System.out.println(j);
            
            Integer a = cube(i);
            System.out.println(a);
        }
    }
    

    Automatic boxing and automatic unboxing is demonstrated in this code example.

    Integer i = 10;
    

    The Java compiler performs automatic boxing in this code line. An int value is boxed into the Integer type.

    Java编译器在此代码行中执行自动装箱。将int值装箱为Integer类型

    int j = i;
    

    Here an automatic unboxing takes place.

    在这里会自动开箱

    Integer a = cube(i);
    

    When we pass an Integer to the cube() method, automatic unboxing is done. When we return the computed value, automatic boxing is performed, because an int is transformed back to the Integer.

    当我们将Integer传递给cube()方法时,便完成了自动拆箱。当我们返回计算值时,将执行自动装箱,因为int会转换回Integer

    Java language does not support operator overloading. When we apply arithmetic operations on wrapper classes, automatic boxing is done by the compiler.

    Java语言不支持运算符重载。当我们对包装类应用算术运算时,自动装箱由编译器完成

    com/zetcode/Autoboxing2.java
    
    package com.zetcode;
    
    public class Autoboxing2 {
        
        public static void main(String[] args) {
            
            Integer a = new Integer(5);
            Integer b = new Integer(7);
            
            Integer add = a + b;
            Integer mul = a * b;
            
            System.out.println(add);
            System.out.println(mul);
        }
    }
    

    We have two Integer values. We perform addition and multiplication operations on these two values.

    Integer add = a + b;
    Integer mul = a * b;
    

    Unlike languages like Ruby, C#, Python, D or C++, Java does not have operator overloading implemented. In these two lines, the compiler calls the intValue() methods and converts the wrapper classes to int and later wraps the outcome back to an Integer by calling the valueOf() method.

    与Ruby,C#,Python,D或C ++等语言不同,Java没有实现运算符重载。在这两行中,编译器调用intValue()方法,并将包装器类转换为int,然后通过调用valueOf()方法将结果包装回Integer

    Java autoboxing and object interning

    Object interning is storing only one copy of each distinct object. The object must be immutable. The distinct objects are stored in an intern pool. In Java, when primitive values are boxed into a wrapper object, certain values (any boolean, any byte, any char from 0 to 127, and any short or int between -128 and 127) are interned, and any two boxing conversions of one of these values are guaranteed to result in the same object.

    对象交互仅存储每个不同对象的一个副本。该对象必须是不可变的。不同的对象存储在内部池中。在Java中,当将原始值装箱到包装对象中时,将插入某些值(任何布尔值,任何字节,0到127之间的任何char以及-128到127之间的任何short或int),并且将两个装箱转换为1这些值的其中之一保证得到相同的对象。

    According to the Java language specification, these are minimal ranges. So the behavior is implementation dependent. Object interning saves time and space. Objects obtained from literals, autoboxing and Integer.valueOf() are interned objects while those constructed with new operator are always distinct objects.

    根据Java语言规范,这些是最小范围。因此,行为取决于实现。对象交互可以节省时间和空间。从文字,自动装箱和Integer.valueOf()获得的对象是内部对象,而使用new运算符构造的对象始终是不同的对象。

    The object interning has some important consequences when comparing wrapper classes. The == operator compares reference identity of objects while the equals() method compares values.

    比较包装类时,对象交互会产生一些重要的后果。==运算符比较对象的引用标识,而equals()方法比较值

    com/zetcode/Autoboxing3.java
    
    package com.zetcode;
    
    public class Autoboxing3 {
        
        public static void main(String[] args) {
            
            Integer a = 5;	// new Integer(5);
            Integer b = 5;	// new Integer(5);
            
            System.out.println(a == b);
            System.out.println(a.equals(b));
            System.out.println(a.compareTo(b));
            
            Integer c = 155;
            Integer d = 155;
            
            System.out.println(c == d);
            System.out.println(c.equals(d));
            System.out.println(c.compareTo(d));
        }
    }
    

    The example compares some Integer objects.

    Integer a = 5; // new Integer(5);
    Integer b = 5; // new Integer(5);
    

    Two integers are boxed into Integer wrapper classes.

    System.out.println(a == b);
    System.out.println(a.equals(b));
    System.out.println(a.compareTo(b));
    

    Three different ways are used to compare the values. The == operator compares the reference identity of two boxed types. Because of the object interning, the operation results in true. If we used the new operator, two distinct objects would be created and the == operator would return false. The equals() method compares the two Integer objects numerically. It returns a boolean true or false (a true in our case.)

    使用三种不同的方法比较这些值。运算符将比较两个框式类型的引用标识。由于对象的嵌入,该运算结果为true。如果使用new运算符,则将创建两个不同的对象,并且运算符将返回false。equals()方法对两个Integer对象进行数值比较。它返回布尔值true或false(在我们的例子中为true)

    Finally, the compareTo() method also compares the two objects numerically. It returns the value 0 if this Integer is equal to the argument Integer; a value less than 0 if this Integer is numerically less than the argument Integer; and a value greater than 0 if this Integer is numerically greater than the argument Integer.

    最后,compareTo()方法对两个对象进行数值比较。如果此Integer等于参数Integer,则返回值0。如果此Integer在数值上小于参数Integer,则返回小于0的值;如果此Integer在数值上大于参数Integer,则该值大于0。

    Integer c = 155;
    Integer d = 155;
    

    We have another two boxed types. However, these values are greater than the maximum value interned (127); therefore, two distinct objects are created. This time the == operator yields false.

    $ java Autoboxing3.java
    true
    true
    0
    false
    true
    0
    

    This is the output of the program.

    Java null type

    Java has a special null type. The type has no name. As a consequence, it is impossible to declare a variable of the null type or to cast to the null type. The null represents a null reference, one that does not refer to any object. The null is the default value of reference-type variables. Primitive types cannot be assigned a null literal.

    Java具有特殊的null类型。该类型没有名称。因此,不可能声明null类型的变量或将其强制转换为null类型。null表示一个空引用,一个不引用任何对象的引用。null是引用类型变量的默认值。不能为原始类型分配为空

    In different contexts, the null means an absence of an object, an unknown value, or an uninitialized state.

    在不同的上下文中,null表示不存在对象,未知值或未初始化状态

    com/zetcode/NullType.java
    
    package com.zetcode;
    
    import java.util.Random;
    
    public class NullType {
        
        private static String getName() {
            
            Random r = new Random();
            boolen n = r..nextBoolean();
            
            if (n == true) {
                return "John";
            } else {
                return null;
            }
        }
        
        public static void main(String[] args) {
            
            String name = getName();
            
            System.out.println(name);
            
            System.out.println(null == null);
            
            if ("John".equals(name)) {
                System.out.println("His name is John");
            }
        }
    }
    

    We work with the null value in the program.

    private static String getName() {
    
        Random r = new Random();
        boolean n = r.nextBoolean();
    
        if (n == true) {
            return "John";
        } else {
            return null;
        }
    }
    

    In the getName() method we simulate a situation that a method can sometimes return a null value.

    在getName()方法中,我们模拟一种情况,该方法有时会返回空值

    System.out.println(null == null);
    

    We compare a two null values. The expression returns true.

    我们比较两个空值。该表达式返回true

    if ("John".equals(name)) {
        System.out.println("His name is John");
    }
    

    We compare the name variable to the "John" string. Notice that we call the equals() method on the "John" string. This is because if the name variable equals to null, calling the method would lead to NullPointerException.

    我们将名称变量与“ John”字符串进行比较。请注意,我们在“ John”字符串上调用了equals()方法。这是因为如果名称变量等于null,则调用该方法将导致NullPointerException

    $ java NullType.java
    null
    true
    $ java NullType.java
    null
    true
    $ java NullType.java
    John
    true
    His name is John
    

    Java default values

    Uninitialized fields are given default values by the compiler. Final fields and local variables must be initialized by developers.

    编译器会为未初始化的字段提供默认值。最终字段和局部变量必须由开发人员初始化

    The following table shows the default values for different types.

    下表显示了不同类型的默认值

    Data type Default value
    byte 0
    char 'u0000'
    short 0
    int 0
    long 0L
    float 0f
    double 0d
    Object null
    boolean false

    Table: Default values for uninitialized instance variables

    表:未初始化的实例变量的默认值

    The next example will print the default values of the uninitialized instance variables. An instance variable is a variable defined in a class for which each instantiated object of the class has a separate copy.

    下一个示例将打印未初始化的实例变量的默认值。实例变量是在类中定义的变量,该类的每个实例化对象都有一个单独的副本

    com/zetcode/DefaultValues.java
    
    package com.zetcode;
    
    public class DefaultValues {
    
        static byte b;
        static char c;
        static short s;
        static int i;
        static float f;
        static double d;
        static String str;
        static Object o;
    
        public static void main(String[] args) {
    
            System.out.println(b);
            System.out.println(c);
            System.out.println(s);
            System.out.println(i);
            System.out.println(f);
            System.out.println(d);
            System.out.println(str);
            System.out.println(o);
        }
    }
    

    In the example, we declare eight member fields. They are not initialized. The compiler will set a default value for each of the fields.

    在示例中,我们声明了八个成员字段。它们未初始化。编译器将为每个字段设置默认值

    static byte b;
    static char c;
    static short s;
    static int i;
    ...
    

    These are instance variables; they are declared outside any method. The fields are declared static because they are accessed from a static main() method. (Later in the tutorial we will talk more about static and instance variables.)

    这些是实例变量;它们在任何方法外声明。这些字段被声明为静态字段,因为它们是通过静态main()方法访问的

    $ java DefaultValues.java
    0
    
    0
    0
    0.0
    0.0
    null
    null
    

    This is the output of the program.

    Java type conversions

    We often work with multiple data types at once. Converting one data type to another one is a common job in programming. The term type conversion refers to changing of an entity of one data type into another. In this section, we will deal with conversions of primitive data types. Reference type conversions will be mentioned later in this chapter. The rules for conversions are complex; they are specified in chapter 5 of the Java language specification.

    我们经常一次处理多种数据类型。将一种数据类型转换为另一种数据类型是编程中的常见工作。术语类型转换是指将一种数据类型的实体更改为另一种。在本节中,我们将处理原始数据类型的转换。引用类型的转换将在本章后面提到。转换规则很复杂

    There are two types of conversions: implicit and explicit. Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. In explicit conversion the programmer directly specifies the converting type inside a pair of round brackets. Explicit conversion is called type casting.

    转换有两种类型:隐式转换和显式转换。隐式类型转换,也称为强制转换,是编译器自动进行的类型转换。在显式转换中,程序员直接在一对圆括号内指定转换类型。显式转换称为类型转换

    Conversions happen in different contexts: assignments, expressions, or method invocations.

    转换发生在不同的上下文中:赋值,表达式或方法调用

    int x = 456;
    long y = 34523L;
    float z = 3.455f;
    double w = 6354.3425d;
    

    In these four assignments, no conversion takes place. Each of the variables is assigned a literal of the expected type.

    在这四个分配中,没有转换发生。每个变量都被分配了预期类型的文字

    int x = 345;
    long y = x;
    
    float m = 22.3354f;
    double n = m;
    

    In this code two conversions are performed by Java compiler implicitly. Assigning a variable of a smaller type to a variable of a larger type is legal. The conversion is considered safe, as no precision is lost. This kind of conversion is called implicit widening conversion.

    在此代码中,Java编译器隐式执行了两次转换。将较小类型的变量分配给较大类型的变量是合法的。该转换被认为是安全的,因为不会损失任何精度。这种转换称为隐式加宽转换

    long x = 345;
    int y = (int) x;
    
    double m = 22.3354d;
    float n = (float) m;
    

    Assigning variables of larger type to smaller type is not legal in Java. Even if the values themselves fit into the range of the smaller type. In this case it is possible to loose precision. To allow such assignments, we have to use the type casting operation. This way the programmer says that he is doing it on purpose and that he is aware of the fact that there might be some precision lost. This kind of conversion is called explicit narrowing conversion.

    在Java中,将较大类型的变量分配给较小类型是不合法的。即使值本身适合较小类型的范围。在这种情况下,可能会降低精度。为了允许这种分配,我们必须使用类型转换操作。这样,程序员说他是故意这样做的,并且他意识到可能会丢失一些精度这一事实。这种转换称为显式缩小转换。

    byte a = 123;
    short b = 23532;
    

    In this case, we deal with a specific type of assignment conversion. 123 and 23532 are integer literals, the a, b variables are of byte and short type. It is possible to use the casting operation, but it is not required. The literals can be represented in their variables on the left side of the assignment. We deal with implicit narrowing conversion.

    在这种情况下,我们处理一种特定类型的分配转换。123和23532是整数文字,a,b变量是byte和short类型。可以使用转换操作,但不是必需的。我们称这种处理方式为隐式变窄转换。

    private static byte calc(byte x) {
    ...
    }
    byte b = calc((byte) 5);
    

    The above rule only applies to assignments. When we pass an integer literal to a method that expects a byte, we have to perform the casting operation.

    以上规则仅适用于分配。当我们将整数文字传递给需要一个字节的方法时,我们必须执行强制转换操作

    Java numeric promotions

    Numeric promotion is a specific type of an implicit type conversion. It takes place in arithmetic expressions. Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed.

    数值提升是隐式类型转换的特定类型。它发生在算术表达式中。数字提升用于将数字运算符的操作数转换为通用类型,以便可以执行操作

    int x = 3;
    double y = 2.5;
    double z = x + y;
    

    In the third line we have an addition expression. The x operand is int, the y operand is double. The compiler converts the integer to double value and adds the two numbers. The result is a double. It is a case of implicit widening primitive conversion.

    上面的第三行中有一个加法表达式。x操作数为int,y操作数为double。编译器将整数转换为双精度值,然后将两个数字相加。结果是两倍。这是隐式扩展基元转换的情况。

    byte a = 120;
    a = a + 1; // compilation error
    

    This code leads to a compile time error. In the right side of the second line, we have a byte variable a and an integer literal 1. The variable is converted to integer and the values are added. The result is an integer. Later, the compiler tries to assign the value to the a variable. Assigning larger types to smaller types is not possible without an explicit cast operator. Therefore we receive a compile time error.

    此代码导致编译时错误。在第二行的右侧,我们有一个字节变量a和一个整数1。该变量将转换为整数并添加值。结果是一个整数。以后,编译器尝试将值分配给a变量。没有显式的强制转换运算符,就不可能将较大的类型分配给较小的类型。因此,我们收到一个编译时错误

    byte a = 120;
    a = (byte) (a + 1);
    

    This code does compile. Note the usage of round brackets for the a + 1 expression. The (byte) casting operator has a higher precedence than the addition operator. If we want to apply the casting on the whole expression, we have to use round brackets.

    此代码可以编译。注意a + 1表达式中使用圆括号。(byte)强制转换运算符的优先级高于加法运算符。如果要对整个表达式应用转换,则必须使用圆括号。

    byte a = 120;
    a += 5;
    

    Compound operators perform implicit conversions automatically.

    复合运算符自动执行隐式转换

    byte u = 100;
    byte v = u++;
    

    In case of the unary increment ++, decrement -- operators, no conversion is done. The casting is not necessary.

    如果是一元递增++,减量-运算符,则不会进行任何转换

    Java boxing, unboxing conversions

    Boxing conversion converts expressions of primitive type to corresponding expressions of wrapper type. Unboxing conversion converts expressions of wrapper type to corresponding expressions of primitive type. Conversions from boolean to Boolean or from byte to Byte are examples of boxing conversions. The reverse conversions, e.g. from Boolean to boolean or from Byte to byte are examples of unboxing conversions.

    装箱转换将原始类型的表达式转换为包装器类型的对应表达式。拆箱转换将包装器类型的表达式转换为原始类型的相应表达式。从boolean到Boolean或从byte到Byte的转换是装箱转换的示例。反向转换,例如从Boolean到boolean或从Byte到byte是取消装箱转换的示例。

    Byte b = 124;
    byte c = b;
    

    In the first code line, automatic boxing conversion is performed by the Java compiler. In the second line, an unboxing conversion is done.

    在第一行代码中,自动装箱转换由Java编译器执行。在第二行中,完成了拆箱转换

    private static String checkAge(Short age) {
    ...
    }
    String r = checkAge((short) 5);
    

    Here we have boxing conversion in the context of a method invocation. We pass a short type to the method which expects a Short wrapper type. The value is boxed.

    在这里,我们在方法调用的上下文中进行装箱转换。我们将short类型传递给需要Short包装类型的方法。该值已装箱

    Boolean gameOver = new Boolean("true");
    if (gameOver) {
        System.out.println("The game is over");
    }
    

    This is an example of an unboxing conversion. Inside the if expression, the booleanValue() method is called. The method returns the value of a Boolean object as a boolean primitive.

    这是拆箱转换的示例。在if表达式内部,将调用booleanValue()方法。该方法将布尔对象的值作为布尔原型返回

    Java string conversions

    Performing string conversions between numbers and strings is very common in programming. The casting operation is not allowed because the strings and primitive types are fundamentally different types. There are several methods for doing string conversions. There is also an automatic string conversion for the + operator.

    在数字和字符串之间执行字符串转换在编程中是非常常见的。不允许进行强制转换操作,因为字符串和基本类型在根本上是不同的类型。有几种执行字符串转换的方法。+运算符还具有自动字符串转换功能。

    More about string conversions will be covered in the Strings chapter of this tutorial.

    String s = (String) 15; // compilation error
    int i = (int) "25";    // compilation error
    

    It is not possible to cast between numbers and strings. Instead, we have various methods for doing conversion between numbers and strings.

    不能在数字和字符串之间进行强制转换。相反,我们有各种方法可以在数字和字符串之间进行转换

    short age = Short.parseShort("35");
    int salary = Integer.parseInt("2400");
    float height = Float.parseFloat("172.34");
    double weight = Double.parseDouble("55.6");
    

    The parse methods of the wrapper classes convert strings to primitive types.

    包装类的parse方法将字符串转换为原始类型

    Short age = Short.valueOf("35");
    Integer salary = Integer.valueOf("2400");
    Float height = Float.valueOf("172.34");
    Double weight = Double.valueOf("55.6");
    

    The valueOf() method returns the wrapper classes from primitive types.

    valueOf()方法从原始类型返回包装器类

    int age = 17;
    double weight = 55.3;
    String v1 = String.valueOf(age);
    String v2 = String.valueOf(weight);
    

    The String class has a valueOf() method for converting various types to strings.

    String类具有valueOf()方法,用于将各种类型转换为字符串

    Automatic string conversions take place when using the + operator and one operator is a string, the other operator is not a string. The non-string operand to the + is converted to a string.

    当使用+运算符并且一个运算符是字符串,而另一个运算符不是字符串时,会自动进行字符串转换。+的非字符串操作数将转换为字符串。

    com/zetcode/AutomaticStringConversion.java
    
    package com.zetcode;
    
    public class AutomaticStringConversion {
        
        public static void main(String[] args) {
            
            String name = "Jane";
            short age = 17;
            
            System.out.println(name + " is " + age + " years old.
    ");
        }
    }
    

    In the example, we have a String data type and a short data type. The two types are concatenated using the + operator into a sentence.

    在示例中,我们有一个String数据类型和一个short数据类型。使用+运算符将这两种类型连接成一个句子

    System.out.println(name + " is " +  age + " years old.");
    

    In the expression, the age variable is converted to a String type.

    在表达式中,age变量将转换为String类型

    $ java AutomaticStringConversion.java
    Jane is 17 years old.
    

    This is the example output.

    Object reference conversion

    暂时还没学习到

    In this part of the Java tutorial, we have covered wrapper classes, boxing and unboxing, default values, conversions, and promotions.

  • 相关阅读:
    第十章 Ingress
    第九章 Service
    第八章 资源控制器
    第一章 Xshell5评估期已过问题
    第七章 yaml格式
    第六章 资源清单
    第五章 配置私有仓库Harbor
    第四章 K8s部署安装
    36 SpringBoot 在系统配置文件中动态加载配置
    Java 集合、数组 任意个数数字相加等于一个指定的数
  • 原文地址:https://www.cnblogs.com/PrimerPlus/p/13025764.html
Copyright © 2011-2022 走看看