Change class type java

Type Casting in Java

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion.

In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.

Note: type casting is not possible for a Boolean data type.

There are 13 types of conversion in Java. In this article, we will only look at 2 major types:

To read about the other types of casting, refer to this documentation.

Implicit casting

This type of conversion is also known as widening casting. It happens automatically when converting from a narrower range data type to a wider range data type. It also means converting a lower data type like an int to a higher data type like a double .

Implicit casting takes place under two conditions:

  • Compatibility of the data types. For example, data types such as numeric are compatible with other numeric data types, but they are not compatible with boolean, char, or string data types. In the same way as string is not compatible with a boolean data type.
  • If the targeted value to be converted has a smaller length e.g. 4 bytes, to a larger data type e.g. 8 bytes.
Читайте также:  Php header location post values

Implicit casting follows the order of conversion as shown below:

Byte -> Short -> Char -> Int -> Long -> Float -> Double 

Let’s look at an example of implicit type casting in Java.

Here, we will convert an int value to a long value and finally to a double value by using a simple assignment operator:

public class Main   public static void main(String[] args)   int a = 20;  long b = a; //implicit casting from int to long data type  double c = b; // implicit casting from long to double data type   System.out.println(a);  System.out.println(b);  System.out.println(c);  > > 

We can also convert an int into a double data type by instantiating a double class or by using the double.valueOf() method. This way also applies to converting an int to a long data type.

You can read more on this here.

Explicit type casting

This type of casting involves assigning a data type of high range to a lower range. This process of conversion is also referred to as narrowing type casting.

This is done manually as you need to do the casting using the “()” operator. If we fail to do the casting, a compile-time error will be returned by the compiler.

Explicit casting follows the order of conversion as shown below:

Double -> FLoat -> Long -> Int -> Char -> Short -> Byte 

Lets look at an example of explicit casting in Java:

public class Main   public static void main(String args[])   double d = 57.17;  int i = (int)d; // Explicit casting from long to int data type  System.out.println(d);  System.out.println(i); //fractional part lost  > > 

In the example above, we converted the double data type into an int data type. The decimal part of the value is lost after type casting.

Java wrapper class

To convert a primitive data type into an object, we need the wrapper classes. We can take string inputs from the users e.g “1234”, then, convert it to int data type and vice versa. For example:

String a = "1234"; int b = Integer.parseInt(a); // converting string to int 

In Java, all primitive wrapper classes are immutable i.e when we create a new object, the old object cannot be changed without exception.

Ways of creating wrapper objects

1. Using Double wrapper class constructor

We can cast an int to double data type by passing the value of int to the constructor of the Double wrapper class.

public class Main   public static void main (String args[])    int num = 67;  Double myDouble = new Double(num); // using Double wrapper class   // showing the double value  System.out.println("My double is " + myDouble);  > > 

2. Using Java Double valueOf() method

In this method, we convert int to double using the valueOf() method in the Double wrapper class.

public class Main   public static void main (String[] args)    int myInt = 67;  Double myDouble = Double.valueOf(myInt);// converting int to double using the Double valueOf() method   System.out.println("My double is " + myDouble);  > > 

Conclusion

In this article, we have looked at the different ways of type casting our data type. We can now easily type cast from one data type to another.

Peer Review Contributions by: Mohan Raj

Источник

Приведение типов объектов в Java

Система типов Java состоит из двух типов типов: примитивы и ссылки.

Мы рассмотрели примитивные преобразования вthis article, и здесь мы сосредоточимся на приведении ссылок, чтобы получить хорошее представление о том, как Java обрабатывает типы.

Дальнейшее чтение:

Основы Java Generics

Краткое введение в основы Java Generics.

Java экземпляр оператора

Узнайте об операторе instanceof в Java

2. Примитив против Ссылка

Хотя примитивные преобразования и приведение ссылочных переменных могут выглядеть одинаково, они довольноdifferent concepts.

В обоих случаях мы «превращаем» один тип в другой. Но в упрощенном виде примитивная переменная содержит свое значение, а преобразование примитивной переменной означает необратимые изменения ее значения:

double myDouble = 1.1; int myInt = (int) myDouble; assertNotEquals(myDouble, myInt);

После преобразования в приведенном выше примере переменнаяmyInt равна1, и мы не можем восстановить из нее предыдущее значение1.1.

Reference variables are different; ссылочная переменная относится только к объекту, но не содержит самого объекта.

Приведение ссылочной переменной не затрагивает объект, к которому она относится, а только помечает этот объект другим способом, расширяя или сужая возможности для работы с ним. Upcasting narrows the list of methods and properties available to this object, and downcasting can extend it.с

Ссылка похожа на дистанционное управление объектом. Пульт дистанционного управления имеет больше или меньше кнопок в зависимости от его типа, а сам объект хранится в куче. Когда мы выполняем кастинг, мы меняем тип пульта дистанционного управления, но не меняем сам объект.

3. Апкастинг

Casting from a subclass to a superclass is called upcasting. Как правило, преобразование выполняется неявным образом.

Обновление тесно связано с наследованием — еще одна ключевая концепция в Java. Обычно используются ссылочные переменные для ссылки на более конкретный тип. И каждый раз, когда мы делаем это, происходит неявное обновление.

Чтобы продемонстрировать апкастинг, давайте определим классAnimal:

Источник

Оцените статью