String ou String Buffer? Qual usar?
Autor: Eduardo Monteiro de Andrade | Publicado: 2013-02-08T12:11:00-08:00



String ou String Buffer? Qual
usar?



&nbsp; Isso vai depender do objetivo do
seu algoritmo. Quando precisamos desenvolver algum método, que precise
concatenar Strings (por exemplo), temos opções de usar a classe String ou a
StringBuffer. No momento de desenvolver o método, você deve decidir qual das
duas classes mais se adéqua ao seu algoritmo entendendo as diferenças entre
elas, é claro. Então vamos às diferenças:



Classe String: cria um objeto na
memória a cada concatenação.

Classe StringBuffer: cria
somente um objeto na memória e, a cada concatenação, usa o objeto da memória e
adiciona a nova string àquele objeto String da memória.



Logo, se você tiver um algoritmo
que precise concatenar poucas strings, use a classe String. Caso contrário, use
a StringBuffer. Abaixo alguns exemplos:



public class TesteString {



//DECLARAÇÃO DOS ATRIBUTOS COMO PÚBLICOS PARA USAR
NO EXEMPLO. NÃO É A MELHOR PRÁTICA. USE-OS COMO PRIVADOS.



&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public Integer id;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public String nome;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public Integer idade;



<!--[if !supportLists]-->&nbsp; &nbsp; 1)&nbsp; <!--[endif]-->Exemplo de uso
da classe String, concatenando apenas 3 variáveis.&nbsp;&nbsp;&nbsp;&nbsp; 



&nbsp;&nbsp;&nbsp;&nbsp; public String
toString() {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return id + " " + nome + " " + idade;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

<!--[if !supportLists]-->&nbsp; &nbsp; 2)&nbsp; <!--[endif]-->Já neste exemplo, foi usada
a classe String Buffer devido às possibilidades de filtro.



&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public String
monteStringSql(Integer id, String nome, Integer idade){

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
StringBuffer buffer = new StringBuffer();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
buffer.append("SELECT * FROM ALUNO WHERE 1=1
");

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (id != null )

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
buffer.append(" AND id = " + id.intValue());

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (nome != null)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
buffer.append(" AND nome = '" + nome + "'");

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (idade != null)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
buffer.append(" AND idade = " + idade.intValue());

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
buffer.append(" ORDER BY nome");

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return
buffer.toString();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

<!--[if !supportLists]-->&nbsp; &nbsp; 3)&nbsp; <!--[endif]-->Execução de ambos os testes:



&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public static void main(String[]
args) {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
TesteString ts = new TesteString();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ts.id = 1;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ts.nome = "classe string";

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ts.idade = 30;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
System.out.println(":::: STRING
::::");

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
System.out.println(ts.toString());

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
System.out.println(":::: STRING BUFFER
::::");

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
System.out.println(ts.monteStringSql(null, null, null));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(ts.monteStringSql(10,
null, null));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
System.out.println(ts.monteStringSql(10, "TESTE", null));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
System.out.println(ts.monteStringSql(10, "TESTE", 35));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }

}



RESULTADO:



:::: STRING ::::

1 classe string 30



:::: STRING BUFFER ::::

SELECT * FROM ALUNO WHERE 1=1&nbsp; ORDER BY nome

SELECT * FROM ALUNO WHERE 1=1&nbsp; AND id = 10 ORDER BY nome

SELECT * FROM ALUNO WHERE 1=1&nbsp; AND id = 10 AND nome = 'TESTE' ORDER
BY nome

SELECT * FROM ALUNO WHERE 1=1&nbsp; AND id
= 10 AND nome = 'TESTE' AND idade = 35 ORDER BY nome



OBSERVAÇÃO: Note que o número de atributos foi o mesmo, 3 em ambos
os exemplos, porém o objetivo dos métodos foi diferente. No uso da classe
string, apenas concatenei parâmetros da classe e, no segundo, a concatenação vai
ocorrer apenas se o parâmetro tiver valor. Esse são exemplos clássicos de uso
de ambas as classes.



Leitor, espero ter auxiliado no conhecimento dessas classes. 



Um grande abraço e até a próxima!



Post enviado por:



Wallace Rodrigo do Nascimento

Desenvolvedor Java