Método Java Inteiro valueOf()
O valor de() método é um método estático que retorna o objeto inteiro relevante que contém o valor do argumento passado. O argumento pode ser um tipo de dados primitivo, String, etc. três diferentes tipos de método Java valueOf() que podem ser diferenciados dependendo de seu parâmetro.
Estes são:
- Método Java inteiro valueOf (int i)
- Método Java inteiro valueOf (String s)
- Método Java inteiro valueOf (String s, int radix)
1. Método Java inteiro valueOf (int i)
O valorOf(int i) método de Java inteiro class retorna uma instância Integer representando o valor int especificado. Este método sempre aceitará valores no intervalo de -128 a 127 e poderá armazenar em cache outros valores fora desse intervalo.
2. Método Java inteiro valueOf (String s)
O valorOf (String s) é um método embutido de Java que é usado para retornar um objeto inteiro contendo o valor da string especificada. O argumento é interpretado como um número inteiro decimal assinado. Em outras palavras, este método retorna um objeto Inteiro igual ao valor de:
new Integer(Integer.parseInt(s)).
3. Método Java inteiro valueOf (String s, int radix)
O valueOf (String s, raiz interna) O método é usado para retornar um objeto Integer contendo o valor extraído da string especificada quando analisado com a base fornecida pelo segundo argumento. Em outras palavras, este método retorna um objeto Inteiro igual ao valor de:
new Integer(Integer.parseInt(s, radix))
Sintaxe:
Seguem a declaração de valor de() método:
public static Integer valueOf(int i) public static Integer valueOf(String s) throws NumberFormatException public static Integer valueOf(String s, int radix) throws NumberFormatException
Parâmetro:
| Tipo de dados | Parâmetro | Descrição | Obrigatório/Opcional |
|---|---|---|---|
| interno | eu | É um valor int especificado pelo usuário e usado na conversão do objeto Integer. | Obrigatório |
| Corda | é | É um tipo de String que será analisado em um objeto inteiro. | Obrigatório |
| interno | raiz | É do tipo inteiro e usado na conversão do objeto string. | Obrigatório |
Retorna:
| Método | Devoluções |
|---|---|
| valorOf(int i) | Retorna uma instância Integer contendo o valor do parâmetro especificado int i. |
| valorOf (String s) | Retorna uma instância Integer contendo o valor representado pelo argumento string. |
| valueOf (String s, raiz interna) | Retorna uma instância Integer contendo o valor representado pelo argumento string na raiz especificada. |
Exceções:
NumberFormatException: Ele lança uma exceção quando a String de entrada em relação à base especificada não é um int analisável.
Versão de compatibilidade:
Java 1.5 e superior
Exemplo 1
public class IntegerValueOfExample1 { @SuppressWarnings('static-access') public static void main(String[] args) { Integer a = 35; Integer b = -45; //It returns a Integer instance representing the specified int value System.out.println('Value = ' + a.valueOf(2)); System.out.println('Value = ' + b.valueOf(-5)); } } Teste agora Saída:
Value = 2 Value = -5
Exemplo 2
public class IntegerValueOfExample2 { @SuppressWarnings('static-access') public static void main(String[] args) { Integer i = 10; String str1 = '355'; String str2 = '-355'; // It will return a Integer instance representing the specified string System.out.println('Output Value = ' + i.valueOf(str1)); System.out.println('Output Value = ' + i.valueOf(str2)); } } Teste agora Saída:
Output Value = 355 Output Value = -355
Exemplo 3
public class IntegerValueOfExample3 { public static void main(String[] args)throws NumberFormatException { String strValue = '234'; System.out.print('Desired Value is: '+strValue); int radix = 8; System.out.print('
Base Number is: '+radix); // print the value in decimal format System.out.println('
Integer Value: ' + Integer.valueOf(strValue, radix)); } } Teste agora Saída:
Desired Value is: 234 Base Number is: 8 Integer Value: 156
Exemplo 4
import java.util.Scanner; public class IntegerValueOfExample4 { public static void main(String[] args)throws NumberFormatException { //Input desired value from the console System.out.print('Enter Desired Value: '); Scanner scan = new Scanner(System.in); String strValue = scan.nextLine(); //Input base number from the console System.out.print('Enter Base Number: '); int radix = scan.nextInt(); scan.close(); // print the output in decimal format System.out.println('Output Value: ' +Integer.valueOf(strValue, radix)); } } Teste agora Saída:
Enter Desired Value: CDEF Enter Base Number: 16 Output Value: 52719
Exemplo 5
import java.util.Scanner; public class IntegerValueOfExample5 { public static void main(String[] args)throws NumberFormatException { //Enter input from user console System.out.print('Enter Desired Value: '); Scanner scan = new Scanner(System.in); String strVal = scan.nextLine(); scan.close(); //Print the output value in decimal format System.out.println('Integer Value:' + Integer.valueOf(strVal)); } } Teste agora Saída:
Enter Desired Value: ABCDEF Exception in thread 'main' java.lang.NumberFormatException: For input string: 'ABCDEF' at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.valueOf(Integer.java:983) at myPackage.IntegerValueOfExample5.main(IntegerValueOfExample5.java:13)