SlideShare uma empresa Scribd logo
Strings e I/ O

Grupo de estudo para SCJP
Strings e I/ O
• Tópicos abordados
  – String, StringBuilder, and StringBuffer
    •   The String Class
    •   Important Facts About Strings and Memory
    •   Important Methods in the String Class
    •   The StringBuffer and StringBuilder Classes
    •   Important Methods in the StringBuffer and
        StringBuilder Classes
  – File Navigation and I/ O
    • The java.io.Console Class
Strings
• Strings são objetos imutáveis
• Cada caractere em uma string é 16- bit
  Unicode
• Como strings são objetos, é possível criar
  uma instância:
  – utilizando new:
    String s = new String();
    String s = new String("abcdef");
  – de outras maneiras:
    String s = "abcdef";
Strings: Métodos e
           referências
• Métodos e referências
Strings: Métodos e
           referências
• Métodos e referências
Strings: Métodos e
           referências
• Métodos e referências
Strings: Métodos e
            referências
• Out ros ex em plos
    String x = "Java";
    x.concat(" Rules!");
    System.out.println("x = " + x);
    x.toUpperCase();
    System.out.println("x = " + x);
    x.replace('a', 'X');
    System.out.println("x = " + x);
  – Qual será a saída?
Strings: Métodos e
            referências
• Out ros ex em plos
    String x = "Java";
    x.concat(" Rules!");
    System.out.println("x = " + x);
    x.toUpperCase();
    System.out.println("x = " + x);
    x.replace('a', 'X');
    System.out.println("x = " + x);
  – Qual será a saída? x = Java
Strings: Métodos e
            referências
• Out ro ex em plo
     String x = "Java";
     x = x.concat(" Rules!");
     System.out.println("x = " + x);
  – E agora?
Strings: Métodos e
            referências
• Out ro ex em plo
     String x = "Java";
     x = x.concat(" Rules!");
     System.out.println("x = " + x);
  – E agora? x = Java Rules!
Strings: Métodos e
            referências
• Possível ex emplo do teste
  String s1 = "spring ";
  String s2 = s1 + "summer ";
  s1.concat("fall ");
  s2.concat(s1);
  s1 += "winter ";
  System.out.println(s1 + " " + s2);
• Possíveis questionamentos:
  – Qual a saída? Quantos objetos foram criados?
    Quantos estão perdidos?
Strings: Fatos importantes sobre
            memória
• Área especial na m em ória: St ring
  constant pool
• Referências iguais, objetos iguais
• Para evitar problem as com a
  im utabilidade, a classe String é
  definida com o final
Strings: Fatos importantes sobre
            memória
• Qual a diferença na m em ória entre os
  dois m étodos a seguir?
    String s = "abc";
    String s = new String("abc");
Strings: Fatos importantes sobre
            memória
• Qual a diferença na m em ória entre os
  dois m étodos a seguir?
    String s = "abc";
    String s = new String("abc");
   Pelo fato de utilizarmos o new,um
   novo objeto String será criado na
   memória normal, e “abc” será
   criado na pool
Strings: Métodos im portantes
•   Mét odos important es da classe St ring
    ■ charAt() Returns the character located at the specified index
    ■ concat() Appends one String to the end of another ( "+ " also
      works)
    ■ equalsIgnoreCase() Determines the equality of two Strings,
      ignoring case
    ■ length() Returns the number of characters in a String
    ■ replace() Replaces occurrences of a character with a new character
    ■ substring() Returns a part of a String
    ■ toLowerCase() Returns a String with uppercase characters
      converted
    ■ toString() Returns the value of a String
    ■ toUpperCase() Returns a String with lowercase characters
      converted
    ■ trim() Removes whitespace from the ends of a String
Strings: Erros com uns
• Erros com uns
  – O atributo length
    • Ex emplo:
       String x = "test";
       System.out.println( x.length );
       ou
       String[] x = new String[3];
       System.out.println( x.length() );
    • Qual desses códigos funcionará?
Strings: StringBuffer e
            StringBuilder
• StringBuffer x StringBuilder
  – As duas apresentam a mesma API
  – StringBuilder não apresenta métodos
    sincronizados
  – A Sun recomenda StringBuilder pela sua
    velocidade
Strings: StringBuffer e
             StringBuilder
• Ex em plo inicial
  StringBuffer sb = new StringBuffer("abc");
  sb.append("def");
  System.out.println("sb = " + sb);
  sb = new StringBuilder("abc");
  sb.append("def").reverse().insert(3, "---");
  System.out.println( sb );
  – Qual será a saída?
