gianluca.aguzzi@unibo.it
angelo.filaseta@unibo.it
Questo materiale è ampiamente basato su quello realizzato dai Prof. Mirko Viroli e Roberto Casadei, che ringrazio.
Ogni errore riscontratovi è esclusiva responsabilità degli autori di questo documento.
java
] + JCL) + strumenti di sviluppo (javac
, …)this
main
in classe pubblicajavac
ed esecuzione con java
Competenza attuale attesa: costruzione di semplici classi; loro esercizio mediante programmi; compilazione ed esecuzione di programmi
JShell
jshell
boolean
, byte
, short
, int
, long
, float
, double
, char
Object
, String
, Integer
, ArrayList
, JFrame
, $\ldots$boolean[]
, byte[]
, String[]
, String[][]
, $\ldots$Nome del tipo: boolean
Valori: true
, false
Operatori unari: !
(not)
Operatori binari: &
(and), |
(or), ^
(xor), &&
(and-c), ||
(or-c)
&&
e ||
valutano il secondo argomento solo se necessario (short-circuiting)false && X
restituisce false
senza valutare X
true || X
restituisce true
senza valutare X
Operatori di confronto numerici: >
, <
, >=
, <=
Operatori di uguaglianza (su tutti i tipi): ==
, !=
10 == 20 // false
new Object() == new Object() // true o false ???
?:
b ? v1 : v2
restituisce v1
se b
è vero, v2
altrimentiType name | Size (bits) | Minimum | Maximum |
---|---|---|---|
char | 16 | \u0000 ($0$) |
\uFFFF ($2^{16}-1$) |
byte | 8 | $-128$ | $128$ |
short | 16 | $-2^{15}$ | $2^{15}-1$ |
int | 32 | $-2^{31}$ | $2^{31}-1$ |
long | 64 | $-2^{63}$ | $2^{63}-1$ |
float | 32 | IEEE754 | IEEE754 |
double | 64 | IEEE754 | IEEE754 |
byte
, short
, int
, long
+
, -
, *
, /
(con resto), %
(resto), +
e -
anche unari&
(and), |
(or), ^
(xor), ~
(complement)>>
(dx con segno), <<
(sx), >>>
(dx senza segno)200
), ottale (0310
), esadecimale (0xC8
)int
, per avere un long
va aggiunta una L
(15L
)byte
e short
, non molto più efficienti di int
int
più efficiente di long
float
, double
+
, -
, *
, /
(con resto), %
(resto), +
e -
anche unari-128.345
), o scientifica (-1.2835E+2
)double
, per avere un float
va aggiunta una F
5 // int
5. // double
5d // double
5f // float
float
, anche se più efficiente di double
public class Try {
public static void main(String[] s) {
System.out.println(10 + 20); // 30
System.out.println(010 + 020); // 24
System.out.println(0xFFFFFFFF); // -1
System.out.println(0x7FFFFFFF); // 2147483647
System.out.println(0x80000000); // -2147483648
System.out.println(0x80000000 - 1); // 2147483647
System.out.println(2147483647 + 1); // -2147483648
System.out.println(2147483647L + 1); // 2147483648
System.out.println((0x0F0F | 0xF0F0) == 0xFFFF); // true
System.out.println((0x0F0F & 0xF0F0) == 0); // true
System.out.println((0x0F0F << 4) == 0xF0F0); // true
System.out.println((0x0F0F >> 4) == 0x00F0); // true
System.out.println(~0x0F0F == 0xFFFFF0F0); // true
System.out.println(10 / 3); // 3
System.out.println(10 % 3); // 1
System.out.println(3.5 / 51 * 51); // 3.5000000000000004
System.out.println(3.5f / 51 * 51);// 3.5000002
}
}
(tipo)valore
boolean
(int)3.33
, ((double)10)/3
, (short)100
byte
$\rightarrow$short
$\rightarrow$int
$\rightarrow$long
$\rightarrow$float
$\rightarrow$double
long l=100;
diventa long l=(long)100;
10.1+10
diventa 10.1+(double)10
'a'
, 'z'
, 'A'
, '='
'A'
), 66 ('B'
)'\n'
, '\\'
, '\0'
'\u6C34'
class TryChars {
public static void main(String[] s) {
System.out.println("lettera 'a' e a capo" + 'a');
System.out.println("acqua (cinese) e a capo " + '\u6C34');
System.out.println("backslash e a capo" + '\\');
System.out.print("a capo " + '\n');
System.out.print("a capo " + (char) 10);
}
}
new
)length
) esplicita e accessibile (non modificabile)ArrayIndexOutOfBoundsException
)int[] ar1 = new int[]{10,20,30,40,50,7,8,9};
var ar2 = new int[]{10,20,30}; // variante con `var`
int[] ar3 = {10,20,30}; // variante senza `new`
int[] ar4 = new int[200]; // new int[]{0,0,...,0}
int[][] m = new int[][]{ new int[]{...}, ... };
int[][] m2 = new int[200][200];
ar4.length // 200 (lunghezza)
ar4[23] // espressione per leggere 24-esimo elemento
ar4[23] = 10; // assegnamento del 24-esimo elemento
m[1][2] = 10; // assegnamento riga 2 colonna 3
public class UseArrays {
public static void main(String[] s) {
int[] a = new int[] { 10, 20, 30 }; // int[] aa = {10,20,30};
System.out.println("a: " + a[0] + " " + a[1] + " " + a[2]);
System.out.println(a); // [I@1794d431
System.out.println(java.util.Arrays.toString(a)); // [10, 20, 30]
double[] b = new double[] { 10.1, 10.2 };
b[1] = 10.21;
String[] c = new String[] { "10", "20", "3" + "0" };
System.out.println("c.length: " + c.length); // 3
boolean[] d = new boolean[10000];
System.out.println("d[5000]: " + d[5000]); // false
int[][] e = new int[5][10]; // matrice 5x10 di zeri
System.out.println("e.length: " + e.length); // 5
int[][] f = new int[][] { // int[][] f = {{11,12,13,14},{21,22,23,24},....};
new int[] { 11, 12, 13, 14 },
new int[] { 21, 22, 23, 24 },
new int[] { 31, 32, 33, 34 } };
System.out.println("f.length: " + f.length); // 3
System.out.println("f[0].length: " + f[0].length); // 4
System.out.println("f[1][2]: " + f[1][2]); // 23
System.out.println("ERR: f[1][4]: " + f[1][4]); // ArrayIndexOutOfBoundsException
}
}
Object[] ar = new Object[]{ new Object(), new Object() };
Object[] ar2 = new Object[200];
null
new
quindi si crea un solo oggetto, l’array stessoint x; // dichiarazione
int x=5; var x=5; // dichiarazione e inizializzazione (assegnamento)
x=5; // assegnamento
return 5;
meth(3,4);
obj.meth(3);
Cls.meth(4);
for
, while
, do
, switch
, if
, break
, continue
boolean
(cf. strong typing)
if
, for
, while
e do
è un boolean
boolean b = 1; // ERROR: incompatible types: int cannot be converted to boolean
boolean b = (boolean) 1; // incompatible types: int cannot be converted to boolean
if(1){ /* ... */ } // ERROR: incompatible types: int cannot be converted to boolean
static
public
): <nome-classe>.<nome-metodo>(...)
<nome-metodo>(...)
java.lang.Math
java.lang.Math
import java.util.Arrays;
public class UseMath { // E' una utility class
// Metodo statico, crea e torna un array di double
// lungo size, contenente numeri random 0<=x<=1
static double[] randomValues(int size){
double[] d = new double[size];
for (int i = 0; i < size; i++){
d[i] = Math.random();
}
return d;
}
public static void main(String[] args) {
System.out.println(Math.random());
// Ricorda: toString è un metodo statico della classe Arrays
System.out.println(Arrays.toString(randomValues(10)));
for (double x = 0.0; x <= Math.PI * 2; x = x + Math.PI / 10){
System.out.println("x = " + x + "\t sin(x) = " + Math.sin(x));
}
}
}
Costruire una funzione che dato un array ne produce in uscita uno della stessa lunghezza, ma invertendo il primo elemento con l’ultimo, il secondo col penultimo, etc..
import java.util.Arrays; // Classe con funzioni di utilità
class Reverse {
static int[] reverse(int[] array) { // funzione reverse
int[] out = new int[array.length]; // creo array per lunghezza
for (int i = 0; i < out.length; i++) { // for con var. interna
out[i] = array[out.length - 1 - i];
}
return out;
}
// l'uso di public qui sotto è necessario per il main
public static void main(String[] s) { // prova funz. di reverse
int[] a = new int[] { 10, 20, 30, 40 };
int[] b = reverse(a);
System.out.println(Arrays.toString(a)); // [10, 20, 30, 40]
System.out.println(Arrays.toString(b)); // [40, 30, 20, 10]
}
}
for
for(int v: array){ /* uso di v */ }
var
:for(var v: array){ /* uso di v */ }
array
è una espressione che restituisce un int[]
for
, v
vale via via ogni elemento dell’arrayv
in array
esegui il corpo”class Sum {
public static int sum(int[] array) { // soluzione standard
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum = sum + array[i];
}
return sum;
}
public static int sum2(int[] array) { // soluzione con for-each
int sum = 0;
for (int elem : array) { // per ogni elem in array..
sum = sum + elem;
}
return sum;
}
public static void main(String[] s) {
int res = sum2(new int[] { 10, 20, 30, 40 });
System.out.println("Somma : " + res);
}
}
main
class SumMain {
public static int sum(int[] array) { // soluzione con for-each
int sum = 0;
for (int elem : array) { // per ogni elem in array..
sum = sum + elem;
}
return sum;
}
// da invocare con: java SumMain 10 20 30 40
public static void main(String[] args) {
int[] input = new int[args.length];
for (int i = 0; i < input.length; i++){
input[i] = Integer.parseInt(args[i]);
}
int res = sum(input);
System.out.println("Somma : " + res);
}
}
GuessMyNumberApp
Realizzare una applicazione che, scelto un numero a caso compreso fra 1 a 100, chieda all’utente di indovinarlo, dandogli $10$ tentativi e indicando ogni volta se il numero in input è maggiore o minore di quello scelto all’inizio
main
for
)java.io.Console#readLine
usabile per leggere input da tastiera (console ottenibile da System.console()
, se associata alla JVM in uso)java.lang.Integer.parseInt(String)
usabile per convertire una stringa in un numerojava.util.Random.nextInt
usabile per ottenere un numero randomGuessMyNumberApp
import java.util.Random;
public class GuessMyNumberApp {
public static void main(String[] args) {
int number = new Random().nextInt(99) + 1;
for (int i = 1; i <= 10; i++){
System.out.println("Attempt no. "+i);
System.out.println("Insert your guess.. ");
int guess = Integer.parseInt(System.console().readLine());
if (guess == number){
System.out.println("You won!!");
return;
} else if (guess > number){
System.out.println("Your guess is greater, try again..");
} else {
System.out.println("Your guess is lower, try again..");
}
}
}
}
Class
, clas
, bolean
for(int i=0,i<10,i++){..}
int a = true;
int a = 5 + false;
if (5) ..
string
, system
, Sistem
(cf. Errore cannot find symbol)