1 Java
1 Java
Fernando Silva
2024/2025
(Setembro de 2022)
(Setembro de 2024)
(Setembro de 2024)
Segurança e Robustez
▶ verificação de tipos estática
▶ gestão automática de memória (alocação de memória, reclamação de
memória, etc)
▶ exceções para tratar erros em tempo de execução
p u b l i c c l a s s HelloWorld {
p u b l i c s t a t i c v o i d main( String [] args) {
System .out. println (" Hello World !");
}
}
/* ***************************************************
HelloWorld - um primeiro programa em Java
**************************************************** */
p u b l i c c l a s s HelloWorld {
p u b l i c s t a t i c v o i d main( String [] args) {
System .out. println (" Hello World !"); // A minha primeira instrução
}
}
int i = 2;
float f = 3.192;
boolean b = true ;
char c = ’a’;
Inteiros
byte 8 bits [−27 : 27 − 1]
short 16 bits [−215 : 215 − 1]
int 32 bits [−231 : 231 − 1]
long 64 bits [−263 : 263 − 1]
Outros
boolean depende JVM valor booleano (true ou false)
char 16 bits ISO Unicode char set
// Casting explícito
int i1 = ( i n t )d1; // i1 fica com o valor de 3
int i2 = ( i n t )d2; // i2 fica com o valor de 3
double d3 = ( double )i2; // d3 fica com o valor de 3.0
// Casting implícito
int i3 = 42;
double d4 = i3; // d4 fica com o valor de 42.0
int i4 = d4; // erro: "possible loss of precision"
// Conversão entre char e int
char ch1 = ’A’;
int i5 = ch1; // i5 fica com 65 (código ascii de ’A’)
char ch2 = 66; // ch2 fica com ’B’ (código ASCII 66)
// Exemplo de tipos incompatíveis: boolean e int
boolean b1 = i1; // erro: "incompatible types"
// virgula flutuante
f l o a t largestFloat = F l o a t . MAX_VALUE ;
double largestDouble = Double. MAX_VALUE ;
// mostrar limites
System .out. println (" Largest byte value : " + largestByte );
System .out. println (" Largest short value : " + largestShort );
System .out. println (" Largest integer value : " + largestInteger );
System .out. println (" Largest long value : " + largestLong );
Aritméticos: Lógicos:
+ adição - subtracção
! NOT lógico
* multiplicação / divisão
&& AND lógico
% módulo ++ incremento
|| OR lógico
-- decremento
Bits:
~ NOT binário & AND binário
| OR binário ^ XOR binário
<< shift binário esquerda >> shift binário direita
Relacionais ou de comparação:
== igualdade != diferente
< menor que <= menor ou igual que
> maior que >= maior ou igual que
int i1 = 3;
double d4 = i1 /2; // dá 1.0 e não 1.5 (int/int)
double d5 = 3;
int i2 = d5 /2; // resultado da divisão é 1.5 mas depois
// dá erro "possible loss of precision"
// (double/int = double)
operadores modifica-e-atribui:
▶ variavel += valor; ⇐⇒ variavel = variavel + valor;
▶ variavel -= valor; ⇐⇒ variavel = variavel - valor;
▶ variavel *= valor; ⇐⇒ variavel = variavel * valor;
▶ variavel /= valor; ⇐⇒ variavel = variavel / valor;
Exemplos:
▶ x -= 1; ⇐⇒ x--; ⇐⇒ x= x-1;
▶ y /= 2; ⇐⇒ y = y/2;
▶ x *= y+2;⇐⇒ x= x*(y+2);
Exemplo de uso:
c l a s s TestWhile {
p u b l i c s t a t i c boolean isPrime ( i n t n) {
i n t divisor = 2; // init. first possible divisor
w h i l e ( divisor * divisor <= n) { // condition to stop the cicle
i f ( (n % divisor ) == 0 ) // if divisible
return f a l s e ; // returns false (not prime)
divisor ++; // updates to next divisor
}
return true ; // cicle ended, n has no divisors
} // thus returns true
}
Exemplo de uso:
c l a s s TestFor {
p u b l i c s t a t i c v o i d main( String [] args) {
System .out. println (" isPrime (19) = " + isPrime (19));
}
p u b l i c s t a t i c boolean isPrime ( i n t n) {
f o r ( i n t divisor = 2; divisor < n/2; divisor ++)
i f ( (n % divisor ) == 0 )
return f a l s e ;
return true ;
}
}
Exemplo de uso:
c l a s s TestDoWhile {
p u b l i c s t a t i c v o i d main( String [] args) {
System .out. println (" isPrime (19) = " + isPrime (19));
}
p u b l i c s t a t i c boolean isPrime ( i n t n) {
i n t divisor = 2;
do {
i f ( (n % divisor ) == 0 )
return f a l s e ;
divisor ++;
} w h i l e ( divisor * divisor <= n);
return true ;
}
}
(fonte:https://pt.wikipedia.org/wiki/Crivo_de_Eratostenes)
Fernando Silva (DCC-FCUP) Introdução à Linguagem Java 2024/2025 29 / 66
Instruções de controle de fluxo em ciclos
Válidas para as instruções de ciclo for, while ou do-while.
break sai do ciclo mais interno onde está.
Continua a execução na linha a seguir ao ciclo
c l a s s TestBreak {
p u b l i c s t a t i c v o i d main( String [] args) {
f o r ( i n t i=1; i <=2; i++) {
f o r ( i n t j=1; j <=10; j++) {
i f (j == 3) break ;
// Linha seguinte só será executada quando j < 3
System .out. println (" ciclo j = " + j + " | i = " + i);
}
System .out. println (" ciclo i = " + i);
}
}
}
ciclo j = 1 | i = 1
ciclo j = 2 | i = 1
ciclo i = 1
ciclo j = 1 | i = 2
ciclo j = 2 | i = 2
ciclo i = 2
[ antes ] i = 1
[ depois ] i = 1
[ antes ] i = 2
[ depois ] i = 2
[ antes ] i = 3
[ antes ] i = 4
c l a s s TestPoint {
p u b l i c s t a t i c v o i d main( String [] args) {
Point p1 = new Point (); // Criação de um objecto do tipo Point
p1.x = 42; // Atribui um valor ao atributo x
System .out. println (p1.x); // Escreve 42
c l a s s TestPoint {
p u b l i c s t a t i c v o i d main( String [] args) {
c l a s s TestPoint {
p u b l i c s t a t i c v o i d main( String [] args) {
Point p = new Point (42 , 13);
p.show (); // Escreve "(42,13)"
}
}
c l a s s TestPoint {
p u b l i c s t a t i c v o i d main( String [] args) {
Point p = new Point (); // Erro: não existe construtor sem argumentos
} // Apenas existe um que recebe int, int
}
c l a s s TestPoint {
p u b l i c s t a t i c v o i d main( String [] args) {
Point p1 = new Point (); // p1 fica com (0,0)
Point p2 = new Point (42 ,13); // p2 fica com (42,13)
}
}
c l a s s TestPoint {
p u b l i c s t a t i c v o i d main( String [] args) {
Point p1 = new Point (1 ,1); // p1 fica com (1,1)
Point p2 = new Point (1 ,1); // p2 fica com (1,1)
System .out. println (p1 == p2 ); // escreve false, porque são referências
} // para objectos diferentes, embora tenham
} // conteúdos iguais
c l a s s TestPoint {
p u b l i c s t a t i c v o i d main( String [] args) {
// É possível chamar método estático mesmo sem objectos criados
Point . showNumPoints (); // Escreve npoints = 0
Point p1 = new Point ();
Point . showNumPoints (); // Escreve npoints = 1
Point p2 = new Point ();
Point . showNumPoints (); // Escreve npoints = 2
}
}
s t a t i c v o i d showX () {
// Erro: non-static variable x cannot be referenced from a static context
System .out. println (x);
}
}
// corpo do método
}
qualificadores:
▶ public pode ser invocado por qualquer um
▶ protected pode ser invocado apenas por métodos do mesmo package
ou subclasses.
▶ private pode ser invocado apenas pelos métodos da mesma subclasse.
▶ por defeito o método é friendly, pode ser invocado por objectos de
classes do mesmo package.
API: https://docs.oracle.com/javase/9/docs/api/java/lang/String.html
uma string é uma sequência de caracteres
em Java não são um tipo básico, mas sim instâncias da classe String
não se comportam como arrays, pois são imutáveis
(uma vez criadas não se podem modificar)
criação/inicialização invocando métodos construtores:
▶ String c1 = new String("CC");
criação simplificada:
▶ String c2 = "1007";
operador de concatenação:
▶ String c3 = c1 + c2 + " rocks";
o valor que fica em c3 é:
▶ "CC1007 rocks";
Fernando Silva (DCC-FCUP) Introdução à Linguagem Java 2024/2025 45 / 66
Strings
As strings podem ser vistas como vectores de caracteres (mas não são
do tipo array do Java). Ex: String s = "algoritmos";
índice 0 1 2 3 4 5 6 7 8 9
caracter ’a’ ’l’ ’g’ ’o’ ’r’ ’i’ ’t’ ’m’ ’o’ ’s’
podemos ler caracteres individuais mas não alterá-los
String s = " algoritmos ";
System .out. println (s. charAt (6)); // ’t’
mini-exercício: encontrarIntrodução
Fernando Silva (DCC-FCUP) um método
à Linguagemna
JavaAPI que verifique se um
2024/2025 48 / 66
Arrays
Para poder usar-se uma classe de um package que não seja do java.lang,
deve usar-se a palavra-chave import. Exemplo:
import java.util.Scanner; //importar a classe Scanner
output:
[ I@75b84c92
[2 ,3 ,5 ,7 ,11 ,13]
j=0
Exemplo:
c l a s s TestMatrixVectorProduct {
p u b l i c s t a t i c v o i d main( String [] args) {
i n t [][] a = {{1 ,2 ,3} ,{4 ,5 ,6}};
i n t [] u = {7 ,8 ,9};
i n t [] v = matrixVectorMult (a,u);
As classes mais importantes que lidam com I/O no Java estão definidas
nas packages java.io e java.lang
a leitura e escrita faz-se através de canais (streams) que podem
representar um qualquer periférico físico.
a classe System, definida em java.lang, inclui muitas definições de
sistema, nomeadamente 3 canais: in, out, e err.
▶ InputStream System.in – objecto que representa o standard input
stream (por omissão é o teclado);
▶ PrintStream System.out – objecto que representa o standard
output stream (por defeito a consola);
▶ PrintStream System.err – objecto que representa o standard error
stream (consola).
▶ ou de um ficheiro
File file= new File( fileName );
Scanner fileIn = new Scanner (file );
p u b l i c c l a s s TestScannerFromString {
p u b l i c s t a t i c v o i d main ( String [] args) {
Scanner strIn = new Scanner ("1 - 2 - 3 - 4 - 5");
strIn . strIn . useDelimiter (" - ");
i n t n;
w h i l e ( strIn . hasNextInt () ) {
n = strIn . nextInt ();
System .out. println (n);
}
}
}
c l a s s TestScannerFromStdIn {
p u b l i c s t a t i c v o i d main ( String [] args) {
Scanner stdIn = new Scanner ( System .in );
f o r ( i n t i = 0; i < n ; i++ ) {
System .out. println (" input name[ space ]age: ");
names [i] = stdIn .next ();
ages[i] = stdIn . nextInt ();
}
f o r ( i n t i = 0; i < n ; i++ )
System .out. println ("name:"+ names [i]+" age: "+ages[i]);
}
} Fernando Silva (DCC-FCUP) Introdução à Linguagem Java 2024/2025 60 / 66
Scanner: leitura a partir de um ficheiro
import java.io.File;
import java.io. IOException ;
import java.util. Scanner ;
c l a s s TestScannerFromFile {
p u b l i c s t a t i c v o i d main ( String args []) {
try {
File file = new File("./ example .txt");
Scanner fileIn = new Scanner (file );
w h i l e ( fileIn . hasNextLine () )
System .out. println ( fileIn . nextLine ());
}
catch ( IOException e) { // Mais sobre a instrução catch noutra aula
System .out. println (" Error Opening File");
}
}
}