Java - 13 | Type casting in Java | Implicit and Explicit Type casting
The process of converting one data type to another is called casting.
Casting is often necessary when a function returns a data in different form than what we need.
Under certain circumstances Type conversion can be carried out automatically, in other cases it must be "forced" manually (explicitly).
The storage size of the types while casting is very important otherwise the data loss will occur.
For example, suppose we cast a long to an int. A long is a 64-bit value and an int is a 32-bit value. When casting a long to an int, the compiler truncates the upper 32 bits of the long value so as to fit into the 32-bit int.
If the upper 32 bits of the long contain any useful information, then data loss will occur.
In some cases, the data type of the expression is changed automatically to the variable's data type.
For example, suppose that i is an integer variable declared as follows:
int i = 10 ;
Even though d is a variable of type double, the following assignment is valid:
double d = i *10; // valid, (i*10) is converted to type double
Java changes (i*10) from int to double, and then assigns it to d.
This conversion does not cause any loss of information because the double data type is 64 bits wide and thus is wider than the int data type that has 32 bits. This is called a widening conversion because a narrower type is converted to a wider type, and it takes place implicitly.
some more examples of when widening conversions occur:
short s = 10;
int num= s;
float f = 10.5f;
double d = f;
Assigning a value of type double to an int causes a compilation error:
double d = 100.5;
int i = d; // error!
Java does not allow this assignment because a double can hold a larger range of values than an int, and it could result in a loss of data.
To allow this type of assignment, it is necessary for the programmer to force a conversion from double to int using a cast.
For example, a cast is used here to force a conversion of the variable d to type int and then assign it to i:
int i = (int) d; //
i = 100
Note: The above assignment truncates (not rounds) the fractional part so that it assigns 100 to i.
Automatic Conversion:
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment.
Thus we can safely assign:
byte ---short --- int --- long --- float --- double.
Explicit Conversion (Casting): we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost.
To force such a conversion we must carry out an explicit conversion (assuming that the long integer will fit into a standard integer). This is done using a process known as a type cast
myInteger = (int) myLongInteger
This tells the compiler that the type of myLongInteger must be temporarily changed to an int when the given assignment statement is processed. Thus, the cast only lasts for the duration of the assignment.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Java - 13 | Type casting in Java | Implicit and Explicit Type casting», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.