Casting de tipo Java

Estamos discutindo a conversão de tipo Java com exemplos , a fim de atender às necessidades dos alunos.

Cast de tipo Java

Casting de tipo Java

Quando um valor de um tipo de dados primitivo é atribuído a outro tipo de dados primitivo, ele é chamado de conversão de tipo .

Existem dois tipos de conversão em Java:

  • Widening Casting (automaticamente) – convertendo um tipo de dados de tamanho menor em um tamanho maior. (Byte -> short -> char -> int -> long -> float -> double)
  • Narrowing Casting (manualmente) – convertendo um tipo de dados de tamanho maior em um tamanho menor. (Double -> float -> long -> int -> char -> short -> byte)


Alargamento Elenco

O alargamento da fundição é feito automaticamente ao passar de um tamanho pequeno para um tamanho grande:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
public static void main(String[] args) {
int my_Int_value = 20;
double my_Double = my_Int_value; // Automatic casting: int to double System.out.println(my_Int_value);
System.out.println(my_Double);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
int my_Int_ample = 17;
long my_long_mrx = my_Int_ample; // Widening casting is applied here which converts int to long
System.out.println("Integer value: "+my_Int_ample);
System.out.println("Long value: "+my_long_mrx);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Estreitando o elenco

A conversão de restrição é feita manualmente colocando o tipo entre parênteses antes do valor:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
public static void main(String[] args) {
double my_Double_value = 126.7d;
byte my_Byte_value = (byte) my_Double_value; // Explicit casting: double to byte System.out.println("Actual Double Value : "+my_Double_value);
System.out.println("After Narrowing casting modified value is: "+my_Byte_value);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos converter o valor double(8 byte) para float(4 byte):

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
double my_Double_value = 437.7241d;
float my_float_value = (float) my_Double_value; // Explicit casting: double to float
System.out.println("Actual Double Value : "+my_Double_value);
System.out.println("After Narrowing casting float value is: "+my_float_value);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone