diff --git a/.gitignore b/.gitignore index a034915..4f46d6b 100644 --- a/.gitignore +++ b/.gitignore @@ -9,8 +9,8 @@ npm-debug.log *.DS_Store ._* -### Nosso exemplos ### -arquivo*.txt +### Examples ### +file*.txt ### Eclipse ### .settings/ diff --git a/.travis.yml b/.travis.yml index 38f9cca..0fb4436 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,7 @@ sudo: required env: global: - secure: eXGVND48r4WyUCELydGxJ5NZURQ5iSaMYT6sLyPAdsjoio5NO+/eF17Fw61YqljrSgy+SuYTtHSeVLET4VOVMry2AH2474UD4DDAZ0Fo21s/u/+wQzIW7szO+gzg+PB/22zM67Yx+9ICo+xm10juHwJRyse9s5EFCgL40LtHPWXc5iTbSJtQFbc3YqPMmrvZZEeGYKAEX6uaqeoSi5PJdDrZfMAcienrbXMx9ASW1LlaJXEr3GKQLHxdfeiEsmVpppeYbfVSRcNRGIgFHS397D2eTVBbsTnxx72dqkR6eYC9z0sifai6baTPx34K3Us1lTx9/bR2DKYohNhea7jinYNSuJB2Lyrf3u4qfJPVLlnSgT+fJYPkmmjDuRepRUK6Kvs4M69YA7FdOhSKHpZlKUtIGjRVFe4CTvkoPAJt+lSaifVKWBD6Q18NqgCkCgijIq3Hn8tjtbWHe256fqZYjio4HBHwfifWG5oxK9ZTKxc9Z+wv2mASHhnmjWpHCtFvib8HMtIizqEVOndg58vMFXJNX1sisZxIV8+I7LSgHU7OBfi2A2Ik5Zeuo46Q7/V+2xl/nOOpC6M7Bgbe+c8gFc8PyJA/3w9+m6xUmRuE5F14D4ItXZvK1lR70oBTlFb0fXNQrEejsKAerXRw1ThbmaFZqcw7ppPQrOM+ZvFcQf0= + secure: UQEVLPeTl6NG7X2y3mdXKEOtchx/uPNNwWOckOAaKfFNIG3MMqfDMnBYGrcj38303zwbqYxjg/2ptwpTeA+eW1TWe1N+I1Y/BX6jA0bUKZgS2PvQXN8SHehDV33pWkSkhxhAi3pp/T3cvVugse2MMWtlRCZ9WizY0jn1viU40G3VQJYi4cNe+QwdxEvG7/GlWW11i9D8ev4nhTKEwYUGQ/KZHjCZwWzVjVesvV7mfcvjZWN4OrMYMH76hjIqA6WIa2pVtIgLp1ZF6g13AYQPlqzBTsItssukQfh/1fzrdGD9v/fbH60N6NDqpJmqVfDnCHOuioS8ZNPo9GZ62nDeTPa5EWETwLxqcbJWL4xWZFvDHSEUL5ZFLfEXZAANw2jPojYZU71mqRSGeLE+ZVh2sb11t4oOis0do7MR8G9/3U7vcqpoigslSaECtXN2G3lA4gAJkKzbkvfnQtseDF6LTclG29mGmA8g6uXNN9kBCK5alkhrrerad1otDfkp/09mwWNGzjSlBYGhrbHZiHVNnVlHr0dMbOc33xxOzqSeFNZsUYnUbGt01pVQzIgzMp5cErEHdxMmwvLoePNcaT2iy5kseJOkKlheDF6Lmbo/yoCta7MCIi0Fdrz7AYL+LnYEW8cHKx5vnu7R3/gkDjGdCIG0WRQ+HZPDD19maq6sem0= jobs: include: diff --git a/C-references.asc b/C-references.asc index c6d6721..207412a 100644 --- a/C-references.asc +++ b/C-references.asc @@ -1,5 +1,5 @@ [[C-references]] [appendix] -== Referências +== References include::README.asc[lines=34..-1] diff --git a/LICENSE.asc b/LICENSE.asc index b0931e8..a8b4ab3 100644 --- a/LICENSE.asc +++ b/LICENSE.asc @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2019 Rinaldo Pitzer Jr. e Rodrigo Moutinho +Copyright (c) 2019 Rinaldo Pitzer Jr. and Rodrigo Moutinho Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.asc b/README.asc index dc07cef..89de30f 100644 --- a/README.asc +++ b/README.asc @@ -1,68 +1,68 @@ -= Guia Prático para Certificação: Atualize sua certificação Java 6 para Java 8 += Practical Guide to Certification: Update your certification from Java 6 to Java 8 -image:https://img.shields.io/travis/com/duke-certification/java6-to-java8.svg[Travis (.com), link=https://travis-ci.com/duke-certification/java6-to-java8] image:https://img.shields.io/github/release/duke-certification/java6-to-java8.svg[GitHub release] image:https://img.shields.io/github/release-date/duke-certification/java6-to-java8.svg[GitHub Release Date] image:https://img.shields.io/github/downloads/duke-certification/java6-to-java8/total.svg[GitHub All Releases] image:https://img.shields.io/github/issues/duke-certification/java6-to-java8.svg[GitHub issues] image:https://img.shields.io/github/license/duke-certification/java6-to-java8.svg[GitHub License] +image:https://img.shields.io/travis/com/duke-certification/java6-to-java8-en.svg[Travis (.com), link=https://travis-ci.com/duke-certification/java6-to-java8-en] image:https://img.shields.io/github/release/duke-certification/java6-to-java8-en.svg[GitHub release] image:https://img.shields.io/github/release-date/duke-certification/java6-to-java8-en.svg[GitHub Release Date] image:https://img.shields.io/github/downloads/duke-certification/java6-to-java8-en/total.svg[GitHub All Releases] image:https://img.shields.io/github/issues/duke-certification/java6-to-java8-en.svg[GitHub issues] image:https://img.shields.io/github/license/duke-certification/java6-to-java8-en.svg[GitHub License] -Este projeto serve como material de apoio na realização do exame *https://education.oracle.com/upgrade-to-java-se-8-ocp/pexam_1Z0-813[1Z0-813]* que atualiza qualquer profissional com certificação Java 6 ou inferior, para a versão 8. No momento desta documentação, o _voucher_ do exame custa R$ 597,00 no Brasil. +This project is a support material for the *https://education.oracle.com/upgrade-to-java-se-8-ocp/pexam_1Z0-813[1Z0-813]* exam that updates any certified Java professional from version 6 or lower to version 8. -image::images/ebook-400x400.png[Guia Open Source para Certificação,align="center"] +image::images/ebook-400x400.png[Practical Guide to Certification,align="center"] -Baixe a versão mais recente do ebook https://github.com/duke-certification/java6-to-java8/releases[no link de releases]. +Download the eBook latest version on the https://github.com/duke-certification/java6-to-java8-en/releases[releases' page]. -== Gerando o Livro -Para gerar cada arquivo do livro (HTML, Epub, Mobi e PDF), utilize a https://github.com/asciidoctor/docker-asciidoctor[imagem oficial do asciidoctor] para não precisar instalar nada em sua máquina, exceto o https://docker.com[Docker]. +== Generating the Book +To generate each file in the book (HTML, Epub, Mobi, and PDF), use the https://github.com/asciidoctor/docker-asciidoctor[official asciidoctor image], so you don't have to install anything except https://docker.com[Docker]. -Execute este comando a partir do diretório raiz deste projeto: +Run the following command from the root directory of this project: [source,shell] -.Utilizando Docker Compose +.Using Docker Compose ---- docker-compose run --rm ebook ---- [source,shell] -.Utilizando Docker +.Using Docker ---- # linux / unix docker run --rm -v $(pwd):/documents/ asciidoctor/docker-asciidoctor scripts/docker-startup.sh -# others (substituir pelo diretório completo deste projeto) -docker run --rm -v :/documents/ asciidoctor/docker-asciidoctor scripts/docker-startup.sh +# others (change with the full path of this project) +docker run --rm -v :/documents/ asciidoctor/docker-asciidoctor scripts/docker-startup.sh ---- -== Referências +== References -Em todas sessões do livro são feitas referências diretas as fontes de inspiração ou argumentação base para a criação deste conteúdo. A seguir o resumo das principais e de outras referências que também fizeram parte dessa jornada de aprendizado. +Direct references are made in every session of the book for the inspiration sources or base resources used during the creation of this content. The following is a summary of the main resources and other references that were also part of this learning journey. -Para criação da estrutura do projeto deste livro foi utilizado como base o projeto https://github.com/rcmoutinho/ebook-with-asciidoctor[ebook-with-asciidoctor]. +The project structure of this book is based on the https://github.com/rcmoutinho/ebook-with-asciidoctor[ebook-with-asciidoctor] project. -NOTE: Boa parte das fontes estão em inglês *(en-US)*, mas algumas também podem ser encontradas em português *(pt-BR)*. +NOTE: Most of the sources are in English *(en-US)*, but some can also be found in Portuguese *(pt-BR)*. -* *(en-US)* Excelente livro que mostra o passo-a-passo para tirar a certificação completa do Java 8 ou atualizar para a versão 8, objetivo deste livro. +* *(en-US)* An excellent book that shows you the step-by-step guide to complete Java 8 certification or upgrade to version 8, the purpose of this book. + Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide: Exam 1Z0-809 (English Edition) 1st Edition. Wiley. Edição do Kindle. + -https://www.amazon.com.br/dp/B0191U2H8C[Link na loja Amazon Brasil]. +https://www.amazon.com/dp/B0191U2H8C[Amazon.com]. -* *(en-US)* Blog do Eugen (Baeldung) com dezenas de artigos focados em Java, entre outros assuntos. +* *(en-US)* Eugen's (Baeldung) blog with dozens of articles focused on Java, among other topics. + https://www.baeldung.com/category/java/ -* *(en-US)* Tutoriais da própria Oracle com explicações detalhadas da linguagem Java. +* *(en-US)* Oracle's own tutorials with detailed explanations of the Java language. + https://docs.oracle.com/javase/tutorial/java/ -* *(en-US)* Documentação oficial do Java. +* *(en-US)* Oficial Java documentation. + https://docs.oracle.com/javase/8/docs/ -* *(pt-BR)* Curso da Alura, que apesar de focar no Java 7 (ao menos no momento da escrita desse texto), mostra como não cair em pegadinhas na prova. Principalmente em relação à situações que exigem pensar como um compilador e apontar a falta de um `;`. São mais de 80 horas de conteúdo. Vale muito a pena para quem quer ir a fundo de cada detalhe da linguagem (pelo menos até a versão 7). +* *(pt-BR)* Alura's course, which despite focusing on Java 7 (at least at the time of writing this text), shows how not to fall on traps on the test. Especially in situations that require thinking like a compiler and pointing out the lack of a `;`. More than 80 hours of content. It is worth it for those who want to go deep into every detail of the Java language (at least until version 7). + https://www.alura.com.br/formacao-certificacao-java -=== Material Complementar +=== Complementary Material -* *(pt-BR)* Canal do YouTube https://www.youtube.com/channel/UCyRDiqqSkqGvTE_wIB1nN1w[RinaldoDev] com vídeos explicativos de diversos conceitos da linguagem Java. +* *(pt-BR)* https://www.youtube.com/channel/UCyRDiqqSkqGvTE_wIB1nN1w[RinaldoDev] YouTube channel with explanatory videos of various Java language concepts. -* *(en-US)* https://www.youtube.com/playlist?list=PL3py5YSIGvPMgKXOVqnYn9nBoT_zvsvsi[_Java Challengers_], uma playlist no Youtube do canal do https://twitter.com/RafaDelNero[Rafael Del Nero] que explica desafios de Java para ensinar conceitos importantes da linguagem. +* *(en-US)* https://www.youtube.com/playlist?list=PL3py5YSIGvPMgKXOVqnYn9nBoT_zvsvsi[_Java Challengers_], a Youtube playlist from https://twitter.com/RafaDelNero[Rafael Del Nero's] channel that explains Java challenges to teach essential language concepts. -* *(en-US)* https://devgym.oracle.com/pls/apex/dg/competition/java[Oracle Dev Gym], desafios online e gratuitos para testar suas habilidades de Java. +* *(en-US)* https://devgym.oracle.com/pls/apex/dg/competition/java[Oracle Dev Gym], free online challenges to test your Java skills. diff --git a/book/01-getting-started/sections/01-introduction.asc b/book/01-getting-started/sections/01-introduction.asc index d3161f9..ee171cc 100644 --- a/book/01-getting-started/sections/01-introduction.asc +++ b/book/01-getting-started/sections/01-introduction.asc @@ -1,3 +1,3 @@ -=== Introdução +=== Introduction include::../../../README.asc[lines=5..6] diff --git a/book/01-getting-started/sections/02-objectives.asc b/book/01-getting-started/sections/02-objectives.asc index 076d403..56435b5 100644 --- a/book/01-getting-started/sections/02-objectives.asc +++ b/book/01-getting-started/sections/02-objectives.asc @@ -1,5 +1,5 @@ -=== Objetivos +=== Objectives -Como guia para criação deste livro foi utilizado todos os objetivos citados na seção _"Review Exam Topics"_, de acordo com o https://education.oracle.com/upgrade-to-java-se-8-ocp/pexam_1Z0-813[site da certificação]. +As a guide for the creation of this book, we used all the objectives mentioned in the _"Review Exam Topics"_ section, according to the https://education.oracle.com/upgrade-to-java-se-8-ocp/pexam_1Z0-813[certification website]. -A missão deste livro é criar o maior número de exemplos práticos possíveis para ajudar você a colocar a mão na massa. Quanto maior for seu contato com os códigos da versão 8 do Java, mais confiante estará na hora do exame, e também para lidar com projetos em Java 8 no mercado de trabalho. +The mission of this book is to create as many practical examples as possible to help you get your hands on coding. The greater your contact with Java version 8 code, the more confident you will be at exam time, as well as dealing with Java 8 projects in the job market. diff --git a/book/02-language-enhancement/sections/01-string-in-switch-and-literals.asc b/book/02-language-enhancement/sections/01-string-in-switch-and-literals.asc index e1a0e32..b5e5da1 100644 --- a/book/02-language-enhancement/sections/01-string-in-switch-and-literals.asc +++ b/book/02-language-enhancement/sections/01-string-in-switch-and-literals.asc @@ -1,18 +1,16 @@ :java-package: src/org/j6toj8/languageenhancements :section-java-package: ../../../{java-package} -=== Objetos Strings +=== String objects -.Objetivo +.Objective ---- Develop code that uses String objects in the switch statement, binary literals, and numeric literals, including underscores in literals. -- -Desenvolver código que utilize objetos String em instruções Switch, binários literais, e numéricos literais, incluindo underscore (_) em literais. ---- -==== String em instruções Switch +==== String in the switch statement -É esperado que o candidato saiba compreender e analisar o uso de Strings em instruções `switch`, como no seguinte exemplo. +The candidate is expected to understand and analyze the use of Strings in `switch` statements, as in the following example. [source,java,indent=0] .{java-package}/stringinswitch/StringInSwitch_Complete.java @@ -20,11 +18,11 @@ Desenvolver código que utilize objetos String em instruções Switch, binários include::{section-java-package}/stringinswitch/StringInSwitch_Complete.java[tag=code] ---- -Apesar da certificação ter foco nas atualizações trazidas pelo Java 7 e 8, é esperado que o candidato entenda também conceitos de versões anteriores do Java. Por isso, serão apresentadas algumas regras que talvez você já conheça sobre `switch`, mas utilizando `String` no `switch`. +Although certification focuses on updates brought by Java 7 and 8, the candidate is expected to understand concepts from previous versions of Java as well. Therefore, some rules you may already know about `switch` will be presented but using `String` on the `switch`. -. Todo `case` deve ser único, não pode se repetir. +. Every `case` must be unique, cannot be repeated. -. O `default` pode aparecer em qualquer posição no `switch`. +. The `default` can appear anywhere on the `switch`. + .{java-package}/stringinswitch/StringInSwitch_Default.java [source,java,indent=0] @@ -32,15 +30,15 @@ Apesar da certificação ter foco nas atualizações trazidas pelo Java 7 e 8, include::{section-java-package}/stringinswitch/StringInSwitch_Default.java[tag=code] ---- -. Tipos suportados em `switch`. -* int e Integer -* byte e Byte -* short e Short -* char e Character +. Supported types in `switch`. +* int and Integer +* byte and Byte +* short and Short +* char and Character * String -* valores de Enums +* Enums values -. Tipos não suportados em `switch`. +. Types not supported in `switch`. + .{java-package}/stringinswitch/StringInSwitch_Type.java [source,java,indent=0] @@ -48,7 +46,7 @@ include::{section-java-package}/stringinswitch/StringInSwitch_Default.java[tag=c include::{section-java-package}/stringinswitch/StringInSwitch_Type.java[tag=code] ---- -. A execução se inicia em um `case` e somente para ao encontrar um `break`. +. Execution starts in a `case` and only stops when it encounters a `break`. + .{java-package}/stringinswitch/StringInSwitch_Break.java [source,java,indent=0] @@ -56,17 +54,17 @@ include::{section-java-package}/stringinswitch/StringInSwitch_Type.java[tag=code include::{section-java-package}/stringinswitch/StringInSwitch_Break.java[tag=code] ---- + -.saída no console +.console output [source,console] ---- -Janeiro -Não é um mês -Fevereiro +January +Not a month +February ---- + -Nesse caso a execução inicia no `case "jan"`, passar pelo `default` e pelo `case "fev"` até parar no `break`, por isso as 3 strings aparecem no console. +In this case, execution starts in `case "jan "`, goes through `default` and `case "Feb"` until it stops at `break`. So the 3 strings will appear in the console. -. Um `switch` vazio é válido, mesmo que não tenha utilidade. +. An empty `switch` is valid even if it has no use. + .{java-package}/stringinswitch/StringInSwitch_Empty.java [source,java,indent=0] @@ -74,7 +72,7 @@ Nesse caso a execução inicia no `case "jan"`, passar pelo `default` e pelo `ca include::{section-java-package}/stringinswitch/StringInSwitch_Empty.java[tag=code] ---- -. Todos os valores de `case` precisam ser constantes, ou seja, variáveis finais em tempo de compilação. Se o valor do `case` puder mudar em tempo de execução, o código não compila. +. All `case` values must be constant, i.e., final variables at compile time. If the value of `case` can change at runtime, the code does not compile. + .{java-package}/stringinswitch/StringInSwitch_ConstantOnly.java [source,java,indent=0] @@ -82,11 +80,11 @@ include::{section-java-package}/stringinswitch/StringInSwitch_Empty.java[tag=cod include::{section-java-package}/stringinswitch/StringInSwitch_ConstantOnly.java[tag=code] ---- -Pronto, essas são as regras de `switch`. Você provavelmente já conheçe algumas referentes à versões anteriores do Java, mas agora você as viu em `switch` que utilizam Strings. Isso não era possível antes do Java 7. +These are the switch rules. You probably already know some about previous versions of Java, but now you have seen them in `switch` that use Strings. This was not possible before Java 7. -==== Literais Binários e Numéricos, incluindo underscore( _ ) +==== Binary and numeric literals, including underscores in literals -É esperado que o candidato saiba compreender e analisar o uso de literais binários e numéricos, como no seguinte exemplo. +The candidate is expected to understand and analyze the use of binary and numeric literals, as in the following example. [source,java,indent=0] .{java-package}/literals/Literals_Complete.java @@ -94,11 +92,11 @@ Pronto, essas são as regras de `switch`. Você provavelmente já conheçe algum include::{section-java-package}/literals/Literals_Complete.java[tag=code] ---- -Apesar da certificação ter foco nas atualizações trazidas pelo Java 7 e 8, é esperado que o candidato entenda também conceitos de versões anteriores do Java. Por isso, serão apresentadas algumas regras que talvez você já conheça sobre literais. +Although certification focuses on updates brought by Java 7 and 8, the candidate is expected to understand concepts from previous versions of Java as well. So here are some rules you may already know about literals. -. No Java, _Literal_ é qualquer número escrito diretamente no código, como todos do exemplo acima. +. In Java, _Literal_ is any number written directly in code, like the previous example. -. Por padrão, o Java interpreta literais como `int`. Ou seja, se não houver um sufixo no número para mudar seu tipo, ele é um `int`. +. By default, Java interprets literals as `int`. That is, if there is no suffix in the number to change its type, it is an `int`. + .{java-package}/literals/Literals_Suffix.java [source,java,indent=0] @@ -106,7 +104,7 @@ Apesar da certificação ter foco nas atualizações trazidas pelo Java 7 e 8, include::{section-java-package}/literals/Literals_Suffix.java[tag=code] ---- -. Por padrão, o Java interpreta literais como sendo decimais. Existem prefixos que mudam o sistema numérico do literal. +. By default, Java interprets literals to be decimal. There are prefixes that change the numerical system of the literal. + .{java-package}/literals/Literals_Prefix.java [source,java,indent=0] @@ -114,7 +112,7 @@ include::{section-java-package}/literals/Literals_Suffix.java[tag=code] include::{section-java-package}/literals/Literals_Prefix.java[tag=code] ---- -. A partir do Java 7, é possível utilizar underscore (_) para separar visualmente um número. Isso não muda o valor do número, e serve apenas para tornar o código mais legível. +. Starting with Java 7, you can use underscore (_) to visually separate a number. This does not change the value of the number, and only serves to make the code more readable. + .{java-package}/literals/Literals_Underscore.java [source,java,indent=0] @@ -122,16 +120,16 @@ include::{section-java-package}/literals/Literals_Prefix.java[tag=code] include::{section-java-package}/literals/Literals_Underscore.java[tag=code] ---- -.Referências +.References **** -.Strings em Switch -* Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 598). Wiley. Edição do Kindle. +.String in the switch statement +* Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 598). Wiley. Kindle Edition. * https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html[Strings in switch Statements.] Java Documentation. * https://dzone.com/articles/new-java-7-feature-string[New Java 7 Feature: String in Switch support.] DZone. -.Literais -* Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 597). Wiley. Edição do Kindle. +.Literals +* Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 597). Wiley. Kindle Edition. * https://pt.wikibooks.org/wiki/Java/Literais[Java/Literais.] Wikibooks. **** diff --git a/book/02-language-enhancement/sections/02-try-with-resources.asc b/book/02-language-enhancement/sections/02-try-with-resources.asc index 02bf208..acb4cf3 100644 --- a/book/02-language-enhancement/sections/02-try-with-resources.asc +++ b/book/02-language-enhancement/sections/02-try-with-resources.asc @@ -1,18 +1,16 @@ :java-package: src/org/j6toj8/languageenhancements :section-java-package: ../../../{java-package} -=== Try com recursos +=== Try-with-resources -.Objetivo +.Objective ---- Develop code that uses try-with-resources statements, including using classes that implement the AutoCloseable interface. -- -Desenvolver código que utilize instruções try-with-resources, incluindo o uso de classes que implementam a interface AutoCloseable. ---- -É esperado que o candidato saiba compreender e analisar o uso da instrução _try-with-resources_, incluindo classes que implementam a interface `AutoClosable`. +The candidate is expected to understand and analyze the use of the _try-with-resources_ statement, including classes that implement the `AutoClosable` interface. -Antes de continuar, com base no exemplo a seguir, entenda a execução do método `main` e o que é apresentado no console após sua execução. +Before proceeding, based on the following example, understand the execution of the `main` method and what is presented on the console after its execution. [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_Complete.java @@ -20,7 +18,7 @@ Antes de continuar, com base no exemplo a seguir, entenda a execução do métod include::{section-java-package}/trywithresources/TryWithResouces_Complete.java[tag=code] ---- -O código acima utiliza dois arquivos, e faz leitura e escrita neles. A grande novidade desse código é a declaração de variáveis dentro de parênteses após a instrução `try`. Isso é a sintaxe chamada _try-with-resources_, e ela chama automaticamente o método `close()` dos recursos que estão sendo utilizados. Até o Java 6, seria necessário chamar o `close()` manualmente, como no exemplo abaixo. +The previous code uses two files and reads and writes them. The big news of this code is the declaration of variables within parentheses after the `try` statement. This is the syntax called _try-with-resources_, and it automatically calls the `close ()` method of the resources being used. Until Java 6, you would need to call `close ()` manually, as in the following example. [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_Java6.java @@ -28,9 +26,9 @@ O código acima utiliza dois arquivos, e faz leitura e escrita neles. A grande n include::{section-java-package}/trywithresources/TryWithResouces_Java6.java[tag=code] ---- -. A instrução _try-with-resources_ fecha automaticamente os recursos que implementam a interface `AutoCloseable`. +. The _try-with-resources_ statement automatically closes resources that implement the `AutoCloseable` interface. -. Ela não precisa de `catch` nem `finally` explícitos. +. It does not need explicit `catch` or `finally`. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_AutoCloseable.java @@ -38,16 +36,16 @@ include::{section-java-package}/trywithresources/TryWithResouces_Java6.java[tag= include::{section-java-package}/trywithresources/TryWithResouces_AutoCloseable.java[tag=code] ---- + -.Saída no console +.console output [source,console] ---- try -Porta fechada. +Closed door. ---- -. A instrução _try-with-resources_ ainda pode ter `catch` e `finally`, apesar de não ser necessário. Nesse caso, os recursos são fechados depois do `try` e antes de qualquer `catch` ou `finally`. +. The _try-with-resources_ statement can still have `catch` and `finally`, although it is not required. In this case, resources are closed after `try` and before either any `catch` or `finally`. -. O método `close` pode lançar uma exceção sendo capturada pelo `catch`, caso exista. +. The `close` method may throw an exception being caught by `catch`, if any. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_WithCatchFinally.java @@ -55,18 +53,18 @@ Porta fechada. include::{section-java-package}/trywithresources/TryWithResouces_WithCatchFinally.java[tag=code] ---- + -.Saída no console +.console output [source,console] ---- try -Porta fechada. +Closed door. catch finally ---- + -Ou seja, primeiro o `try` é chamado. Logo depois é chamado o método `close()` que ao final lança uma exceção. O `catch` captura essa exceção. E finalmente o `finally` é chamado. +That is, first the `try` is called. Soon after is called the `close ()` method which at the end throws an exception. `Catch` catches this exception. And finally `finally` is called. -. Os recursos declarados na instrução _try-with-resources_ são fechados na ordem inversa da declaração. +. Resources declared in the _try-with-resources_ statement are closed in the reverse order of the declaration. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_Order.java @@ -74,17 +72,17 @@ Ou seja, primeiro o `try` é chamado. Logo depois é chamado o método `close()` include::{section-java-package}/trywithresources/TryWithResouces_Order.java[tag=code] ---- + -.Saída no console +.console output [source,console] ---- -Olá. -Gaveta fechada. -Porta fechada. +Hello. +Drawer closed. +Closed door. ---- + -Ou seja, como a ordem de declaração dentro do _try-with-resources_ foi `Porta` e depois `Gaveta`, a ordem de chamada do método `close` é inversa: `Gaveta` e depois `Porta`. +That is, since the declaration order within _try-with-resources_ was `Door` and then `Drawer`, the call order of the `close` method is reversed: `Drawer` and then `Door`. -. Os recursos declarados no _try-with-resources_ só estão disponível dentro do bloco `try`. +. Resources declared in _try-with-resources_ are only available within the `try` block. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_ResourceInsideTry.java @@ -92,7 +90,7 @@ Ou seja, como a ordem de declaração dentro do _try-with-resources_ foi `Porta` include::{section-java-package}/trywithresources/TryWithResouces_ResourceInsideTry.java[tag=code] ---- -. Somente classes que implementam `AutoCloseable` podem ser utilizadas dentro do _try-with-resources_. +. Only classes that implement `AutoCloseable` can be used within _try-with-resources_. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_NoAutoCloseable.java @@ -100,7 +98,7 @@ include::{section-java-package}/trywithresources/TryWithResouces_ResourceInsideT include::{section-java-package}/trywithresources/TryWithResouces_NoAutoCloseable.java[tag=code] ---- -. Caso o método `close()` lance uma exceção checada (ou seja, que herda de `Exception`), o código só compila se existir um `catch` que capture aquela exceção, ou o método declare o `throws`. +. If the `close ()` method throws a checked exception (i.e., inherits from `Exception`), the code only compiles if there is a `catch` that catches that exception or the method declares `throws`. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_CloseException.java @@ -108,9 +106,9 @@ include::{section-java-package}/trywithresources/TryWithResouces_NoAutoCloseable include::{section-java-package}/trywithresources/TryWithResouces_CloseException.java[tag=code] ---- -. O Java 5 já possuía uma interface chamada `Closeable`, porém ela permite lançar apenas `IOException`. A nova interface `AutoCloseable` permite lançar qualquer exceção. Como `Closeable` atende a implementação de `AutoCloseable`, ela agora estende `AutoCloseable`. Logo, todas as classes que já implementavam `Closeable` podem ser utilizadas dentro do _try-with-resources_. Veja abaixo como era a interface `Closeable` antes e a partir do Java 7: +. Java 5 already had an interface called `Closeable`, but it allows only `IOException` to be thrown. The new `AutoCloseable` interface permits you to throw any exceptions. Since `Closeable` meets the implementation of `AutoCloseable`, it now extends `AutoCloseable`. So all classes that already implement `Closeable` can be used inside _try-with-resources_. Here's what the `Closeable` interface was like before and from Java 7: + -.Antes do Java 7 +.Before Java 7 [source,java] ---- public interface Closeable { @@ -118,7 +116,7 @@ public interface Closeable { } ---- + -.A partir do Java 7 +.From Java 7 [source,java] ---- public interface Closeable extends AutoCloseable { @@ -126,7 +124,7 @@ public interface Closeable extends AutoCloseable { } ---- -. Um comportamento novo são as exceções suprimidas (suppressed). Se ambos o bloco `try` e o método `close` lançam exceção, a do `close` fica suprimida, pois a do `try` é lançada primeiro. +. The new behavior is suppressed exceptions. If both the `try` block and the `close` method throw exception, that of `close` is suppressed because that of `try` is thrown first. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_Suppressed.java @@ -139,13 +137,13 @@ include::{section-java-package}/trywithresources/TryWithResouces_Suppressed.java ---- try close -erro no try -erro no close +error on try +error on close ---- + -Ou seja, a exceção que de fato foi capturada foi a do bloco `try`, pois foi lançada primeiro. A exceção lançada pelo método `close` ficou suprimida, e fica disponível em um array no método `getSuppressed()` da exceção. +That is, the exception that was actually caught was the `try` block because it was thrown first. The exception thrown by the `close` method has been suppressed and is available in an array in the exception `getSuppressed()` method. -. E por fim, é necessário lembrar que a instrução `try` "comum" ainda precisa obrigatoriamente de um `catch` ou `finally`. +. And lastly, it should be remembered that the _"default"_ `try` statement still necessarily needs a `catch` or `finally`. + [source,java,indent=0] .{java-package}/trywithresources/TryWithResouces_CommonTry.java @@ -153,24 +151,24 @@ Ou seja, a exceção que de fato foi capturada foi a do bloco `try`, pois foi la include::{section-java-package}/trywithresources/TryWithResouces_CommonTry.java[tag=code] ---- -==== Alguns tipos que implementam _Closeable_ +==== Some types that implement _Closeable_ -* `InputStream` e suas subclasses (`FileInputStream`, `ObjectInputStream`, etc) -* `OutputStream` e suas subclasses (`ByteArrayOutputStream`, `FileOutputStream`, etc) -* `Reader` e suas subclasses (`BufferedReader`, `CharSequenceReader`) -* `Writer` e suas subclasses (`BufferedWriter`, `PrintWriter`, etc) +* `InputStream` and its subclasses (`FileInputStream`, `ObjectInputStream`, etc) +* `OutputStream` and its subclasses (`ByteArrayOutputStream`, `FileOutputStream`, etc) +* `Reader` and its subclasses (`BufferedReader`, `CharSequenceReader`) +* `Writer` and its subclasses (`BufferedWriter`, `PrintWriter`, etc) -.Referências +.References **** * Using Try-With-Resources + -Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 296). Wiley. Edição do Kindle. +Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 296). Wiley. Kindle Edition. * https://www.baeldung.com/java-try-with-resources[Java – Try with Resources.] * https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html[The try-with-resources Statement.] Java Documentation. -* https://pt.stackoverflow.com/questions/172909/como-funciona-o-try-with-resources/172910#172910[Como funciona o try-with-resources?] +* https://pt.stackoverflow.com/questions/172909/como-funciona-o-try-with-resources/172910#172910[Como funciona o try-with-resources?] (pt-BR) **** \ No newline at end of file diff --git a/book/02-language-enhancement/sections/03-multiple-exception.asc b/book/02-language-enhancement/sections/03-multiple-exception.asc index 1c1ada3..c958e97 100644 --- a/book/02-language-enhancement/sections/03-multiple-exception.asc +++ b/book/02-language-enhancement/sections/03-multiple-exception.asc @@ -1,18 +1,16 @@ :java-package: src/org/j6toj8/languageenhancements :section-java-package: ../../../{java-package} -=== Múltiplas `Exception` no mesmo `catch` +=== Handles multiple Exception in a single catch -.Objetivo +.Objective ---- Develop code that handles multiple Exception types in a single catch block. -- -Desenvolver código que lide com múltiplos tipos de Exception em um único bloco catch. ---- -É esperado que o candidato saiba compreender e analisar o uso da instrução _try-catch_ com múltiplos tipos de `Exception` no mesmo bloco `catch`. +The candidate is expected to understand and analyze the use of the _try-catch_ statement with multiple types of `Exception` in the same `catch` block. -Antes de continuar, com base no exemplo a seguir, entenda a execução do método `main` e o que é apresentado no console após sua execução. +Before proceeding, based on the following example, understand the execution of the `main` method and what is presented on the console after its execution. [source,java,indent=0] .{java-package}/multipleexception/MultipleException_Complete.java @@ -20,17 +18,17 @@ Antes de continuar, com base no exemplo a seguir, entenda a execução do métod include::{section-java-package}/multipleexception/MultipleException_Complete.java[tag=code] ---- -O código anterior possui um bloco _try-catch_ que você provavelmente já conhece. A novidade neste código está no primeiro bloco `catch`, onde várias exceções são declaradas e capturadas ao mesmo tempo. +The previous code has a _try-catch_ block that you probably already know. The new about this code is in the first `catch` block, where multiple exceptions are thrown and caught at the same time. -.Saída no console +.console output [source,console] ---- -Exceção capturada: java.lang.NullPointerException +Exception caught: java.lang.NullPointerException ---- -. Desde o Java 7, múltiplas exceções podem ser capturadas no mesmo `catch`. +. Since Java 7, multiple exceptions can be caught in the same catch. -. Apenas uma variável é permitida para um bloco `catch`, e deve estar localizada no final. +. Only one variable is allowed for a `catch` block, and must be located at the end. + [source,java,indent=0] .{java-package}/multipleexception/MultipleException_MultipleSameCatch.java @@ -38,7 +36,7 @@ Exceção capturada: java.lang.NullPointerException include::{section-java-package}/multipleexception/MultipleException_MultipleSameCatch.java[tag=code] ---- -. Não é permitido declarar exceções diferentes, mas que seriam redundantes levando em consideração a herança. +. It is not allowed to declare different exceptions, but would be redundant considering inheritance. + [source,java,indent=0] @@ -47,7 +45,7 @@ include::{section-java-package}/multipleexception/MultipleException_MultipleSame include::{section-java-package}/multipleexception/MultipleException_Redundant.java[tag=code] ---- -. Ao fazer `catch` de múltiplas `Exception`, não é permitido sobrescrever a variável da exceção. Mas é possível se for apenas uma `Exception` no `catch`. +. When catching multiple Exceptions, it is not allowed to override the exception variable. But it's possible if it's just an `Exception` in `catch`. + [source,java,indent=0] .{java-package}/multipleexception/MultipleException_OverrideVar.java @@ -55,7 +53,7 @@ include::{section-java-package}/multipleexception/MultipleException_Redundant.ja include::{section-java-package}/multipleexception/MultipleException_OverrideVar.java[tag=code] ---- -. Assim como nas versões anteriores, tipos mais genéricos de `Exception` devem vir depois, mais abaixo nos _catch's_. +. As in previous releases, more generic types of `Exception` should come later, lower in the _catch_. + [source,java,indent=0] @@ -64,7 +62,7 @@ include::{section-java-package}/multipleexception/MultipleException_OverrideVar. include::{section-java-package}/multipleexception/MultipleException_GenericsLower.java[tag=code] ---- -. Assim como nas versões anteriores, Exceções repetidas ainda são proibidas. +. As in previous versions, repeated exceptions are still prohibited. + [source,java,indent=0] .{java-package}/multipleexception/MultipleException_RepeatException.java @@ -72,7 +70,7 @@ include::{section-java-package}/multipleexception/MultipleException_GenericsLowe include::{section-java-package}/multipleexception/MultipleException_RepeatException.java[tag=code] ---- -. Assim como nas versões anterior, Exceções checadas (aquelas que herdam de `Exception`) só podem estar em um `catch` caso algo no `try` lance elas. +. As in previous versions, Checked Exceptions (those that inherit from `Exception`) can only be in a `catch` if something in `try` throws them. + [source,java,indent=0] .{java-package}/multipleexception/MultipleException_CheckedException.java @@ -80,10 +78,10 @@ include::{section-java-package}/multipleexception/MultipleException_RepeatExcept include::{section-java-package}/multipleexception/MultipleException_CheckedException.java[tag=code] ---- -.Referências +.References **** -* Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 291). Wiley. Edição do Kindle. +* Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 291). Wiley. Kindle Edition. * https://docs.oracle.com/javase/8/docs/technotes/guides/language/catch-multiple.html[Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking.] Java Documentation. diff --git a/book/02-language-enhancement/sections/04-static-default-in-interfaces.asc b/book/02-language-enhancement/sections/04-static-default-in-interfaces.asc index 67d7e47..b831fce 100644 --- a/book/02-language-enhancement/sections/04-static-default-in-interfaces.asc +++ b/book/02-language-enhancement/sections/04-static-default-in-interfaces.asc @@ -1,18 +1,16 @@ :java-package: src/org/j6toj8/languageenhancements :section-java-package: ../../../{java-package} -=== Métodos `static` e `default` em Interfaces +=== Static and default methods of an interface -.Objetivo +.Objective ---- Use static and default methods of an interface including inheritance rules for a default method. -- -Usar métodos static e default de uma interface, incluindo regras de herança para um método default. ---- -É esperado que o candidato saiba compreender e analisar o uso da dos modificadores `static` e `default` em métodos de interfaces. +It is expected that the candidate can understand and analyze the use of `static` and `default` modifiers in interface methods. -Antes de continuar, com base no exemplo a seguir, entenda a execução do método `main` e o que é apresentado no console após sua execução. +Before proceeding, based on the following example, understand the execution of the `main` method and what is presented on the console after its execution. [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Complete.java @@ -20,19 +18,19 @@ Antes de continuar, com base no exemplo a seguir, entenda a execução do métod include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Complete.java[tag=code] ---- -.Saída no console +.console output [source,console] ---- 10.0 -Correndo -Pessoa Correndo Rápido +Running +Fast Running Person ---- -O código anterior possui dois modificadores novos para interfaces, possíveis desde o Java 8: `default` e `static`. É possível perceber que esses dois métodos possuem corpo, algo que não era possível antes em uma interface. Então, vamos entender quais são as novas possibilidades. +The previous code has two new interface modifiers, possible since Java 8: `default` and `static`. You can see that these two methods have a body, something that was not possible before in an interface. So let's understand what the new possibilities are. -. Desde o Java 8, Interfaces podem ter métodos com o modificador `static`. +. Since Java 8, Interfaces can have methods with the `static` modifier. -. Métodos com o modificador `static` em interfaces são chamados iguais aos de uma classe comum, ou seja, não fazem parte da API da interface. Dessa forma, não são herdados pelas classes que implementam essa interface. +. Methods with the `static` modifier on interfaces are called the same as those of a standard class, i.e., they are not part of the interface API. So, they are not inherited by classes that implement this interface. + [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Static.java @@ -40,10 +38,9 @@ O código anterior possui dois modificadores novos para interfaces, possíveis d include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Static.java[tag=code] ---- -. Desde o Java 8, Interfaces podem ter métodos com o modificador `default`. - -. Métodos `default` não precisam, mas podem, ser sobrescritos. +. Since Java 8, Interfaces can have methods with the `default` modifier. +. `Default` methods do not need, but can be overridden. + [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Default.java @@ -51,18 +48,18 @@ include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfa include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Default.java[tag=code] ---- + -Veja que a classe `Pessoa` não sobrescreve o método `correr()`, mantendo o comportamento padrão da implementação feita na interface `Corredor`. +Note that the `Person` class does not override the `run()` method, maintaining the default implementation behavior of the `Runner` interface. + -A classe `Cavalo`, por outro lado, sobrescreve o método `correr()` para ter sua própria implementação. +The `Horse` class, on the other hand, overrides the `run()` method to have its own implementation. + -.Saída no console +.console output [source,console] ---- -Correndo -Galopando +Running +Galloping ---- -. Assim como os outros método de uma interface, os métodos `static` e `default` *são sempre `public`*, e não podem ser modificados para `private` ou `protected`. +. Like the other methods of an interface, the `static` and `default` *methods are always `public`*, and cannot be changed to `private` or `protected`. + [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_AccessModifiers.java @@ -70,8 +67,7 @@ Galopando include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_AccessModifiers.java[tag=code] ---- -. Diferente dos outros método de uma interface, os métodos `static` e `default` não são `abstract`, e também não podem ser. Afinal, eles possuem implementação. Apenas métodos sem implementação são `abstract`. - +. Unlike other interface methods, the `static` and `default` methods are not `abstract`, nor can they be. After all, they have implementation. Only methods without implementation are `abstract`. + [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Abstract.java @@ -79,7 +75,7 @@ include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfa include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_Abstract.java[tag=code] ---- -. Se uma classe implementa duas interfaces que possuem métodos `default` repetidos, ela obrigatoriamente deve implementar o seu próprio. +. If a class implements two interfaces that have repeated `default` methods, it must implement its own. + [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefault.java @@ -87,7 +83,7 @@ include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfa include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefault.java[tag=code] ---- -. Ao implementar múltiplas interfaces, é possível acessar a implementação `default` de uma delas. +. By implementing multiple interfaces, you can access the `default` implementation of one of them. + [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefaultSuper.java @@ -95,13 +91,13 @@ include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfa include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefaultSuper.java[tag=code] ---- + -.Saída no console +.console output [source,console] ---- -Correndo +Running ---- -. Quando uma interface herda de outra interface métodos `default`, estes podem ser mantidos, transformados em `abstract` ou redefinidos. +. When an interface inherits from another interface, `default` methods can be retained, transformed into `abstract` or redefined. + [source,java,indent=0] .{java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_InterfaceInheritance.java @@ -109,18 +105,18 @@ Correndo include::{section-java-package}/staticdefaultininterfaces/StaticDefaultInInterfaces_InterfaceInheritance.java[tag=code] ---- + -Nesse exemplo, a interface `Piloto` herda de `Corredor` e mostra 3 cenários distintos: +In this example, the `Pilot` interface inherits from `Runner` and shows 3 distinct scenarios: -* Mantém o método `correr()` inalterado; -* Altera o método `correrRapido()` para que seja `abstract`, fazendo com que qualquer classe que implemente a interface `Piloto` tenha que implementar esse método; -* Altera o método `correrDevagar()` para que tenha sua própria implementação +* Keep `run()` method unchanged; +* Changes the `runFast()` method to be `abstract`, so any class that implements the `Pilot` interface has to implement this method; +* Change `runSlow()` method to have its own implementation -.Referências +.References **** * Designing an Interface + -Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 48). Wiley. Edição do Kindle. +Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 48). Wiley. Kindle Edition. * https://www.baeldung.com/java-static-default-methods[Static and Default Methods in Interfaces in Java.] diff --git a/book/contributors.asc b/book/contributors.asc index 39801d0..7f7e3c9 100644 --- a/book/contributors.asc +++ b/book/contributors.asc @@ -1,11 +1,11 @@ [preface] -== Contribuidores +== Contributors -Por ser um livro de código aberto, recebemos várias mudanças de conteúdo e erratas ao longo de seu desenvolvimento. Aqui estão todas as pessoas que contribuíram para a versão em português do livro como um projeto de código aberto. Obrigado a todos por ajudarem a tornar este livro melhor para todos. +Since this is an Open Source book, we have gotten several errata and content changes donated over the years. Here are all the people who have contributed to the English version of Pro Git as an open source project. Thank you everyone for helping make this a better book for everyone. [source,tabsize=8] ---- include::contributors.txt[] ---- -Esse texto é praticamente o mesmo utilizado no *Pro Git 2*. Acesse o texto original https://raw.githubusercontent.com/progit/progit2/master/book/contributors.asc[aqui]. +This is the same text used in *Pro Git 2*. Access the original text https://raw.githubusercontent.com/progit/progit2/master/book/contributors.asc[here]. diff --git a/book/license.asc b/book/license.asc index 65322b2..090996a 100644 --- a/book/license.asc +++ b/book/license.asc @@ -1,4 +1,4 @@ [preface] -== Licença +== License include::../LICENSE.asc[] diff --git a/ch01-getting-started.asc b/ch01-getting-started.asc index 83ed0f1..0651126 100644 --- a/ch01-getting-started.asc +++ b/ch01-getting-started.asc @@ -1,5 +1,5 @@ [[ch01-getting-started]] -== Começando +== Getting Started include::book/01-getting-started/sections/01-introduction.asc[] include::book/01-getting-started/sections/02-objectives.asc[] diff --git a/ch09-assume.asc b/ch09-assume.asc index 7dcbcad..a82bcb3 100644 --- a/ch09-assume.asc +++ b/ch09-assume.asc @@ -1,25 +1,25 @@ [[ch09-assume]] == Assume the following -* *Ausência das instruções de pacote e importação:* +* *Missing package and import statements:* + -Se o código de amostra não incluir instruções de pacote ou de importação, e a pergunta não se referir explicitamente a essas instruções ausentes, suponha que toda a amostra de código esteja no mesmo pacote ou que existam instruções de importação para suportá-las. +If sample code do not include package or import statements, and the question does not explicitly refer to these missing statements, then assume that all sample code is in the same package, or import statements exist to support them. -* *Nenhum nome de arquivo ou caminho de diretório para classes:* +* *No file or directory path names for classes:* + -Se uma pergunta não indicar os nomes de arquivo ou os locais de diretório das classes, assuma um dos seguintes, o que permitirá que o código seja compilado e executado: +If a question does not state the file names or directory locations of classes, then assume one of the following, whichever will enable the code to compile and run: -** Todas as classes estão em um arquivo -** Cada classe está contida em um arquivo separado e todos os arquivos estão em um diretório +** All classes are in one file +** Each class is contained in a separate file, and all files are in one directory -* *Quebras de linha não intencionais:* +* *Unintended line breaks:* + -O código de exemplo pode ter quebras de linha não intencionais. Se você vir uma linha de código que parece ter sido quebrada, e isso criar uma situação em que a quebra de linha é significativa (por exemplo, um literal de String citado foi divido), suponha que a quebra de linha seja uma extensão da mesma linha e não contém um retorno explícito (_carriage return_) que causaria uma falha de compilação. +Sample code might have unintended line breaks. If you see a line of code that looks like it has wrapped, and this creates a situation where the wrapping is significant (for example, a quoted String literal has wrapped), assume that the wrapping is an extension of the same line, and the line does not contain a hard carriage return that would cause a compilation failure. -* *Fragmentos de código:* +* *Code fragments:* + -Um fragmento de código é uma pequena seção do código-fonte que é apresentada sem seu contexto. Suponha que todo o código de suporte necessário exista e que o ambiente ofereça suporte completo à compilação e execução corretas do código mostrado e seu ambiente omitido. +A code fragment is a small section of source code that is presented without its context. Assume that all necessary supporting code exists and that the supporting environment fully supports the correct compilation and execution of the code shown and its omitted environment. -* *Comentários descritivos:* +* *Descriptive comments:* + -Considere comentários descritivos, como "setter e getters vão aqui", pelo valor nominal. Suponha que o código correto exista, compile e execute com êxito para criar o efeito descrito. +Take descriptive comments, such as "setter and getters go here," at face value. Assume that correct code exists, compiles, and runs successfully to create the described effect. diff --git a/images/cover.png b/images/cover.png index e02d043..d2090ef 100644 Binary files a/images/cover.png and b/images/cover.png differ diff --git a/images/ebook-400x400.png b/images/ebook-400x400.png index ed3fd7f..46d725d 100644 Binary files a/images/ebook-400x400.png and b/images/ebook-400x400.png differ diff --git a/java6-to-java8.asc b/java6-to-java8.asc index 2333938..54e3752 100644 --- a/java6-to-java8.asc +++ b/java6-to-java8.asc @@ -1,4 +1,4 @@ -= Guia Prático para Certificação: Atualize sua certificação Java 6 para Java 8 += Practical Guide to Certification: Update your certification from Java 6 to Java 8 Rinaldo Pitzer Jr.; Rodrigo Moutinho :doctype: book :docinfo: @@ -9,8 +9,8 @@ Rinaldo Pitzer Jr.; Rodrigo Moutinho :icons: font :source-highlighter: pygments -:appendix-caption: Apêndice -:toc-title: Índice +:appendix-caption: Appendix +:toc-title: Table of Contents ifdef::ebook-format[:leveloffset: -1] diff --git a/package.json b/package.json index 423ce2d..0a0aa51 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,16 @@ { - "author": "Rinaldo Pitzer Jr. e Rodrigo Moutinho", - "name": "java6-to-java8", - "description": "Guia para ajudar devs Java atualizarem sua certificação Java 6 para Java 8.", + "author": "Rinaldo Pitzer Jr. and Rodrigo Moutinho", + "name": "java6-to-java8-en", + "description": "Guide to help Java devs to upgrade their Java 6 certification to Java 8.", "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/duke-certification/java6-to-java8.git" + "url": "https://github.com/duke-certification/java6-to-java8-en.git" }, "bugs": { - "url": "https://github.com/duke-certification/java6-to-java8/issues" + "url": "https://github.com/duke-certification/java6-to-java8-en/issues" }, - "homepage": "https://github.com/duke-certification/java6-to-java8", + "homepage": "https://github.com/duke-certification/java6-to-java8-en", "keywords": [ "java", "java6", diff --git a/src/org/j6toj8/languageenhancements/literals/Literals_Complete.java b/src/org/j6toj8/languageenhancements/literals/Literals_Complete.java index 1266d10..9f09cbc 100644 --- a/src/org/j6toj8/languageenhancements/literals/Literals_Complete.java +++ b/src/org/j6toj8/languageenhancements/literals/Literals_Complete.java @@ -6,20 +6,20 @@ public static void main(String[] args) { // tag::code[] int i1 = 1; // int - int i2 = 1_000_000; // int com underscore + int i2 = 1_000_000; // int with underscore int i3 = 0567; // octadecimal int i4 = 0xFA1; // hexadecimal - int i5 = 0b0101; // binário + int i5 = 0b0101; // binary - long l1 = 1L; // long com L - long l2 = 1l; // long com l - long l3 = 12_345_6_7890_123456_789L; // long com underscore - long l4 = 0xFA1L; // long hexadecimal + long l1 = 1L; // long with L + long l2 = 1l; // long with l + long l3 = 12_345_6_7890_123456_789L; // long with underscore + long l4 = 0xFA1L; // hexadecimal long double d1 = 1.00; // double - double d2 = 100_000.01; // double com underscore - double d3 = 1D; // double com D - double d4 = 3.1E2; // notação científica = 3.1 * 10^2 = 3.1 * 100 = 310.0 + double d2 = 100_000.01; // double with underscore + double d3 = 1D; // double with D + double d4 = 3.1E2; // cientific notation = 3.1 * 10^2 = 3.1 * 100 = 310.0 float f1 = 1.00F; // float // end::code[] diff --git a/src/org/j6toj8/languageenhancements/literals/Literals_Prefix.java b/src/org/j6toj8/languageenhancements/literals/Literals_Prefix.java index 755a220..0514115 100644 --- a/src/org/j6toj8/languageenhancements/literals/Literals_Prefix.java +++ b/src/org/j6toj8/languageenhancements/literals/Literals_Prefix.java @@ -5,11 +5,11 @@ public class Literals_Prefix { public static void main(String[] args) { // tag::code[] - int i1 = 0567; // octadecimal - base 8 - começa com 0 - int i2 = 0xFA1; // hexadecimal - base 16 - começa com 0x - int i3 = 0b0101; // binário - base 2 - começa com 0b + int i1 = 0567; // octadecimal - base 8 - starts with 0 + int i2 = 0xFA1; // hexadecimal - base 16 - starts with 0x + int i3 = 0b0101; // binary - base 2 - starts with 0b - long l1 = 0xABCL; // long também pode ser hexadecimal - começa com 0x e termina com L + long l1 = 0xABCL; // long can also be hexadecimal - starts with 0x and ends with L // end::code[] } } diff --git a/src/org/j6toj8/languageenhancements/literals/Literals_Suffix.java b/src/org/j6toj8/languageenhancements/literals/Literals_Suffix.java index 2335118..437ad92 100644 --- a/src/org/j6toj8/languageenhancements/literals/Literals_Suffix.java +++ b/src/org/j6toj8/languageenhancements/literals/Literals_Suffix.java @@ -5,11 +5,11 @@ public class Literals_Suffix { public static void main(String[] args) { // tag::code[] - int i1 = 1; // por padrão é int - long l1 = 1L; // com um L no final, é um long + int i1 = 1; // by default is int + long l1 = 1L; // with an L in the end, it's a long double d1 = 1.0; - double d2 = 1.0D; // com ou sem D no final, se tiver casa decimal é um double por padrão - float f1 = 1.0F; // com um F no final, é um float + double d2 = 1.0D; // with or without a D in the end, if you have a decimal place is a double by default + float f1 = 1.0F; // with an F at the end, it's a float // end::code[] } } diff --git a/src/org/j6toj8/languageenhancements/literals/Literals_Underscore.java b/src/org/j6toj8/languageenhancements/literals/Literals_Underscore.java index d98a39e..fe59f60 100644 --- a/src/org/j6toj8/languageenhancements/literals/Literals_Underscore.java +++ b/src/org/j6toj8/languageenhancements/literals/Literals_Underscore.java @@ -5,20 +5,20 @@ public class Literals_Underscore { public static void main(String[] args) { // tag::code[] - int i1 = 1_000_000; // int com underscore - é o mesmo que escrever 1000000 - int i2 = 10_00_00_0; // o underscore pode estar em qualquer posição entre 2 números - int i3 = _1000; // NÃO COMPILA - o underscore não pode estar no início - int i4 = 1000_; // NÃO COMPILA - o underscore não pode estar no final - int i5 = 1___000; // COMPILA - vários underscore é permitido, desde que estejam entre 2 números - int i6 = 0x_100; // NÃO COMPILA - entre marcador de base não é permitido - int i7 = 0xF_F; // COMPILA - apesar de serem letras, representam valores numéricos dessa base - - long l1 = 12_345_6_7890_123456_789L; // long com underscore - long l2 = 12_345_6_789_L; // NÃO COMPILA - não pode ficar ao lado de um marcador de tipo - - double d1 = 100_000.01; // double com underscore - double d2 = 10_.01; // NÃO COMPILA - o underscore deve estar entre números - double d3 = 10._01; // NÃO COMPILA - o underscore deve estar entre números + int i1 = 1_000_000; // int with underscore - is the same as writing 1000000 + int i2 = 10_00_00_0; // underscore can be anywhere between 2 numbers + int i3 = _1000; // NOT COMPILING - underscore can't be at the beginning + int 14 = 1000_; // NOT COMPILING - underscore can't be at the end + int i5 = 1___000; // COMPILES - Multiple underscore is allowed as long as they are between 2 numbers + int i6 = 0x_100; // NOT COMPILING - between base marker is not allowed + int i7 = 0xF_F; // COMPILES - Although they are letters, they represent numerical values of this base + + long l1 = 12_345_6_7890_123456_789L; // long with underscore + long l2 = 12_345_6_789_L; // NOT COMPILING - cannot be next to a type marker + + double d1 = 100_000.01; // double with underscore + double d2 = 10_.01; // NOT COMPILING - underscore must be between numbers + double d3 = 10._01; // NOT COMPILING - underscore must be between numbers // end::code[] } } diff --git a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_CheckedException.java b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_CheckedException.java index 8fbe9bd..b42387f 100644 --- a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_CheckedException.java +++ b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_CheckedException.java @@ -9,8 +9,8 @@ public static void main(String[] args) { try { throw new NullPointerException(); - } catch (NullPointerException | IOException e) { // NÃO COMPILA - IOException não é lançada dentro do bloco try - System.out.println("Exceção capturada: " + e); + } catch (NullPointerException | IOException e) { // NOT COMPILING - IOException is not thrown inside try block + System.out.println("Exception caught: " + e); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Complete.java b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Complete.java index d65f3e5..6749eb7 100644 --- a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Complete.java +++ b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Complete.java @@ -8,9 +8,9 @@ public static void main(String[] args) { try { throw new NullPointerException(); } catch (NullPointerException | IllegalArgumentException | IllegalStateException e) { - System.out.println("Exceção capturada: " + e); + System.out.println("Exception caught: " + e); } catch (Exception e) { - System.out.println("Exceção capturada: " + e); + System.out.println("Exception caught: " + e); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_GenericsLower.java b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_GenericsLower.java index 658b6dc..3c07133 100644 --- a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_GenericsLower.java +++ b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_GenericsLower.java @@ -8,9 +8,9 @@ public static void main(String[] args) { try { throw new NullPointerException(); } catch (Exception e) { - System.out.println("Exceção capturada: " + e); - } catch (NullPointerException | IllegalArgumentException e) { // NÃO COMPILA - NullPointerException é mais específico que Exception, logo deveria ser capturada antes de Exception - System.out.println("Exceção capturada: " + e); + System.out.println("Exception caught: " + e); + } catch (NullPointerException | IllegalArgumentException e) { // NOT COMPILING - NullPointerException is more specific than Exception, so it should be caught before Exception + System.out.println("Exception caught: " + e); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_MultipleSameCatch.java b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_MultipleSameCatch.java index c6a816d..cc3b0b6 100644 --- a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_MultipleSameCatch.java +++ b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_MultipleSameCatch.java @@ -9,12 +9,12 @@ public static void main(String[] args) { try { throw new NullPointerException(); - } catch (NullPointerException | IllegalArgumentException e) { // COMPILA - múltiplas exceções no mesmo catch, só uma variável no final - System.out.println("Exceção capturada: " + e); - } catch (IllegalStateException ise | UnsupportedOperationException uoe) { // NÃO COMPILA - mais de uma variável declarada - System.out.println("Exceção capturada: " + ise); - } catch (ClassCastException cce | ConcurrentModificationException) { // NÃO COMPILA - só uma variável, mas no lugar errado - System.out.println("Exceção capturada: " + cce); + } catch (NullPointerException | IllegalArgumentException e) { // COMPILES - multiple exceptions in the same catch, only one variable at the end + System.out.println("Exception caught: " + e); + } catch (IllegalStateException ise | UnsupportedOperationException uoe) { // NOT COMPILING - more than one declared variable + System.out.println("Exception caught: " + ise); + } catch (ClassCastException cce | ConcurrentModificationException) { // NOT COMPILING - just one variable but in the wrong place + System.out.println("Exception caught: " + cce); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_OverrideVar.java b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_OverrideVar.java index 724cf9d..b09ada8 100644 --- a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_OverrideVar.java +++ b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_OverrideVar.java @@ -8,9 +8,9 @@ public static void main(String[] args) { try { throw new NullPointerException(); } catch (NullPointerException | IllegalArgumentException e) { - e = new IllegalStateException(); // NÃO COMPILA - a variável não pode ser sobrescrita quando está em um multi-catch + e = new IllegalStateException(); // NOT COMPILING - variable cannot be overwritten when multi-catching } catch (Exception e) { - e = new IllegalStateException(); // COMPILA - ainda é possível sobrescrever a variável quando não é um multi-catch + e = new IllegalStateException(); // COMPILES - it is still possible to overwrite the variable when it is not a multi-catch } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Redundant.java b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Redundant.java index d71d9ce..81f7ed6 100644 --- a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Redundant.java +++ b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Redundant.java @@ -9,8 +9,8 @@ public static void main(String[] args) { try { throw new NullPointerException(); - } catch (RuntimeException | IllegalArgumentException e) { // NÃO COMPILA - IllegalArgumentException herda de RuntimeException, logo seria redundante - System.out.println("Exceção capturada: " + e); + } catch (RuntimeException | IllegalArgumentException e) { // NOT COMPILING - IllegalArgumentException inherits from RuntimeException, so would be redundant + System.out.println("Exception caught: " + e); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_RepeatException.java b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_RepeatException.java index 05fd960..ec24845 100644 --- a/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_RepeatException.java +++ b/src/org/j6toj8/languageenhancements/multipleexception/MultipleException_RepeatException.java @@ -8,9 +8,9 @@ public static void main(String[] args) { try { throw new NullPointerException(); } catch (NullPointerException | IllegalArgumentException e) { - System.out.println("Exceção capturada: " + e); - } catch (IllegalStateException | NullPointerException e) { // NÃO COMPILA - NullPointerException já foi capturada no catch anterior - System.out.println("Exceção capturada: " + e); + System.out.println("Exception caught: " + e); + } catch (IllegalStateException | NullPointerException e) { // NOT COMPILING - NullPointerException already caught in previous catch + System.out.println("Exception caught: " + e); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Abstract.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Abstract.java index 28a6c26..8526acd 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Abstract.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Abstract.java @@ -5,20 +5,20 @@ public class StaticDefaultInInterfaces_Abstract { // tag::code[] - interface Corredor { - default String correr() { // COMPILA - método default não é abstract - return "Correndo"; + interface Runner { + default String run() { // COMPILES - default method is not abstract + return "Running"; } - abstract default String correrRapido() { // NÃO COMPILA - método default não pode ser declarado abstract - return "Correndo Rápido"; + abstract default String runFast() { // NOT COMPILING - default method cannot be declared abstract + return "Running fast"; } - String correrDevagar(); // COMPILA - método comum, é abstract por padrão, mesmo que de forma implícita + String runSlow(); // COMPILES - common method, is abstract by default, even if implicitly - abstract String correrExtremo(); // COMPILA - método comum, declarado abstract de forma explícita + abstract String runExtreme(); // COMPILES - common method, explicitly declared abstract - abstract static double calculeVelocidade(int d, int t) { // NÃO COMPILA - método static não pode ser declarado abstract + abstract static double calculateSpeed(int d, int t) { // NOT COMPILING - static method cannot be declared abstract return d / t; } } diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_AccessModifiers.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_AccessModifiers.java index 7e31eb0..50e507a 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_AccessModifiers.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_AccessModifiers.java @@ -5,21 +5,21 @@ public class StaticDefaultInInterfaces_AccessModifiers { // tag::code[] - interface Corredor { - default String correr() { // COMPILA - não há modificador de acesso declarado, é automaticamente público - return "Correndo"; + interface Runner { + default String run() { // COMPILES - there is no declared access modifier, it is automatically public + return "Running"; } - public default String correrRapido() { // COMPILA - modificador de acesso público explícito - return "Correndo Rápido"; + public default String runFast() { // COMPILES - explicit public access modifier + return "Running fast"; } - protected default String correrDevagar() { // NÃO COMPILA - o método deve ser obrigatoriamente público - return "Correndo Devagar"; + protected default String runSlow() { // NOT COMPILING - the method must be public + return "Running slow"; } - private default String correrExtremo() { // NÃO COMPILA - o método deve ser obrigatoriamente público - return "Correndo ao Extremo"; + private default String runExtreme() { // NOT COMPILING - the method must be public + return "Running to the extreme"; } - private static double calculeVelocidade(int d, int t) { // NÃO COMPILA - o método deve ser obrigatoriamente público + private static double calculateSpeed(int d, int t) { // NOT COMPILING - the method must be public return d / t; } } diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Complete.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Complete.java index 4e84ded..86d76b0 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Complete.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Complete.java @@ -5,28 +5,28 @@ public class StaticDefaultInInterfaces_Complete { // tag::code[] - interface Corredor { - static double calculeVelocidade(int distancia, int tempo) { - return distancia / tempo; + interface Runner { + static double calculateSpeed(int distance, int time) { + return distance / time; } - default String correr() { - return "Correndo"; + default String run() { + return "Running"; } - String correrRapido(); + String runFast(); } - static class Pessoa implements Corredor { + static class Person implements Runner { @Override - public String correrRapido() { - return "Pessoa Correndo Rápido"; + public String runFast() { + return "Fast Running Person"; } public static void main(String[] args) throws IOException { - System.out.println(Corredor.calculeVelocidade(100, 10)); - System.out.println(new Pessoa().correr()); - System.out.println(new Pessoa().correrRapido()); + System.out.println(Runner.calculateSpeed(100, 10)); + System.out.println(new Person().run()); + System.out.println(new Person().runFast()); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Default.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Default.java index b673e3c..1294045 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Default.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Default.java @@ -5,25 +5,25 @@ public class StaticDefaultInInterfaces_Default { // tag::code[] - interface Corredor { - default String correr() { - return "Correndo"; + interface Runner { + default String run() { + return "Running"; } } - static class Pessoa implements Corredor { + static class Person implements Runner { } - static class Cavalo implements Corredor { + static class Horse implements Runner { @Override - public String correr() { - return "Galopando"; + public String run() { + return "Galloping"; } public static void main(String[] args) throws IOException { - System.out.println(new Pessoa().correr()); - System.out.println(new Cavalo().correr()); + System.out.println(new Person().run()); + System.out.println(new Horse().run()); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_InterfaceInheritance.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_InterfaceInheritance.java index 317942b..13cbc43 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_InterfaceInheritance.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_InterfaceInheritance.java @@ -3,23 +3,23 @@ public class StaticDefaultInInterfaces_InterfaceInheritance { // tag::code[] - interface Corredor { - default String correr() { - return "Correndo"; + interface Runner { + default String run() { + return "Running"; } - default String correrRapido() { - return "Correndo Rápido"; + default String runFast() { + return "Running Fast"; } - default String correrDevagar() { - return "Correndo Devagar"; + default String runSlow() { + return "Running Slow"; } } - interface Piloto extends Corredor { - String correrRapido(); + interface Pilot extends Runner { + String runFast(); - default String correrDevagar() { - return "Piloto Correndo Devagar"; + default String runSlow() { + return "Pilot Running Slow"; } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefault.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefault.java index 7ab1288..2f42583 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefault.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefault.java @@ -3,26 +3,26 @@ public class StaticDefaultInInterfaces_RepeatedDefault { // tag::code[] - interface Corredor { - default String correr() { - return "Correndo"; + interface Runner { + default String run() { + return "Running"; } } - interface Piloto { - default String correr() { - return "Piloto Correndo"; + interface Pilot { + default String run() { + return "Pilot Running"; } } - static class Pessoa implements Corredor, Piloto { // NÃO COMPILA - implementa duas interfaces com métodos repetidos e não sobrescreve + static class Person implements Runner, Pilot { // NOT COMPILING - implements two interfaces with repeated methods and does not overwrite } - static class Gigante implements Corredor, Piloto { // COMPILA - implementa duas interfaces com métodos repetidos, mas sobrescreve e cria sua própria implementação + static class Giant implements Runner, Pilot { // COMPILES - implements two interfaces with repeated methods, but overwrites and creates its own implementation @Override - public String correr() { - return "Gigante Correndo"; + public String run() { + return "Giant Running"; } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefaultSuper.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefaultSuper.java index 037ccaa..567bcde 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefaultSuper.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefaultSuper.java @@ -3,26 +3,26 @@ public class StaticDefaultInInterfaces_RepeatedDefaultSuper { // tag::code[] - interface Corredor { - default String correr() { - return "Correndo"; + interface Runner { + default String run() { + return "Running"; } } - interface Piloto { - default String correr() { - return "Piloto Correndo"; + interface Pilot { + default String run() { + return "Pilot Running"; } } - static class Pessoa implements Corredor, Piloto { // COMPILA - mantém a implementação do Corredor no método correr() + static class Person implements Runner, Pilot { // COMPILES - keep the Runner implementation in the run() method @Override - public String correr() { - return Corredor.super.correr(); + public String run() { + return Runner.super.run(); } public static void main(String[] args) { - System.out.println(new Pessoa().correr()); + System.out.println(new Person().run()); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Static.java b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Static.java index da7b961..aa70046 100644 --- a/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Static.java +++ b/src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Static.java @@ -5,16 +5,16 @@ public class StaticDefaultInInterfaces_Static { // tag::code[] - interface Corredor { - static double calculeVelocidade(int distancia, int tempo) { - return distancia / tempo; + interface Runner { + static double calculateSpeed(int distance, int time) { + return distance / time; } } - static class Pessoa implements Corredor { + static class Person implements Runner { public static void main(String[] args) throws IOException { - System.out.println(Corredor.calculeVelocidade(100, 50)); // COMPILA - método static de uma interface sendo chamado como se fosse de uma classe comum - System.out.println(Pessoa.calculeVelocidade(100, 50)); // NÃO COMPILA - o método static não é herdado, nem implementado, pela classe Pessoa + System.out.println(Runner.calculateSpeed(100, 50)); // COMPILES - static method of an interface being called as if it were from a common class + System.out.println(Person.calculateSpeed(100, 50)); // NOT COMPILING - the static method is not inherited or implemented by the Person class. } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Break.java b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Break.java index 4abf008..12198ad 100644 --- a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Break.java +++ b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Break.java @@ -5,18 +5,18 @@ public class StringInSwitch_Break { // tag::code[] public static void main(String[] args) { - String mes = "jan"; + String month = "jan"; - switch (mes) { + switch (month) { case "jan": - System.out.println("Janeiro"); + System.out.println("January"); default: - System.out.println("Não é um mês"); - case "fev": - System.out.println("Fevereiro"); + System.out.println("Not a month"); + case "feb": + System.out.println("February"); break; case "mar": - System.out.println("Março"); + System.out.println("March"); break; } } diff --git a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Complete.java b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Complete.java index ef52d4c..16cc92b 100644 --- a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Complete.java +++ b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Complete.java @@ -5,17 +5,17 @@ public class StringInSwitch_Complete { // tag::code[] public static void main(String[] args) { - String mes = "jan"; + String month = "jan"; - switch (mes) { + switch (month) { case "jan": - System.out.println("Janeiro"); + System.out.println("January"); break; - case "fev": - System.out.println("Fevereiro"); + case "feb": + System.out.println("February"); break; case "mar": - System.out.println("Março"); + System.out.println("March"); break; default: break; diff --git a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_ConstantOnly.java b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_ConstantOnly.java index bd43487..a3226d2 100644 --- a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_ConstantOnly.java +++ b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_ConstantOnly.java @@ -3,31 +3,31 @@ public class StringInSwitch_ConstantOnly { // tag::code[] - private static final String FEV = "fev"; + private static final String FEB = "feb"; private static String jan = "jan"; - public static void getNomeMes(final String mai) { + public static void getMonthName(final String may) { - String mes = "jan"; + String month = "jan"; final String mar = "mar"; - String abr = "abr"; + String apr = "apr"; - switch (mes) { - case jan: // NÃO COMPILA - jan é um atributo comum, pode mudar em tempo de execução - System.out.println("Janeiro"); + switch (month) { + case jan: // NOT COMPILING - jan is a common attribute, can change at runtime + System.out.println("January"); break; - case FEV: // COMPILA - FEV é uma constante em tempo de compilação, seu valor nunca muda - System.out.println("Fevereiro"); + case FEB: // COMPILES - FEB is a compilation time constant, its value never changes + System.out.println("February"); break; - case mar: // COMPILA - mar é uma constante em tempo de compilação, seu valor nunca muda - System.out.println("Março"); + case mar: // COMPILES - mar is a constant at compilation time, its value never changes + System.out.println("March"); break; - case abr: // NÃO COMPILA - abr é uma variável comum, pode mudar em tempo de execução - System.out.println("Março"); + case apr: // NOT COMPILING - apr is a common variable, can change at runtime + System.out.println("April"); break; - case mai: // NÃO COMPILA - mai é final, mas não é constante, pode mudar em tempo de execução - System.out.println("Março"); + case may: // NOT COMPILING - may is final but not constant, may change at runtime + System.out.println("May"); break; } } diff --git a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Default.java b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Default.java index 612cd0b..705d27c 100644 --- a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Default.java +++ b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Default.java @@ -4,20 +4,20 @@ public class StringInSwitch_Default { // tag::code[] public static void main(String[] args) { - - String mes = "jan"; - - switch (mes) { + + String month = "jan"; + + switch (month) { case "jan": - System.out.println("Janeiro"); + System.out.println("January"); break; - default: // COMPILA - O default pode estar em qualquer posição + default: // COMPILES - `Default` can be in any position break; - case "jan": // NÃO COMPILA - Já existe o case "jan" - System.out.println("Janeiro2"); + case "jan": // NOT COMPILING - There is already case "jan" + System.out.println("January2"); break; case "mar": - System.out.println("Março"); + System.out.println("March"); break; } } diff --git a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Empty.java b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Empty.java index d9ddfe7..a672f4a 100644 --- a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Empty.java +++ b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Empty.java @@ -5,8 +5,8 @@ public class StringInSwitch_Empty { // tag::code[] public static void main(String[] args) { - String mes = "jan"; - switch (mes) {} // COMPILA - switch pode estar vazio, mesmo que seja inútil + String month = "jan"; + switch (month) {} // COMPILES - switch may be empty even if it's useless } // end::code[] } diff --git a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Type.java b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Type.java index 92d976c..2ecf0fd 100644 --- a/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Type.java +++ b/src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Type.java @@ -5,14 +5,14 @@ public class StringInSwitch_Type { // tag::code[] public static void main(String[] args) { - Long mes = 1L; + Long month = 1L; - switch (mes) { // NÃO COMPILA - Long não é um tipo suportado + switch (month) { // NOT COMPILING - Long is not a supported type. case 1L: - System.out.println("Janeiro"); + System.out.println("January"); break; case 2L: - System.out.println("Fevereiro"); + System.out.println("February"); break; default: break; diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_AutoCloseable.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_AutoCloseable.java index 391dbf1..839fc85 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_AutoCloseable.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_AutoCloseable.java @@ -5,15 +5,15 @@ public class TryWithResouces_AutoCloseable { // tag::code[] - static class Porta implements AutoCloseable { + static class Door implements AutoCloseable { @Override - public void close() { // chamado automaticamente pelo try-with-resources - System.out.println("Porta fechada."); + public void close() { // called automatically by try-with-resources + System.out.println("Closed door."); } } public static void main(String[] args) throws FileNotFoundException { - try (Porta porta = new Porta()) { // Porta instanciada dentro da instrução try-with-resources + try (Door door = new Door()) { // Door instantiated within the try-with-resources statement System.out.println("try"); } } diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CloseException.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CloseException.java index 59d0ef6..46cdbaa 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CloseException.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CloseException.java @@ -3,29 +3,29 @@ public class TryWithResouces_CloseException { // tag::code[] - static class Porta implements AutoCloseable { + static class Door implements AutoCloseable { @Override - public void close() throws Exception { // declara throws Exception obrigatoriamente + public void close() throws Exception { // must declare throws Exception throw new Exception(); } } void try1() { - try (Porta porta = new Porta()) { // NÃO COMPILA - exceção do close() não é capturada nem declarada - System.out.println("Olá 1"); + try (Door door = new Door()) { // NOT COMPILING - the exception of close() is not captured or declared + System.out.println("Hello 1"); } } void try2() { - try (Porta porta = new Porta()) { - System.out.println("Olá 2"); - } catch (Exception e) { // COMPILA - exceção capturada + try (Door door = new Door()) { + System.out.println("Hello 2"); + } catch (Exception e) { // COMPILES - exception caught } } - void try3() throws Exception { // COMPILA - exceção declarada no método - try (Porta porta = new Porta()) { - System.out.println("Olá 3"); + void try3() throws Exception { // COMPILES - exception declared in the method + try (Door door = new Door()) { + System.out.println("Hello 3"); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CommonTry.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CommonTry.java index 8f5301e..dbb332c 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CommonTry.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CommonTry.java @@ -6,23 +6,23 @@ public class TryWithResouces_CommonTry { public static void main(String[] args) { try { System.out.println("try"); - } // NÃO COMPILA - try "comum" sem catch ou finally + } // NOT COMPILING - "common" try without catch or finally try { System.out.println("try"); } catch (Exception e) { - } // COMPILA - try "comum" só com catch + } // COMPILES - "common" try with catch only try { System.out.println("try"); } finally { - } // COMPILA - try "comum" só com finally + } // COMPILES - "common" try with finally only try { System.out.println("try"); } catch (Exception e) { } finally { - } // COMPILA - try "comum" com catch e finally + } // COMPILES - "common" try with catch and finally } // end::code[] } diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Complete.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Complete.java index 08e124a..011ce80 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Complete.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Complete.java @@ -11,35 +11,35 @@ public class TryWithResouces_Complete { // tag::code[] public static void main(String[] args) throws IOException { - // criação de 2 arquivos - File file = new File("arquivo.txt"); - File file2 = new File("arquivo2.txt"); + // creates 2 files + File file = new File("file.txt"); + File file2 = new File("file2.txt"); - // Exemplo try-with-resources com PrintWriter + // try-with-resources example with PrintWriter try (PrintWriter writer = new PrintWriter(file)) { - // escreve no arquivo.txt - writer.println("Olá Mundo!"); + // write to file.txt + writer.println("Hello World!"); } - // Exemplo try-with-resources com BufferedReader + // try-with-resources example with BufferedReader try (BufferedReader reader = Files.newBufferedReader(file.toPath())) { - // imprime no console uma linha do arquivo.txt + // print a line from file.txt to the console System.out.println(reader.readLine()); } - // Exemplo try-with-resources com BufferedReader e BufferedWriter + // try-with-resources example with BufferedReader and BufferedWriter try (BufferedReader reader = Files.newBufferedReader(file.toPath()); BufferedWriter writer = Files.newBufferedWriter(file2.toPath())) { - // lê a linha do arquivo.txt e escreve no arquivo2.txt + // read line from file.txt and write to file2.txt writer.write(reader.readLine() + "2"); } - // Exemplo try-with-resources com BufferedReader + // try-with-resources example with BufferedReader try (BufferedReader reader = Files.newBufferedReader(file2.toPath())) { - // imprime no console uma linha do arquivo2.txt + // print a line from file2.txt to the console System.out.println(reader.readLine()); } - // todos os Reader e Writer já foram fechados. + // all Reader and Writer have already been closed } // end::code[] } diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Java6.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Java6.java index c63af70..fd882e5 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Java6.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Java6.java @@ -8,14 +8,14 @@ public class TryWithResouces_Java6 { // tag::code[] public static void main(String[] args) throws FileNotFoundException { - File file = new File("arquivo.txt"); + File file = new File("file.txt"); PrintWriter writer = null; try { writer = new PrintWriter(file); - writer.println("Olá Mundo!"); + writer.println("Hello World!"); } finally { if (writer != null) { - writer.close(); // fechando o writer manualmente + writer.close(); // closing the writer manually } } } diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_NoAutoCloseable.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_NoAutoCloseable.java index 060038b..00b89e6 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_NoAutoCloseable.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_NoAutoCloseable.java @@ -3,11 +3,11 @@ public class TryWithResouces_NoAutoCloseable { // tag::code[] - static class Prateleira {} + static class Shelf {} public static void main(String[] args) { - try (Prateleira prateleira = new Prateleira()) { // NÃO COMPILA - Prateleira não implementa AutoClosable - System.out.println("Olá"); + try (Shelf shelf = new Shelf()) { // NOT COMPILING - Shelf do not implement AutoCloseable + System.out.println("Hello"); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Order.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Order.java index ddd53e9..e6a014d 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Order.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Order.java @@ -3,24 +3,24 @@ public class TryWithResouces_Order { // tag::code[] - static class Porta implements AutoCloseable { + static class Door implements AutoCloseable { @Override - public void close() { // chamado automaticamente pelo try-with-resources - System.out.println("Porta fechada."); + public void close() { // called automatically by try-with-resources + System.out.println("Closed door."); } } - static class Gaveta implements AutoCloseable { + static class Drawer implements AutoCloseable { @Override - public void close() { // chamado automaticamente pelo try-with-resources - System.out.println("Gaveta fechada."); + public void close() { // called automatically by try-with-resources + System.out.println("Drawer closed."); } } public static void main(String[] args) { - try (Porta porta = new Porta(); - Gaveta gaveta = new Gaveta()) { - System.out.println("Olá."); + try (Door door = new Door(); + Drawer drawer = new Drawer()) { + System.out.println("Hello."); } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_ResourceInsideTry.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_ResourceInsideTry.java index ecaff85..2a6b644 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_ResourceInsideTry.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_ResourceInsideTry.java @@ -3,20 +3,20 @@ public class TryWithResouces_ResourceInsideTry { // tag::code[] - static class Porta implements AutoCloseable { + static class Door implements AutoCloseable { @Override - public void close() { // chamado automaticamente pelo try-with-resources - System.out.println("Porta fechada."); + public void close() { // called automatically by try-with-resources + System.out.println("Closed door."); } } public static void main(String[] args) { - try (Porta porta = new Porta()) { - porta.toString(); + try (Door door = new Door()) { + door.toString(); } catch (Exception e) { - porta.toString(); // NÃO COMPILA - variável porta só disponível dentro do bloco try + door.toString(); // NOT COMPILING - door variable only available within try block } finally { - porta.toString(); // NÃO COMPILA - variável porta só disponível dentro do bloco try + door.toString(); // NOT COMPILING - door variable only available within try block } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Suppressed.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Suppressed.java index cf25740..a67fd68 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Suppressed.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Suppressed.java @@ -3,21 +3,21 @@ public class TryWithResouces_Suppressed { // tag::code[] - static class Porta implements AutoCloseable { + static class Door implements AutoCloseable { @Override public void close() { System.out.println("close"); - throw new RuntimeException("erro no close"); // lança RuntimeException, mas só depois do try + throw new RuntimeException("error on close"); // throws RuntimeException, but only after try } } public static void main(String[] args) { - try (Porta porta = new Porta()) { + try (Door door = new Door()) { System.out.println("try"); - throw new RuntimeException("erro no try"); // lança RuntimeException - } catch (RuntimeException e) { // captura RuntimeException - qual foi capturada? - System.out.println(e.getMessage()); // apresenta a mensagem da exceção do try - System.out.println(e.getSuppressed()[0].getMessage()); // apresenta a mensagem da exceção suprimida, ou seja, do close + throw new RuntimeException("error on try"); // throws RuntimeException + } catch (RuntimeException e) { // RuntimeException capture - which was captured? + System.out.println(e.getMessage()); // display try exception message + System.out.println(e.getSuppressed()[0].getMessage()); // displays the message of the suppressed exception, i.e., close } } // end::code[] diff --git a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_WithCatchFinally.java b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_WithCatchFinally.java index 0f2feb2..fa167a8 100644 --- a/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_WithCatchFinally.java +++ b/src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_WithCatchFinally.java @@ -5,16 +5,16 @@ public class TryWithResouces_WithCatchFinally { // tag::code[] - static class Porta implements AutoCloseable { + static class Door implements AutoCloseable { @Override - public void close() throws Exception { // chamado automaticamente pelo try-with-resources - System.out.println("Porta fechada."); - throw new Exception(); // lança Exception + public void close() throws Exception { // called automatically by try-with-resources + System.out.println("Closed door."); + throw new Exception(); // throws Exception } } public static void main(String[] args) throws FileNotFoundException { - try (Porta porta = new Porta()) { // Porta instanciada dentro da instrução try-with-resources + try (Door door = new Door()) { // Door instantiated within try-with-resources statement System.out.println("try"); } catch (Exception e) { System.out.println("catch");