/java-tutoriais

Tutoriais da Documentação do Java em Português.

Primary LanguageJavaScript

Este documento é uma base de estudos em Português para a Documentação "The Java™ Tutorials" disponibilizada pela Oracle. A organização deste documento segue o mesmo padrão da organização da documentação da Oracle. Você pode conferir a fonte de cada tópico clicando no título correspondente.

Compilador

A IDE chama o Javac (compilador Java) que compilará o arquivo .java em um arquivo .class. O arquivo class possui os bytecodes que são compreendidos pela Java Virtual Machine. Então a JavaVM transformará o arquivo .class nos bits compreendidos pela máquina.

Plataforma Java

Plataforma é o hardware ou software onde uma aplicação roda. A plataforma Java roda a nível de software e possui dois componentes:

  • Java Virtual Machine (Java VM): transforma o arquivo .class bytecode em arquivos para serem entendidos pela máquina.
  • Java Application Programming Interface (API): provê as principais classes usadas em Java. Ex: System.

Organização do Projeto Java

Ao criar uma aplicação Java, os arquivos ficarão na pasta src. Os arquivos .class com os bytecodes de cada arquivo .java ficarão na pasta bin.

Question 1: When you compile a program written in the Java programming language, the compiler converts the human-readable source file into platform-independent code that a Java Virtual Machine can understand. What is this platform-independent code called?

BinaryCode, it is on a .class file

Question 2: Which of the following is not a valid comment:

a. /** comment / b. / comment / c. / comment d. // comment

c

Question 3: What is the first thing you should check if you see the following error at runtime:

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp.java.

The classpath. The class was not found.

Question 4: What is the correct signature of the main method?

public static void main(String[] args){}
or
public static void main(String... args){}

Question 5: When declaring the main method, which modifier must come first, public or static?

Both.

Question 6: What parameters does the main method define?

String parameters.

Exercises Exercise 1: Change the HelloWorldApp.java program so that it displays Hola Mundo! instead of Hello World!.

Exercise 2: You can find a slightly modified version of HelloWorldApp here: HelloWorldApp2.java

The program has an error. Fix the error so that the program successfully compiles and runs. What was the error?

Miss a "

Answers

O que é Herança

Uma classe herda de outra quando pega para si os atributos e os métodos não privados da superclasse.Classes Java podem ter vários subclasses, mas apenas uma superclasse:

class MountainBike extends Bicycle{}

O que é uma Interface

A interface é um grupo de métodos com conteúdos vazios:

interface Bicycle {
	
	void changeCadence(int newValue);
	
	void changeGear(int newValue);
	
	void speedUp(int increment);
	
	void applyBrakes(int decrement);
	
}

A classe que implementa a interface é:

class ACMEBicycle implements Bicycle{

	int cadence = 0;
	int speed = 0;
	int gear = 1;
	
	public void main(String[] args) {
		changeCadence(2);
		printStates();
	}
	
	public void changeCadence(int newValue) {
		cadence = newValue;
	}
	
	public void changeGear(int newValue) {
		gear = newValue;
	}
	
	public void speedUp(int increment) {
		speed += increment;
	}
	
	public void applyBrakes(int decrement) {
		speed -= decrement;
	}
	
	public void printStates() {
		System.out.println(
				"candece: " +  cadence +
				"\nspeed: " + speed +
				"\ngear: " + gear
				);
	}
	
}

O que é um pacote

Organizam as classes e as interfaces.

A Plataforma Java provê uma grande biblioteca de classes (conjunto de pacotes). Esta biblioteca é a API do Java. Seus pacotes representam as tarefas mais utilizadas. Existem milhares de classes que podem ser utilizadas desta biblioteca e isto permite que o programador foque apenas na sua aplicação sem se preocupar com infraestrutura.

Acesse a Especificação da Java Plataforma API que lista todos os pacotes, classes, interfaces, campos e métodos que a plataforma oferece.

Questions

  1. Real-world objects contain STATES and BEHAVIOR.
  2. A software object's state is stored in FIELDS.
  3. A software object's behavior is exposed through METHODS.
  4. Hiding internal data from the outside world, and accessing it only through publicly exposed methods is known as data ENCAPSULATION.
  5. A blueprint for a software object is called a CLASS.
  6. Common behavior can be defined in a SUPERCLASS and inherited into a SUBCLASS using the EXTENDS keyword.
  7. A collection of methods with no implementation is called an INTERFACE.
  8. A namespace that organizes classes and interfaces by functionality is called a PACKAGE.
  9. The term API stands for APLICATION PROGRAM INTERFACE.

Exercises

  1. Create new classes for each real-world object that you observed at the beginning of this trail. Refer to the Bicycle class if you forget the required syntax.
  2. For each new class that you've created above, create an interface that defines its behavior, then require your class to implement it. Omit one or two methods and try compiling. What does the error look like?

Projeto WhatIsAnInterface

Variáveis

  • Variáveis de Instância (Non-static fields): quando objetos armazenam suas próprias variáveis/fields, independente das variáveis de outros objetos da mesma classe.
  • Variáveis de Classe (Static Fields): quando há uma variável/field estática em uma classe, todas as instâncias desta classe (ou seja, objetos) compartilham a mesma cópia desta variável.
  • Variáveis locais: variáveis/fields visíveis apenas dentro dos métodos.
  • Parâmetros: variáveis (não fields) que são parâmetros para os métodos.

Tipos de dados primitivos

Java suporta oito tipos primitivos de dados:

  • byte: inteiro de complemento de dois de 8 bits. Vai do -128 até o 127.
  • short: inteiro de complemento de dois de 16 bits. Vai do -32768 até o 32767.
  • int: inteiro de complemento de dois de 32 bits. Vai de -231 até 231-1
  • long: inteiro de complemento de dois de 64 bits.
  • float: número de ponto flutuante de 32 bits.
  • double: número de ponto flutuante de 64 bits.
  • boolean: true e false.
  • char: caractere de 16 bits. Tem valor mínimo de '\u0000' (0) e valor máximo '\uffff' (65535).

Além dos 8 tipos de dados primitivos, o Java também dá suporte para string pela Classe java.lang.String. Objeto String são imutáveis. Uma vez que se cria um objeto do tipo String, ele não pode ser alterado (Testei, e parece que isso é mentira) -> (Na realidade não é mentira. Pensei que fosse porque consegui alterar um objeto do tipo String, mas na verdade, "alterar" uma String em java, é criar uma nova String e passar o endereço dessa nova String para a variável).

Obs: byte e short geralmente são utilizados quando economia de memória for importante na aplicação.

  • Valores default:
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object)   null
boolean false

Literais inteiros em diferentes bases

Para representar inteiros binários, utilize 0b.

int binVal = 0b11010; // Número 26 em binário: 11010

Para representar inteiros hexadecimais, utilize 0x.

int hexVal = 0x1a; // Número 26 em hexadecimal: 1a

Literais em ponto flutuante

Você pode utilizar a notação científica "e" para representar literais em ponto flutuante:

double d1 = 123.4;
double d2 = 1.234e2; // Mesmo valor de d1, mas com notação científica

Para escrever um número do tipo float, é necessário colocar F/f no fim.

float f1 = 1.1;  // Type mismatch: cannot convert from double to float
float f2 = 1.1F; // Correct

Unicode scape

Você pode utilizar Unicode scapes para representar símbolos de acentuação:

String sisenor = "S\u00ED Se\u00F1or"; // Sí Señor

Usando underscore em caracteres e literais numéricos

O underscore pode ser utilizado para separar numerais:

long creditCardNumber = 1234_5678_9012_3456L; //1234567890123456

Arrays

Arrays são containers de tamanho fixo que contém objetos do mesmo tipo.

int[] anArray;          // declara o array de inteiros
anArray = new int[10]   // aloca 10 espaços de memória para inteiros

int[] array2 = {1, 2, 3}; //shortcut syntax

Copiando Arrays

Para copiar arrays, utiliza-se o método arraycopy() da classe System. Ele possui o seguinte formato:

public static void arraycopy(
	Object src,   // array to copy from
	int srcPos,   // starting position
	Object dest,  // array to copy to
	int destPso,  // starting position
	int length    // number of array elements to copy
)

O exemplo abaixo demonstra a utilização do método arraycopy:

String[] copyFrom = {
	"Affogato0", "Americano1", "Cappuccino2", "Corretto3", "Cortado4", "Doppio5", "Espresso6", "Frappucino7", "Freddo8", "Lungo9",  "Macchiato10", "Marocchino11", "Ristretto12"
};

String[] copyTo = new String[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);

for(String coffe : copyTo) {
	System.out.println(coffe + " ");
}

A saída será:

Cappuccino2 Corretto3 Cortado4 Doppio5 Espresso6 Frappucino7 Freddo8

O método copyOfRange() da classe java.util.Arrays também pode ser utilizado para fazer a cópia de arrays. A diferença, é que ele criará e retornará o array destino, então não será necessário alocar o espaço do array de destino. A saída será a mesma do anterior.

String[] copyFrom = {
	"Affogato0", "Americano1", "Cappuccino2", "Corretto3", "Cortado4", "Doppio5", "Espresso6", "Frappucino7", "Freddo8", "Lungo9",  "Macchiato10", "Marocchino11", "Ristretto12"
};

String[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9); // copie os elementos de índice 2 até o índice 8 do array copyFrom

for(String coffee : copyTo) {
	System.out.println(coffee + " ");
}

Convertendo um array para String

o Método toString de da classe java.util.Arrays transforma os elementos de uma array em Strings.

System.out.println(java.util.Arrays.toString(copyTo)); // saída: [Cappuccino2, Corretto3, Cortado4, Doppio5, Espresso6, Frappucino7, Freddo8]

Questions

  1. The term "instance variable" is another name for NON-STATIC FIELD.
  2. The term "class variable" is another name for STATIC FIELD.
  3. A local variable stores temporary state; it is declared inside a METHOD.
  4. A variable declared within the opening and closing parenthesis of a method signature is called a PARAMETER.
  5. What are the eight primitive data types supported by the Java programming language? byte, short, int, long, float, double, boolean, char
  6. Character strings are represented by the class java.lang.String.
  7. An ARRAY is a container object that holds a fixed number of values of a single type.

Exercises

  1. Create a small program that defines some fields. Try creating some illegal field names and see what kind of error the compiler produces. Use the naming rules and conventions as a guide.
  2. In the program you created in Exercise 1, try leaving the fields uninitialized and print out their values. Try the same with a local variable and see what kind of compiler errors you can produce. Becoming familiar with common compiler errors will make it easier to recognize bugs in your code.

Check your answers

Operadores

Equals: compara dois objetos se o conteúdo de dois objetos é o mesmo, ainda que sejam instâncias diferentes. == : compara dois tipos primitivos, e também pode ser usado para comparar se dois objetos são a mesma instancia.

  • essa explicação não está muito boa, melhor procurar outra.
Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Questions

  1. Consider the following code snippet. arrayOfInts[j] > arrayOfInts[j+1] Which operators does the code contain? GREATER THAN (>), PLUS (+)
  2. Consider the following code snippet.
int i = 10;
int n = i++%5;

What are the values of i and n after the code is executed? i = 11, n = 0 What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))? i = 11, n = 1

  1. To invert the value of a boolean, which operator would you use? !
  2. Which operator is used to compare two values, = or == ? ==
  3. Explain the following code sample: result = someCondition ? value1 : value2; It is an if: if somecondition, result will receive value1, else, it will receive value2.

Exercises

  1. In the following program, explain why the value "6" is printed twice in a row:
class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        System.out.println(i);    // "4"
        ++i;                     
        System.out.println(i);    // "5"
        System.out.println(++i);  // "6"
        System.out.println(i++);  // "6"
        System.out.println(i);    // "7"
    }
}

O código System.out.println(++i) avalia o valor já incrementado (5+1), já o código System.out.println(i++); avalia para o valor atual (6) e depois incrementa (7).

Check your answers

Expressões, Statements e Blocos

  • Expressões: Construção feita de variáveis, operadores e invocação de métodos.
  • Statements (instruções): o equivalente às sentenças em linguagem natural. Termina sempre com um semicolon (;).
  • Blocos: Grupos de statements separados por chaves {}.

Questions

  1. Operators may be used in building EXPRESSIONS, which compute values.
  2. Expressions are the core components of STATEMENTS.
  3. Statements may be grouped into BLOCKS.
  4. The following code snippet is an example of a COMPOUND expression. 1 * 2 * 3
  5. Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a SEMICOLON (;).
  6. A block is a group of zero or more statements between balanced BRACES {} and can be used anywhere a single statement is allowed.

Exercises Identify the following kinds of expression statements:

- aValue = 8933.234;                    // ASSIGNMENT STATEMENT
- aValue++;                             // INCREMENT STATEMENT
- System.out.println("Hello World!");   // METHOD INVOCATION STATEMENT
- Bicycle myBike = new Bicycle();       // OBJECT CREATION STATEMENT

Check your answers

Expressões de Controle de Fluxo

Instrução Switch

O comando switch utiliza o break para sair do fluxo. Se o break não for usado, ele poderá cair em fall through:

public static void main(String[] args){

	Arraylist<String> futureMonths = new Arraylist<String>();

	int monthNumber = 8;

	switch(monthNumber){
		case 1: futureMonths.add("january");
		case 2: futureMonths.add("february");
		case 3: futureMonths.add("march");
		case 4: futureMonths.add("april");
		case 5: futureMonths.add("may");
		case 6: futureMonths.add("june");
		case 7: futureMonths.add("july");
		case 8: futureMonths.add("august");
		case 9: futureMonths.add("september");
		case 10: futureMonths.add("october");
		case 11: futureMonths.add("november");
		case 12: futureMonths.add("december");
			break;
		default: 
			break;
	}

	if(futureMonths.isEmpty()){
		System.out.println("Número de mês inválido\n");
	} else {
		for (String month : futureMonths){
			System.out.println(month); // mostrará august e todos os meses após august
		}
	}
}

A saída será:

august
september
october
november
december

Instruções Branching

O comando break pode ser usado para para controles de fluxo rotulados (labeled) ou não-rotulados (unlabeled).

Observe o exemplo que faz parar o controle de fluxo rotulado "search":

public class BreakWithLabelDemo {
	
	public static void main(String[] args){
		
		int[][] intNumbers = {
			{1,2,3},
			{4,5,6},
			{7,8,9}
		};

		int num = -1, i = -1, j = -1;

		search:
		for(i = 0; i < intNumbers.length; i++){
			for(j = 0; j < intNumbers[i].length; j++){
				if(intNumbers[i][j] == 5){
					num = intNumbers[i][j]; 
					break search;
				}
			}
		}

		System.out.println("Found " + num + " in position " + i + ", " + j);

	}

}

Questions

  1. The most basic control flow statement supported by the Java programming language is the IF-THEN statement.
  2. The SWITCH statement allows for any number of possible execution paths.
  3. The DO-WHILE statement is similar to the while statement, but evaluates its expression at the BOTTOM of the loop.
  4. How do you write an infinite loop using the for statement?
for(;;){}
  1. How do you write an infinite loop using the while statement?
while(true){}

Exercises

  1. Consider the following code snippet.
if (aNumber >= 0)
    if (aNumber == 0)
        System.out.println("first string");
else System.out.println("second string");
System.out.println("third string");

a. What output do you think the code will produce if aNumber is 3?

second string
third string

The else clause is attached to the second if (probably if-then-else is just one statement).

b. Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is; in other words, what is the control flow for the code snippet? c. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand. d. Use braces, { and }, to further clarify the code.

if (aNumber >= 0){
	if (aNumber == 0){
        System.out.println("first string");
	} else {
		System.out.println("second string");
	} 
} 
System.out.println("third string");

Check your answers

Declarando classes

MyClass é uma subclasse de MySuperClass que implementa YourInterface

class MyClass extends MySuperClass implements YourInterface{
	// field, constructor, and
	// method declarations
}

As declarações de classes possuem o seguinte formato:

<modificador> class <NomeDaClasse> extends <NomeDaSuperClasse> implements <NomeDaInterface> {}

Questões

  1. Consider the following class:
public class IdentifyMyParts {
    public static int x = 7; 
    public int y = 3; 
}
  • What are the class variables? x

  • What are the instance variables? y

  • What is the output from the following code:

IdentifyMyParts a = new IdentifyMyParts();
IdentifyMyParts b = new IdentifyMyParts();
a.y = 5;
b.y = 6;
a.x = 1;
b.x = 2;
System.out.println("a.y = " + a.y);  // 5
System.out.println("b.y = " + b.y);  // 6
System.out.println("a.x = " + a.x);  // 2
System.out.println("b.x = " + b.x);  // 2
System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x); // 2
  1. What's wrong with the following program?
public class SomethingIsWrong {
    public static void main(String[] args) {
        Rectangle myRect;
        myRect.width = 40;
        myRect.height = 50;
        System.out.println("myRect's area is " + myRect.area());
    }
}

myRect must to be initialized.

String[] students = new String[10];
String studentName = "Peter Parker";
students[0] = studentName;
studentName = null;

The following code creates one array and one string object. How many references to those objects exist after the code executes? In the third line, 2 (students[0] and studentName), but in the 4th line, just a reference to "Peter Smith" in students[0].

Is either object eligible for garbage collection? Just for studentName

  1. How does a program destroy an object that it creates? Não destrói. Apenas deixa a referência nula para os objetos.
class OuterClass{

	class InnerClass{
		...
	}

	static class StaticNestedClass{
		...
	}

}

Tipos:

  • Classe aninhada não-estática (Inner class): Possuem acesso a outros membros da classe exterior mesmo que sejam privados.
  • Classe aninhada estática: Não possuem acesso ao membros da classe exterior.

Inner class

Para instanciar uma Inner Class, deve-se instanciar primeiro sua classe externa.

OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Questions

  1. The program Problem.java doesn't compile. What do you need to do to make it compile? Why?
public class Problem {
	String s;
	static class Inner {
		void testMethod() {
		   s = "Set from Inner";
		}
	}
}

A classe aninhada estática Inner não pode acessar os atributo s da classe externa. Só poderia acessar se Inner não fosse estática.

Tipo de variável que consiste de um conjunto fixo de constantes.

enum TamanhoCafe{GRANDE, GIGANTE, GIGANTESCO};
TamanhoCafe tc = TamanhoCafe.GRANDE;

Enums podem ser declaradas em uma classe separada ou como membro de uma classe, mas nunca em uma função.

Enums estendem implicitamente java.lang.Enum.

Enums não podem estender de outra classe. (Pois classes só podem ter uma classe pai)

Declarando construtores de uma Enum

enum TamanhoCafe{
    GRANDE(8), GIGANTE(10), GIGANTESCO(16);

    private int valor;

    TamanhoCafe(int valor){
        this.valor = valor;
    }

    public int getValor(){
        return valor;
    }
}

java.lang.Enum possui o método estático values() que retorna um array com todos os valores do Enum.

Question

  1. True or false: an Enum type can be a subclass of java.lang.String FALSE