valueOf x Construtor

pessoal estou estudando para SCJP e nao consigo entender para que existe o metodo valueOf se no construtor do wraper eu posso por o valor em String que ele ira me retornar o classe!!!

o valueOf é um método estático da classe, logo não precisa instanciar um objeto para fazer esta conversão.

Valeu.

sim… mais eu tenho o parseXXX que retorna um tipo primitivo!! eu uso ele para fazer a conversao quando eu nao precisar d uma nova instancia!!

Por exemplo a classe Integer.

Integer.parseInt(String) - retorna um int
Integer.valueOf(String) - retorna um objeto Integer

sim isso eu sei… mais com o boxing o valueOf ainda eh usado???

Com o construtor você obriga o java a criar uma nova instância. Com o valueOf, o Java está autorizado a te retornar um objeto do cache.

Por exemplo:

[code]Integer x = Integer.valueOf(2);
Integer y = Integer.valueOf(2);

x == y; //Isso é true

Integer a = new Integer(2);
Integer b = new Integer(2);

a == b; //Isso é false.[/code]

Existe um custo de performance associado ao boxing. E nem sempre ele gera uma sintaxe clara… especialmente se você estiver misturando wrappers e tipos primitivos. Por fim, tem que manter a compatibilidade com o código antigo.

ahhh entendiiiii!! bem citado cara

[quote=ViniGodoy]Com o construtor você obriga o java a criar uma nova instância. Com o valueOf, o Java está autorizado a te retornar um objeto do cache.

Por exemplo:

[code]Integer x = Integer.valueOf(2);
Integer y = Integer.valueOf(2);

x == y; //Isso é true

Integer a = new Integer(2);
Integer b = new Integer(2);

a == b; //Isso é false.[/code][/quote]

Complementado o que o Vinigodoy falou.

a classe integer faz cache dos objetos de -128 até +127.

veja o código da classe Integer

    private static class IntegerCache {
	private IntegerCache(){}

	static final Integer cache[] = new Integer[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i &lt cache.length; i++)
		cache[i] = new Integer(i - 128);
	}
    }

    public static Integer valueOf(int i) {
	final int offset = 128;
	if (i &gt= -128 && i &lt= 127) { // must cache 
	    return IntegerCache.cache[i + offset];
	}
        return new Integer(i);
    }

[quote=ViniGodoy]Com o construtor você obriga o java a criar uma nova instância. Com o valueOf, o Java está autorizado a te retornar um objeto do cache.

Por exemplo:

[code]Integer x = Integer.valueOf(2);
Integer y = Integer.valueOf(2);

x == y; //Isso é true

Integer a = new Integer(2);
Integer b = new Integer(2);

a == b; //Isso é false.[/code][/quote]

Agora fiquei com uma dúvida: Qual é a diferença em usar um objeto em cache e um novo, criado exclusivamente para mim :)? Eles não serão sempre objetos idênticos?

Os que já estão em cache não tem o custo de criação de um objeto para a VM.