Strings: StringBuffer e
             StringBuilder
• Ex em plo inicial
  StringBuffer sb = new StringBuffer("abc");
  sb.append("def");
  System.out.println("sb = " + sb);
  sb = new StringBuilder("abc");
  sb.append("def").reverse().insert(3, "---");
  System.out.println( sb );
  – Qual será a saída?
     sb = abcdef
     fed---cba
Strings: StringBuffer e
               StringBuilder
• Métodos importantes
  –   public   synchronized StringBuffer append(String s)
  –   public   StringBuilder delete(int start, int end)
  –   public   StringBuilder insert(int offset, String s)
  –   public   synchronized StringBuffer reverse( )
  –   public   synchronized StringBuffer toString( )
I/ O
• Navegação entre arquivos
• Leitura de arquivos
I/ O
• Navegação entre arquivos
• Leitura de arquivos
I/ O
I/ O
•   Exemplo Geral
          import java.io.*;
          class Writer2 {
             public static void main(String [] args) {
                       char[] in = new char[50];
                       int size = 0;
                       try {
                                     File file = new File("fileWrite2.txt");
                                     FileWriter fw = new FileWriter(file);
                                     fw.write("howdy nfolks n");
                                     fw.flush();
                                     fw.close();
                                       FileReader fr = new FileReader(file);
                                       size = fr.read(in);
                                       System.out.print(size + " ");
                                       for(char c : in)
                                       System.out.print(c);
                                       fr.close();
                       } catch(IOEx ception e) { }
                }
          }
     –   Qual será a saída?
I/ O
•   Exemplo Geral
          import java.io.*;
          class Writer2 {
             public static void main(String [] args) {
                     char[] in = new char[50];
                     int size = 0;
                     try {
                               File file = new File("fileWrite2.txt");
                               FileWriter fw = new FileWriter(file);
                               fw.write("howdynfolksn");
                               fw.flush();
                               fw.close();
                                 FileReader fr = new FileReader(file);
                                 size = fr.read(in);
                                 System.out.print(size + " ");
                                 for(char c : in)
                                 System.out.print(c);
                                 fr.close();
                     } catch(IOException e) { }
                }
          }
     –   Qual será a saída?      12 howdy
                                 folks
I/ O
• Ex em plo com diretório
       File myDir = new File("mydir");
       myDir.mkdir();
       File myFile = new File(myDir,"myFile.txt");
       myFile.createNewFile();
       PrintWriter pw = new PrintWriter(myFile);
       pw.println("new stuff");
       pw.flush();
       pw.close();
I/ O
• Ex em plo com diretório
    File myDir = new File("mydir");
    File myFile = new File(myDir,"myFile.txt");
    myFile.createNewFile();
    O que ocorrerá?
I/ O
• Ex em plo com diretório
    File myDir = new File("mydir");
    File myFile = new File(myDir,"myFile.txt");
    myFile.createNewFile();
    O que ocorrerá?
    java.io.IOException: No such file or directory
I/ O
• Ex emplo com outros métodos
        File delDir = new File("deldir");
        delDir.mkdir();
        File delFile1 = new File(delDir, "delFile1.txt");
        delFile1.createNewFile();
        File delFile2 = new File(
        delDir, "delFile2.txt");
        delFile2.createNewFile();
        delFile1.delete();
        System.out.println("delDir is "+ delDir.delete());
        File newName = new File(delDir, "newName.txt");
        delFile2.renameTo(newName); // rename file
        File newDir = new File("newDir");
        delDir.renameTo(newDir);

        Saída:
          delDir is false
I/ O: Console Class
• Classe para tratar o console
• Sem pre invoca System .console()
• Métodos im portantes:
  – readLine();
  – readPassword();
I/ O: Console Class
•   Exemplo
        import java.io.Console;
        public class NewConsole {
              public static void main(String[] args) {
                   Console c = System.console();
                   char[] pw;
                   pw = c.readPassword("%s", "pw: ");
                   for(char ch: pw)
                   c.format("%c ", ch);
                   c.format("n");
                   MyUtility mu = new MyUtility();
                   while(true) {
                      String name = c.readLine("%s", "input?: ");
                      c.format("output: %s n", mu.doStuff(name));
                   }
              }
        }

        class MyUtility {
              String doStuff(String arg1) {
                 return "result is " + arg1;
              }
        }

Mais conteúdo relacionado

