Clase Java.Lang.Short en Java

La clase corta es una clase contenedora para el tipo primitivo short que contiene varios métodos para manejar de manera efectiva un valor corto, como convertirlo en una representación de string y viceversa. Un objeto de clase Short puede contener un solo valor corto. Hay principalmente dos constructores para inicializar un objeto corto: 
 

  • Short(short b): Crea un objeto Short inicializado con el valor proporcionado. 
     
Syntax : public Short(short b)
Parameters :
b : value with which to initialize
  •  
  • Short(String s): crea un objeto Short inicializado con el valor corto proporcionado por la representación de string. La raíz predeterminada se toma como 10. 
     
Syntax : public Short(String s) 
                    throws NumberFormatException
Parameters :
s : string representation of the short value 
Throws :
NumberFormatException : If the string provided does not represent any short value.
  •  

Métodos: 
 

  1. toString() : Devuelve la string correspondiente al valor corto. 
     
Syntax : public String toString(short b)
Parameters :
b : short value for which string representation required.
  1. valueOf() : devuelve el objeto Short inicializado con el valor proporcionado. 
     
Syntax : public static Short valueOf(short b)
Parameters :
b : a short value
  1. Otra función sobrecargada valueOf(String val,int radix) que proporciona una función similar a 
    new Short(Short.parseShort(val,radix)) 
     
Syntax : public static Short valueOf(String val, int radix)
            throws NumberFormatException
Parameters :
val : String to be parsed into short value
radix : radix to be used while parsing
Throws :
NumberFormatException : if String cannot be parsed to a short value in given radix.
  1. Otra función sobrecargada valueOf(String val) que proporciona una función similar a 
    new Short(Short.parseShort(val,10)) 
     
Syntax : public static Short valueOf(String s)
           throws NumberFormatException
Parameters :
s : a String object to be parsed as short
Throws :
NumberFormatException : if String cannot be parsed to a short value in given radix.
  1. parseShort() : devuelve un valor corto al analizar la string en la base proporcionada. Se diferencia de valueOf() en que devuelve un valor corto primitivo y valueOf() devuelve un objeto corto. 
     
Syntax : public static short parseShort(String val, int radix)
             throws NumberFormatException
Parameters :
val : String representation of short 
radix : radix to be used while parsing
Throws :
NumberFormatException : if String cannot be parsed to a short value in given radix.
  1. Otro método sobrecargado que contiene solo String como parámetro, radix se establece de forma predeterminada en 10. 
     
Syntax : public static short parseShort(String val)
             throws NumberFormatException
Parameters :
val : String representation of short 
Throws :
NumberFormatException : if String cannot be parsed to a short value in given radix.
  1. decode() : devuelve un objeto Short que contiene el valor decodificado de la string proporcionada. La string proporcionada debe tener el siguiente formato; de lo contrario, se lanzará NumberFormatException- 
    Decimal- (Signo)Decimal_Number 
    Hex- (Signo)”0x”Hex_Digits 
    Hex- (Signo)”0X”Hex_Digits 
    Octal- (Signo)”0″Octal_Digits 
     
Syntax : public static Short decode(String s)
             throws NumberFormatException
Parameters :
s : encoded string to be parsed into short val
Throws :
NumberFormatException : If the string cannot be decoded into a short value
  1. byteValue() : devuelve un valor de byte correspondiente a este objeto corto. 
     
Syntax : public byte byteValue()
  1. shortValue() : devuelve un valor corto correspondiente a este objeto corto. 
     
Syntax : public short shortValue()
  1. intValue() : devuelve un valor int correspondiente a este objeto corto. 
     
Syntax : public int intValue()
  1. longValue() : devuelve un valor largo correspondiente a este objeto corto. 
     
Syntax : public long longValue()
  1. doubleValue() : devuelve un valor doble correspondiente a este objeto corto. 
     
Syntax : public double doubleValue()
  1. floatValue() : devuelve un valor flotante correspondiente a este objeto corto. 
     
Syntax : public float floatValue()
  1. hashCode() : devuelve el código hash correspondiente a este objeto corto. 
     
