Java Convert int to String - Diferentes formas de conversão

Convertendo um int para uma String é uma conversão de tipo importante. Muitas operações podem ser realizadas em uma string, embora estejamos limitados quando se trata de números inteiros. Temos uma lista ampla e variada de métodos integrados na classe String que nos ajudam a realizar operações sem complicações. 

Suponha que sejamos obrigados a concatenar dois números inteiros, então isso se tornaria tedioso para nós. Precisamos passar por isso, pois precisamos lidar com o sistema numérico correspondente ao qual estaremos jogando matemática dentro do sistema numérico. Mas para converter inteiros em strings em Java, temos alguns métodos e classes embutidos que tornam nosso trabalho muito fácil. 

Dica: Geralmente convertemos tipos de membros de dados de classes primitivas, embora tenhamos o conceito de Classes de wrapper para Strings porque na programação prática em java lidamos com strings.

Maneiras de converter int em uma string em Java

Convertendo Inteiros para Strings envolve o uso de classes inteiras toString() ou String.valueOf() para conversão direta. String.formato() é outro método que oferece opções de formatação flexíveis. Usando StringBuilder ou StringBuffer anexar valores inteiros como strings é eficiente para manipulação extensiva de strings.

Existem certos métodos para conversões de inteiro em string mencionados abaixo:

  1. Usando o toString() método da classe Integer
  2. Usando o valorOf() método da classe String
  3. Usando Inteiro(int).toString() método da classe Integer
  4. Usando concatenação com uma string vazia.

1. Usando o método toString() da classe Integer

A classe Integer possui um método estático toString() que retorna um objeto String que representa o parâmetro int especificado. O argumento é convertido e retornado como uma instância de string. Se o número for negativo o sinal será preservado.

Exemplo:

Java
   // Java Program to Illustrate Integer to String Conversions   // Using toString() Method of Integer Class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Custom input integers      int     a     =     1234  ;      int     b     =     -  1234  ;      // Converting integer to string      // using toString() method      String     str1     =     Integer  .  toString  (  a  );      String     str2     =     Integer  .  toString  (  b  );      // Printing the above strings that      // holds integer      System  .  out  .  println  (  'String str1 = '     +     str1  );      System  .  out  .  println  (  'String str2 = '     +     str2  );      }   }   

Saída
String str1 = 1234 String str2 = -1234  


2. Usando o método valueOf() da classe String

A classe String possui um método estático valorOf() que pode ser usado para converter o número inteiro em string conforme mostrado abaixo:

Exemplo:

Java
   // Java Program to Illustrate Integer to String Conversions   // Using valueOf() Method of String class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Custom integer input      int     c     =     1234  ;      // Converting above integer to string      // using valueOf() Method      String     str3     =     String  .  valueOf  (  c  );      // Printing the integer stored in above string      System  .  out  .  println  (  'String str3 = '     +     str3  );      }   }   

Saída
String str3 = 1234  


3. Usando Inteiro(int).toString() Método da classe inteira

É diferente do método 1 proposto acima, pois neste método usamos uma instância da classe Integer para invocar seu método toString(). 

Exemplo:

Java
   // Java Program to Illustrate   // Integer to String Conversions   // Using toString() Method of   // Integer Class   // Importing required classes   import     java.util.*  ;   // Main class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Custom input integer      int     d     =     1234  ;      // Converting integer to string      // using toString() method of Integer class      String     str4     =     new     Integer  (  d  ).  toString  ();      // Printing the integer value stored in above string      System  .  out  .  println  (  'String str4 = '     +     str4  );      }   }   

Saída
String str4 = 1234  

Explicação: Se a variável for do tipo primitivo (int) é melhor usar Integer.toString(int) ou String.valueOf(int). Mas se a variável já for uma instância de Integer (classe wrapper do tipo primitivo int) é melhor apenas invocar seu método toString() conforme mostrado acima. 

Observação: Este método não é eficiente porque uma instância da classe Integer é criada antes da execução da conversão. E obsoleto e marcado como remoção.


4. Usando concatenação com uma string vazia

Aqui declararemos uma string vazia e usando o operador '+' simplesmente armazenaremos o resultado como uma string. Agora, com isso, conseguimos anexar e concatenar essas strings. 

Exemplo:

Java
   // Java Program to Illustrate Integer to String Conversions   // Using Concatenation with Empty String   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Custom integer values      int     a     =     1234  ;      int     b     =     -  1234  ;      // Concatenating with empty strings      String     str1     =     ''     +     a  ;      String     str2     =     ''     +     b  ;      // Printing the concatenated strings      System  .  out  .  println  (  'String str1 = '     +     str1  );      System  .  out  .  println  (  'String str2 = '     +     str2  );      }   }   

Saída
String str1 = 1234 String str2 = -1234  


Métodos avançados para converter int em string

Existem certos métodos avançados mencionados abaixo:

  1. Usando a classe DecimalFormat
  2. Usando a classe StringBuffer
  3. usando a classe StringBuilder 
  4. Usando raiz especial e raiz personalizada

1. Usando a classe DecimalFormat

Formato Decimal é uma classe que formata um número em uma String. 

Exemplo:

