Questoes de Cetificação

2 respostas
L

Resposta d . Alguem poderia me explicar o porquê ?? Alguem poderia tb explicar-me essa nomenclatura : char a = 0x0041;

Question 19

class E {

static byte a = (byte)127;

static byte b = (byte)128;

static byte c = (byte)255;

static byte d = (byte)256;

public static void main(String args[]) {

System.out.print(a + " " + b + " " + c + " " + d);

}

}

What is the result of attempting to compile and run the above program?

a. 	Prints: 127 128 255 256

b. 	Prints: 127 128 255 0

c. 	Prints: 127 -1 -127 0

d. 	Prints: 127 -128 -1 0

e. 	Runtime Exception

f. 	Compiler Error

g. 	None of the Above

2 Respostas

ricardolecheta

este 0x indica que o numero está na base hexadecimal:

public static void main(String[] args) { char a = 0x0041; // hexadecimal: corresponde ao caracter 'A' System.out.println(a); System.out.println((int) a); // valor inteiro -> 65 System.out.println((int) 'A'); System.out.println(Integer.toHexString(65)); // valor hex de 65 }

public static void main(String[] args) { // byte -> 127 byte b1 = 127; byte b2 = (byte) 128; // o compilador avisa para fazer cast em um byte só cabe 127 byte b3 = (byte) 129; byte b4 = (byte) 130; byte b5 = (byte) 131; System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }

até o 127 vai tranquilho, mas 128 nao cabe num byte entao:

como o 128 estourou o tamanho para um byte o java faz o complemento de 2, que converte o numero para binario, depois inverte os bits, isto é, o que era 0 vira 1 e vice-versa… ai soma 1.

se converter 128 para binario -> 10000000,

10000000   -> 128 em binario
   01111111   -> inverte os bits
+  00000001   -> soma 1
-> 10000000  -> isto é 128 se converter para decimal, mas o bit a esquerda que representa o sinal é 1, entao o numero ficou negativo...
e fica -128

pois o zero a esquerda representa o sinal.
0 -> positivo
1 - negativo

de uma pesquisado sobre complemento de 2 para entender melhor… :slight_smile:

L

Valeu pela exlplicação !!!

Criado 8 de janeiro de 2004
Ultima resposta 9 de jan. de 2004
Respostas 2
Participantes 2