Introdução
Neste laboratório, aprenderemos sobre o método toString() da classe Integer em Java. Veremos como usar este método para obter a representação String de um objeto Integer. Também veremos alguns exemplos para entender seu uso.
Neste laboratório, aprenderemos sobre o método toString() da classe Integer em Java. Veremos como usar este método para obter a representação String de um objeto Integer. Também veremos alguns exemplos para entender seu uso.
Crie um novo arquivo Java chamado IntegerToString.java.
public class IntegerToString {
public static void main(String[] args) {
// código a ser adicionado
}
}
Nesta etapa, criaremos um objeto Integer e, em seguida, usaremos o método toString() para converter esse objeto Integer em uma String.
public class IntegerToString {
public static void main(String[] args) {
// criar um objeto Integer
Integer num = 35;
// converter integer para string
String str = num.toString();
// imprimir a string
System.out.println("String representation of the Integer: " + str);
}
}
Saída:
String representation of the Integer: 35
O método toString() também funciona para inteiros negativos. Nesta etapa, converteremos um inteiro negativo para sua representação em String.
public class IntegerToString {
public static void main(String[] args) {
// criar um objeto Integer negativo
Integer num = -18;
// converter inteiro negativo para string
String str = num.toString();
// imprimir a string
System.out.println("String representation of the Integer: " + str);
}
}
Saída:
String representation of the Integer: -18
Nesta etapa, criaremos um inteiro de entrada usando Scanner e, em seguida, usaremos o método toString() para obter sua representação em String.
import java.util.Scanner;
public class IntegerToString {
public static void main(String[] args) {
// criar objeto scanner
Scanner sc = new Scanner(System.in);
// receber inteiro de entrada do usuário
System.out.print("Enter an integer: ");
int num = sc.nextInt();
// converter inteiro para string
String str = Integer.toString(num);
// imprimir a string
System.out.println("String representation of the entered integer: " + str);
}
}
Saída:
Enter an integer: 56
String representation of the entered integer: 56
Na etapa 4, não tratamos o caso em que a entrada não é um inteiro. Nesta etapa, lidaremos com a exceção quando a entrada não for um inteiro válido.
import java.util.Scanner;
public class IntegerToString {
public static void main(String[] args) {
// criar objeto scanner
Scanner sc = new Scanner(System.in);
try {
// receber inteiro de entrada do usuário
System.out.print("Enter an integer: ");
int num = sc.nextInt();
// converter inteiro para string
String str = Integer.toString(num);
// imprimir a string
System.out.println("String representation of the entered integer: " + str);
} catch(Exception e) {
System.out.println("Invalid input");
}
}
}
Saída:
Enter an integer: 34
String representation of the entered integer: 34
Em Java, podemos usar o método toBinaryString() da classe Integer para converter um inteiro em sua representação em string binária.
public class IntegerToString {
public static void main(String[] args) {
// criar um inteiro
int num = 10;
// converter inteiro para string binária
String binaryString = Integer.toBinaryString(num);
// imprimir string binária
System.out.println("Binary string representation of the Integer: " + binaryString);
}
}
Saída:
Binary string representation of the Integer: 1010
Em Java, podemos usar o método toHexString() da classe Integer para converter um inteiro em sua representação em string hexadecimal.
public class IntegerToString {
public static void main(String[] args) {
// criar um inteiro
int num = 255;
// converter inteiro para string hexadecimal
String hexString = Integer.toHexString(num);
// imprimir string hexadecimal
System.out.println("Hexadecimal string representation of the Integer: " + hexString);
}
}
Saída:
Hexadecimal string representation of the Integer: ff
Neste laboratório, aprendemos como usar o método toString() da classe Integer para converter um inteiro em uma representação de string. Também aprendemos como lidar com entradas inválidas e converter um inteiro em uma representação de string binária ou hexadecimal. Este método é útil quando precisamos converter um inteiro em uma string para uso em diferentes contextos.