PDF
Estrutura de Dados e Algoritmos com Java #13-18: Pilhas (Stack)
PDF
Estrutura de Dados e Algoritmos com Java #02-12: Vetores e Arrays
PDF
Estrutura de Dados e Algoritmos com Java #19-25: Filas (Queue)
PDF
Java 05
KEY
Grails: Java produtivo e divertido
PDF
Iteráveis e geradores (versão RuPy)
PDF
Threads 07: Sincronizadores
ODP
Palestra2009
Estrutura de Dados e Algoritmos com Java #13-18: Pilhas (Stack)
Estrutura de Dados e Algoritmos com Java #02-12: Vetores e Arrays
Estrutura de Dados e Algoritmos com Java #19-25: Filas (Queue)
Java 05
Grails: Java produtivo e divertido
Iteráveis e geradores (versão RuPy)
Threads 07: Sincronizadores
Palestra2009

Mais procurados (20)

PDF
Mongodb workshop cinlug
PDF
Apostila de ext js com php e postgresql v0.5
PDF
You shall not pass.. permissões no UNIX
PPTX
Hibernate
KEY
Python 01
PDF
Passagem de Objetos entre Java e Oracle
PPTX
Curso java 01 - molhando os pés com java
PDF
Atualização Java 8 (2014)
PDF
Threads 06: Coleções concorrentes
ODP
Palestra cbq
PDF
Threads 08: Executores e Futures
PDF
Curso de Java: Introdução a lambda e Streams
PDF
Threads 04 Variáveis atômicas
PPT
LINQ - Language Integrated Query
PDF
Threads 10: CompletableFuture
PDF
Threads 05: Travas de Exclusão Mútua
KEY
Python 05
PDF
Curso de Java: Threads
PDF
Introducao ao python - Luciana Mota
KEY
SPL Datastructures
Mongodb workshop cinlug
Apostila de ext js com php e postgresql v0.5
You shall not pass.. permissões no UNIX
Hibernate
Python 01
Passagem de Objetos entre Java e Oracle
Curso java 01 - molhando os pés com java
Atualização Java 8 (2014)
Threads 06: Coleções concorrentes
Palestra cbq
Threads 08: Executores e Futures
Curso de Java: Introdução a lambda e Streams
Threads 04 Variáveis atômicas
LINQ - Language Integrated Query
Threads 10: CompletableFuture
Threads 05: Travas de Exclusão Mútua
Python 05
Curso de Java: Threads
Introducao ao python - Luciana Mota
SPL Datastructures
Anúncio

Destaque (8)

PPS
Cto Andalucia Infantil Verano 09
PDF
Portfolio
PDF
Double Vision
PPTX
Jornada 3
PPT
Element Canvis De Rol
PDF
Aulão de JPA com Tomaz Lavieri
Cto Andalucia Infantil Verano 09
Portfolio
Double Vision
Jornada 3
Element Canvis De Rol
Aulão de JPA com Tomaz Lavieri
Anúncio

Semelhante a String e IO (20)

PDF
Arquivos manipulação entrada saída em java
PPTX
Curso de Java 10 - (IO Manipulação de Arquivos).pptx
PPT
55 New Things in Java 7 - Brazil
PPTX
Apresentação java io
PDF
Jug bizus
PDF
Jug bizus (4)
PPT
http://www.dm.ufscar.br/~waldeck/curso/java/
PPT
http://www.dm.ufscar.br/~waldeck/curso/java/
PPT
Java Desktop
ODP
Workshop Python.2
PDF
013 programando em python - arquivos
PDF
Python e django na prática
PDF
Python para quem sabe Python (aula 2)
PPTX
Linguagem de Programação Java
PDF
Programação Web com PHP 7.x
PDF
Abstração do banco de dados com PHP Doctrine
PDF
Classe integer-float-byte-short-long-double
PPT
Aula5 introducao c
PPT
Aula5 introducao c
Arquivos manipulação entrada saída em java
Curso de Java 10 - (IO Manipulação de Arquivos).pptx
55 New Things in Java 7 - Brazil
Apresentação java io
Jug bizus
Jug bizus (4)
http://www.dm.ufscar.br/~waldeck/curso/java/
http://www.dm.ufscar.br/~waldeck/curso/java/
Java Desktop
Workshop Python.2
013 programando em python - arquivos
Python e django na prática
Python para quem sabe Python (aula 2)
Linguagem de Programação Java
Programação Web com PHP 7.x
Abstração do banco de dados com PHP Doctrine
Classe integer-float-byte-short-long-double
Aula5 introducao c
Aula5 introducao c

Mais de Elenilson Vieira (20)