Java
   // Java Program to Illustrate   // Integer to String Conversions   // Using DecimalFormat Class   // Importing required classes   import     java.text.DecimalFormat  ;   // Main class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Input integer value      int     e     =     12345  ;      // Creating an object of DecimalFormat class      // inside main() method      DecimalFormat     df     =     new     DecimalFormat  (  '####'  );      // Converting above integral value to string      String     Str5     =     df  .  format  (  e  );      // Printing the value stored in above string      System  .  out  .  println  (  Str5  );      }   }   

Saída
12345  

Dica: Usando este método, podemos especificar o número de casas decimais e o separador de vírgula para facilitar a leitura.


2. Usando a classe StringBuffer   

StringBuffer é uma classe usada para concatenar vários valores em uma String. 

Exemplo 1:

Java
   // Java Program to Illustrate   // Integer to String Conversions   // Using StringBuffer Class   // Main class   class   Geeks     {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Integer input value      int     f     =     1234  ;      // Creating an object of StringBuffer class      StringBuffer     sb     =     new     StringBuffer  ();      sb  .  append  (  f  );      String     str6     =     sb  .  toString  ();      System  .  out  .  println  (  'String str6 = '     +     str6  );      }   }   

Saída
String str6 = 1234  


Exemplo 2:

Java
   // Java Program to Illustrate   // Integer to String Conversions   // Using StringBuffer Class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      String     str6      =     new     StringBuffer  ().  append  (  1234  ).  toString  ();      System  .  out  .  println  (  'String str6 = '     +     str6  );      }   }   

Saída
String str6 = 1234  


3. Usando a classe StringBuilder

StringBuilder funciona de forma semelhante, mas não é seguro para threads como StringBuffer. 

Exemplo 1:

Java
   // Java Program to Illustrate   // Integer to String Conversions   // Using StringBuilder Class   // Main class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Input integer      int     g     =     1234  ;      // Creating an object of StringBuilder class      // inside main() method      StringBuilder     sb     =     new     StringBuilder  ();      sb  .  append  (  g  );      String     str7     =     sb  .  toString  ();      // Printing the value stored in above string      System  .  out  .  println  (  'String str7 = '     +     str7  );      }   }   

Saída
String str7 = 1234  


Exemplo 2:

Java
   // Java Program to Illustrate Different Ways for   // Integer to String Conversions   // Using StringBuilder Class   // Main class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      String     str7      =     new     StringBuilder  ().  append  (  1234  ).  toString  ();      // Printing the value stored in above string      System  .  out  .  println  (  'String str7 = '     +     str7  );      }   }   

Saída
String str7 = 1234  

Observação: Todos os exemplos acima usam a base (base) 10. A seguir estão métodos convenientes para converter em sistemas binários octais e hexadecimais. O sistema numérico personalizado arbitrário também é suportado. 


Convertendo int em string com base diferente

Também podemos converter int em String em bases diferentes. Abaixo estão alguns dos métodos importantes mencionados que ajudam a converter int em String com bases diferentes.

1. Usando Radix Especial 

Exemplo 1 : Convertendo int (base 2 ou número binário) em String usando Classe inteira método toBinary().

Java
   // Java Program to Illustrate Integer to String Conversions   // Using Special Radix In Binary Numbers   // Main class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Input integer      int     h     =     255  ;      String     binaryString     =     Integer  .  toBinaryString  (  h  );      // Printing the binary number stored in above string      System  .  out  .  println  (  binaryString  );      }   }   

Saída
11111111  

Explicação : 11111111 é a representação binária do número 255.


Exemplo 2: Convertendo int (base 8 ou número octal) em String usando Classe inteira método toOctalString().

Java
   // Java Program to Illustrate Integer to String Conversions   // Using Special Radix In Octal Numbers   // Main class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Custom input integer      int     i     =     255  ;      String     octalString     =     Integer  .  toOctalString  (  i  );      // Printing the octal number stored in above string      System  .  out  .  println  (  octalString  );      }   }   

Saída
377  

Explicação: 377 é a representação octal do número 255. 


Exemplo 3: Convertendo int (base 10 ou número hexadecimal) em String usando Classe inteira método toHexString().

Java
   // Java Program to Illustrate Integer to String Conversions   // Using Special Radix In Hexadecimal Numbers   // Main class   class   Geeks   {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Custom input integer      int     j     =     255  ;      String     hexString     =     Integer  .  toHexString  (  j  );      // Printing the hexadecimal number      // stored in above string      System  .  out  .  println  (  hexString  );      }   }   

Saída
ff  

Explicação: O aff é a representação hexadecimal do número 255.

2. Base/Radix personalizada 

Abordagem: Estamos usando o método toString() da classe Integer para convertê-lo em uma string onde, adicionalmente, passaremos um valor como um argumento conhecido como raiz. Pode-se usar qualquer outra base/raiz personalizada ao converter um int em uma string. No exemplo abaixo, estamos considerando o sistema numérico de base 7 para fins ilustrativos. 

Exemplo: Convertendo int (base 7 ou número de raiz personalizado) em String usando Classe inteira método toString (int I int raiz).

Java
   // Java Program to Illustrate Integer to String Conversions   // Using Custom Radix   // Main class   class   Geeks     {      // Main driver method      public     static     void     main  (  String     args  []  )      {      // Input integer value      int     k     =     255  ;      // Setting base as 7 converting integer to string      // using toString() method and      // storing it into a string      String     customString     =     Integer  .  toString  (  k       7  );      // Printing value stored in above string      System  .  out  .  println  (  customString  );      }   }   

Saída
513  

Observação: 513 é a representação do número 255 quando escrito no sistema de base 7.