Java >> Tutoriel Java >  >> Tag >> class

Méthode Java Integer class toBinaryString() avec exemple

Méthode classe entière versBinaryString()

  • méthode toBinaryString() est disponible dans le package java.lang.
  • méthode toBinaryString() est utilisé pour représenter une chaîne binaire du paramètre donné [valeur] de type entier sous la forme d'un entier non signé en binaire (base 2).
  • méthode toBinaryString() est une méthode statique, elle est également accessible avec le nom de la classe et si nous essayons d'accéder à la méthode avec l'objet de la classe, nous n'obtiendrons pas non plus d'erreur.
  • méthode toBinaryString() ne lève pas d'exception au moment de la conversion d'entier en chaîne binaire.

Syntaxe :

    public static String ToBinaryString(int value);

Paramètre(s) :

  • int value – représente la valeur entière à convertir.

Valeur renvoyée :

Le type de retour de cette méthode est int, elle retourne la chaîne binaire du paramètre donné qui représente la valeur entière non signée.

Exemple :

// Java program to demonstrate the example 
// of toBinaryString(int value) method of Integer class

public class ToBinaryStringOfIntegerClass {
    public static void main(String[] args) {
        // Variables initialization
        int i1 = 10;
        int i2 = 20;
        int i3 = 30;
        int i4 = Integer.MAX_VALUE;
        int i5 = Integer.MIN_VALUE;

        // Integer instance creation
        Integer value = new Integer(i1);

        // It represents binary string of the given
        // integer type i2 argument
        String s = value.toBinaryString(i2);

        // Display Binary String Representation
        System.out.println("value.toBinaryString(i2): " + s);

        // It represents binary string of the given
        // integer type i3 argument
        s = value.toBinaryString(i3);

        // Display Binary String Representation
        System.out.println("value.toBinaryString(i3): " + s);

        // It represents binary string of the given
        // integer type i4 argument
        s = value.toBinaryString(i4);

        // Display Binary String Representation
        System.out.println("value.toBinaryString(i4): " + s);

        // It represents binary string of the given
        // integer type i5 argument
        s = value.toBinaryString(i5);

        // Display Binary String Representation
        System.out.println("value.toBinaryString(i5): " + s);
    }
}

Sortie

value.toBinaryString(i2): 10100
value.toBinaryString(i3): 11110
value.toBinaryString(i4): 1111111111111111111111111111111
value.toBinaryString(i5): 10000000000000000000000000000000

Balise Java