Conversione di tipi in Java

Mattepuffo's logo
Conversione di tipi in Java

Conversione di tipi in Java

Uno dei principali problemi che si trova ad affrontare nella programmazione è che noi abbiamo (ad esempio) una stinga e lo vogliamo trasformare un un numero, o viceversa.

Ci serve quindi sapere come fare le conversioni dei tipi.

Soprattutto per i newbie questo è un problema molto frrequente.

Vediamo qualche esempio tenendo a mente quali sono i tipi primitivi in Java (numerici e non) e che String non è un tipo primitivo.

Da int a String:

int i = 7;

String str = Integer.toString(i);

oppure

String str = "" + i

Da double a String:

String str = Double.toString(i);

 

Da long a String:

String str = Long.toString(i);

Da float a String:

String str = Float.toString(i);

Da String a int

str = "7";

int i = Integer.valueOf(str).intValue();

oppure

int i = Integer.parseInt(str);

Da String a double

Double d = Double.valueOf(str).doubleValue();

Da String a float

Float f = Float.valueOf(str).floatValue();

Da String a long

long l = Long.valueOf(str).longValue();

oppure

Long l = Long.parseLong(str);

Da int a char

int pesi = 7;

(char) (pesi);

Da char a String

String s = String.valueOf('c');

Da int a boolean

b = (i != 0);

// ex : 42 != 0 --> true

Da boolean a int

i = (b)?1:0;

// true --> 1

Da decimal a binary

int i = 7;

String bin = Integer.toBinaryString(i);

Da decimal a hexadecimal

int i = 7;

String hexstr = Integer.toString(i, 16);

oppure

String hexstr = Integer.toHexString(i); 

oppure (with leading zeroes and uppercase)

public class Hex {

public static void main(String args[]){

int i = 7;

System.out.print

(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());

}

}

Da hexadecimal(String) a int

int i = Integer.valueOf("B8DA3", 16).intValue();

oppure

int i = Integer.parseInt("B8DA3", 16);

Da int a ASCII code (byte)

char c = 'A';

int i = (int) c; // i == 65 DECIMAL

Estrazione ASCII da String

String test = "ABCD";

for (

int i = 0; i < test.length(); ++i ) {

char c = test.charAt( i );

int j = (int) c; System.out.println(j);

}

 

Qua un mini articolo sul casting in Java.


Condividi

Commentami!