Widening and Narrowing Conversion

 Widening conversion:


byte b = 126;
short s = 1000;
char c = 65;
int i = 2_147_483_647;
long l;
float f = 3.14F;
double d;

s = b;
l = i;
f = i;
System.out.println("i: " + i + " f: " + f); // informasiya itkisi bash verir
l = i + 1; // overflow bash verir
System.out.println("i: " + i + " l: " + l);
System.out.println();
l = 987_654_123_456_789L;
f = l; // informasiya itkisi bash verir
System.out.println("l: " + l + " f: " + f);


Narrowing conversion:


Java avtomatik olaraq narrowing operationu etmir.

float f = 3.14; // compile time error
int i = 5L; // compile time error

To solve it we must use casting:

float f = (float) 3.14;
int i = (int) 5L;
long l1 = 5;
int i1 = (int) l1; // informasiya itmir

long l2 = 100_000_000_000L;
int i2 = (int) l2; // informasiya itir

double d1 = 123.123456789123;
float f1 = (float) d1; // informasiya itir;

double d2 = 3.14;
int i3 = (int) d2; // 0.14 itir

char c1 = (char) -65; // problem



Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class