PDF
Sistema S2DG e Tecnologias Web
PPT
PDF
JavaME no Mercado Mobile
PDF
JavaFX 1.2
PDF
Apresentação da Doom
PDF
Palestra sobre a Sun
PDF
Apresentação da RedeSoft
PDF
Java Collections - Tomaz Lavieri
PDF
A Sun no Meio Acadêmico - IESP/FatecPB
PDF
Mini-Curso de Sockets no Unipê
PDF
PDF
Concorrência com Java
PDF
Programas Acadêmicos da Sun no Unipê
ODP
Mundo Livre e Aberto
PDF
JavaME - Aula 2
PDF
JavaME - Aula 1
PDF
Apostila JavaME
PDF
PPT
Sincronização - Glêdson Elias
PDF
Collections e Generics
Sistema S2DG e Tecnologias Web
JavaME no Mercado Mobile
JavaFX 1.2
Apresentação da Doom
Palestra sobre a Sun
Apresentação da RedeSoft
Java Collections - Tomaz Lavieri
A Sun no Meio Acadêmico - IESP/FatecPB
Mini-Curso de Sockets no Unipê
Concorrência com Java
Programas Acadêmicos da Sun no Unipê
Mundo Livre e Aberto
JavaME - Aula 2
JavaME - Aula 1
Apostila JavaME
Sincronização - Glêdson Elias
Collections e Generics

String e IO

  • 1. Strings e I/ O Grupo de estudo para SCJP
  • 2. Strings e I/ O • Tópicos abordados – String, StringBuilder, and StringBuffer • The String Class • Important Facts About Strings and Memory • Important Methods in the String Class • The StringBuffer and StringBuilder Classes • Important Methods in the StringBuffer and StringBuilder Classes – File Navigation and I/ O • The java.io.Console Class
  • 3. Strings • Strings são objetos imutáveis • Cada caractere em uma string é 16- bit Unicode • Como strings são objetos, é possível criar uma instância: – utilizando new: String s = new String(); String s = new String("abcdef"); – de outras maneiras: String s = "abcdef";
  • 4. Strings: Métodos e referências • Métodos e referências
  • 5. Strings: Métodos e referências • Métodos e referências
  • 6. Strings: Métodos e referências • Métodos e referências
  • 7. Strings: Métodos e referências • Out ros ex em plos String x = "Java"; x.concat(" Rules!"); System.out.println("x = " + x); x.toUpperCase(); System.out.println("x = " + x); x.replace('a', 'X'); System.out.println("x = " + x); – Qual será a saída?
  • 8. Strings: Métodos e referências • Out ros ex em plos String x = "Java"; x.concat(" Rules!"); System.out.println("x = " + x); x.toUpperCase(); System.out.println("x = " + x); x.replace('a', 'X'); System.out.println("x = " + x); – Qual será a saída? x = Java
  • 9. Strings: Métodos e referências • Out ro ex em plo String x = "Java"; x = x.concat(" Rules!"); System.out.println("x = " + x); – E agora?
  • 10. Strings: Métodos e referências • Out ro ex em plo String x = "Java"; x = x.concat(" Rules!"); System.out.println("x = " + x); – E agora? x = Java Rules!
  • 11. Strings: Métodos e referências • Possível ex emplo do teste String s1 = "spring "; String s2 = s1 + "summer "; s1.concat("fall "); s2.concat(s1); s1 += "winter "; System.out.println(s1 + " " + s2); • Possíveis questionamentos: – Qual a saída? Quantos objetos foram criados? Quantos estão perdidos?
  • 12. Strings: Fatos importantes sobre memória • Área especial na m em ória: St ring constant pool • Referências iguais, objetos iguais • Para evitar problem as com a im utabilidade, a classe String é definida com o final
  • 13. Strings: Fatos importantes sobre memória • Qual a diferença na m em ória entre os dois m étodos a seguir? String s = "abc"; String s = new String("abc");
  • 14. Strings: Fatos importantes sobre memória • Qual a diferença na m em ória entre os dois m étodos a seguir? String s = "abc"; String s = new String("abc"); Pelo fato de utilizarmos o new,um novo objeto String será criado na memória normal, e “abc” será criado na pool
  • 15. Strings: Métodos im portantes • Mét odos important es da classe St ring ■ charAt() Returns the character located at the specified index ■ concat() Appends one String to the end of another ( "+ " also works) ■ equalsIgnoreCase() Determines the equality of two Strings, ignoring case ■ length() Returns the number of characters in a String ■ replace() Replaces occurrences of a character with a new character ■ substring() Returns a part of a String ■ toLowerCase() Returns a String with uppercase characters converted ■ toString() Returns the value of a String ■ toUpperCase() Returns a String with lowercase characters converted ■ trim() Removes whitespace from the ends of a String
  • 16. Strings: Erros com uns • Erros com uns – O atributo length • Ex emplo: String x = "test"; System.out.println( x.length ); ou String[] x = new String[3]; System.out.println( x.length() ); • Qual desses códigos funcionará?
  • 17. Strings: StringBuffer e StringBuilder • StringBuffer x StringBuilder – As duas apresentam a mesma API – StringBuilder não apresenta métodos sincronizados – A Sun recomenda StringBuilder pela sua velocidade
  • 18. Strings: StringBuffer e StringBuilder • Ex em plo inicial StringBuffer sb = new StringBuffer("abc"); sb.append("def"); System.out.println("sb = " + sb); sb = new StringBuilder("abc"); sb.append("def").reverse().insert(3, "---"); System.out.println( sb ); – Qual será a saída?
  • 19. Strings: StringBuffer e StringBuilder • Ex em plo inicial StringBuffer sb = new StringBuffer("abc"); sb.append("def"); System.out.println("sb = " + sb); sb = new StringBuilder("abc"); sb.append("def").reverse().insert(3, "---"); System.out.println( sb ); – Qual será a saída? sb = abcdef fed---cba
  • 20. Strings: StringBuffer e StringBuilder • Métodos importantes – public synchronized StringBuffer append(String s) – public StringBuilder delete(int start, int end) – public StringBuilder insert(int offset, String s) – public synchronized StringBuffer reverse( ) – public synchronized StringBuffer toString( )
  • 21. I/ O • Navegação entre arquivos • Leitura de arquivos
  • 22. I/ O • Navegação entre arquivos • Leitura de arquivos
  • 23. I/ O
  • 24. I/ O • Exemplo Geral import java.io.*; class Writer2 { public static void main(String [] args) { char[] in = new char[50]; int size = 0; try { File file = new File("fileWrite2.txt"); FileWriter fw = new FileWriter(file); fw.write("howdy nfolks n"); fw.flush(); fw.close(); FileReader fr = new FileReader(file); size = fr.read(in); System.out.print(size + " "); for(char c : in) System.out.print(c); fr.close(); } catch(IOEx ception e) { } } } – Qual será a saída?
  • 25. I/ O • Exemplo Geral import java.io.*; class Writer2 { public static void main(String [] args) { char[] in = new char[50]; int size = 0; try { File file = new File("fileWrite2.txt"); FileWriter fw = new FileWriter(file); fw.write("howdynfolksn"); fw.flush(); fw.close(); FileReader fr = new FileReader(file); size = fr.read(in); System.out.print(size + " "); for(char c : in) System.out.print(c); fr.close(); } catch(IOException e) { } } } – Qual será a saída? 12 howdy folks
  • 26. I/ O • Ex em plo com diretório File myDir = new File("mydir"); myDir.mkdir(); File myFile = new File(myDir,"myFile.txt"); myFile.createNewFile(); PrintWriter pw = new PrintWriter(myFile); pw.println("new stuff"); pw.flush(); pw.close();
  • 27. I/ O • Ex em plo com diretório File myDir = new File("mydir"); File myFile = new File(myDir,"myFile.txt"); myFile.createNewFile(); O que ocorrerá?
  • 28. I/ O • Ex em plo com diretório File myDir = new File("mydir"); File myFile = new File(myDir,"myFile.txt"); myFile.createNewFile(); O que ocorrerá? java.io.IOException: No such file or directory
  • 29. I/ O • Ex emplo com outros métodos File delDir = new File("deldir"); delDir.mkdir(); File delFile1 = new File(delDir, "delFile1.txt"); delFile1.createNewFile(); File delFile2 = new File( delDir, "delFile2.txt"); delFile2.createNewFile(); delFile1.delete(); System.out.println("delDir is "+ delDir.delete()); File newName = new File(delDir, "newName.txt"); delFile2.renameTo(newName); // rename file File newDir = new File("newDir"); delDir.renameTo(newDir); Saída: delDir is false
  • 30. I/ O: Console Class • Classe para tratar o console • Sem pre invoca System .console() • Métodos im portantes: – readLine(); – readPassword();
  • 31. I/ O: Console Class • Exemplo import java.io.Console; public class NewConsole { public static void main(String[] args) { Console c = System.console(); char[] pw; pw = c.readPassword("%s", "pw: "); for(char ch: pw) c.format("%c ", ch); c.format("n"); MyUtility mu = new MyUtility(); while(true) { String name = c.readLine("%s", "input?: "); c.format("output: %s n", mu.doStuff(name)); } } } class MyUtility { String doStuff(String arg1) { return "result is " + arg1; } }