Syntax : public int hashCode()
  1. equals() : Se utiliza para comparar la igualdad de dos objetos Short. Este método devuelve verdadero si ambos objetos contienen el mismo valor corto. Debe usarse solo si se verifica la igualdad. En todos los demás casos, se debe preferir el método compareTo. 
     
Syntax : public boolean equals(Object obj)
Parameters :
obj : object to compare with
  1. compareTo() : se usa para comparar dos objetos cortos para la igualdad numérica. Esto debe usarse cuando se comparan dos valores cortos para la igualdad numérica, ya que diferenciaría entre valores menores y mayores. Devuelve un valor menor que 0,0, valor mayor que 0 para menor que, igual a y mayor que. 
     
Syntax : public int compareTo(Short b)
Parameters :
b : Short object to compare with
  1. compare() : se utiliza para comparar dos valores cortos primitivos para la igualdad numérica. Como es un método estático, puede usarse sin crear ningún objeto de Short. 
     
Syntax : public static int compare(short x,short y)
Parameters :
x : short value
y : another short value
  1. reverseBytes() : devuelve un valor corto primitivo invirtiendo el orden de los bits en forma de complemento a dos del valor corto dado. 
     
Syntax : public static short reverseBytes(short val)
Parameters :
val : short value whose bits to reverse in order.
  1.  

Java

// Java program to illustrate
// various methods of Short class
public class Short_test
{
 
    public static void main(String[] args)
    {
 
        short b = 55;
        String bb = "45";
         
        // Construct two Short objects
        Short x = new Short(b);
        Short y = new Short(bb);
 
        // toString()
        System.out.println("toString(b) = " + Short.toString(b));
 
        // valueOf()
        // return Short object
        Short z = Short.valueOf(b);
        System.out.println("valueOf(b) = " + z);
        z = Short.valueOf(bb);
        System.out.println("ValueOf(bb) = " + z);
        z = Short.valueOf(bb, 6);
        System.out.println("ValueOf(bb,6) = " + z);
 
        // parseShort()
        // return primitive short value
        short zz = Short.parseShort(bb);
        System.out.println("parseShort(bb) = " + zz);
        zz = Short.parseShort(bb, 6);
        System.out.println("parseShort(bb,6) = " + zz);
         
        //decode()
        String decimal = "45";
        String octal = "005";
        String hex = "0x0f";
         
        Short dec = Short.decode(decimal);
        System.out.println("decode(45) = " + dec);
        dec = Short.decode(octal);
        System.out.println("decode(005) = " + dec);
        dec = Short.decode(hex);
        System.out.println("decode(0x0f) = " + dec);
 
        System.out.println("bytevalue(x) = " + x.byteValue());
        System.out.println("shortvalue(x) = " + x.shortValue());
        System.out.println("intvalue(x) = " + x.intValue());
        System.out.println("longvalue(x) = " + x.longValue());
        System.out.println("doublevalue(x) = " + x.doubleValue());
        System.out.println("floatvalue(x) = " + x.floatValue());
         
        int hash = x.hashCode();
        System.out.println("hashcode(x) = " + hash);
         
        boolean eq = x.equals(y);
        System.out.println("x.equals(y) = " + eq);
         
        int e = Short.compare(x, y);
        System.out.println("compare(x,y) = " + e);
         
        int f = x.compareTo(y);
        System.out.println("x.compareTo(y) = " + f);
         
         
        short to_rev = 45;
        System.out.println("Short.reverseBytes(to_rev) = " + Short.reverseBytes(to_rev));
    }
}

Producción : 
 

toString(b) = 55
valueOf(b) = 55
ValueOf(bb) = 45
ValueOf(bb,6) = 29
parseShort(bb) = 45
parseShort(bb,6) = 29
decode(45) = 45
decode(005) = 5
decode(0x0f) = 15
bytevalue(x) = 55
shortvalue(x) = 55
intvalue(x) = 55
longvalue(x) = 55
doublevalue(x) = 55.0
floatvalue(x) = 55.0
hashcode(x) = 55
x.equals(y) = false
compare(x,y) = 10
x.compareTo(y) = 10
Short.reverseBytes(to_rev) = 11520

Este artículo es una contribución de Rishabh Mahrsee . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *