Type casting in java with example

Type Casting in Java

Type Casting in Java with Examples

In this article, I am going to discuss Type Casting in Java with Examples. Before learning Type Casting, you must know about Java Data Types. So, please read our previous article, where we discussed Literals in Java with Examples. At the end of this article, you will understand what Type Casting is and why and when we need Type Casting in Java.

What is Type Casting in Java?

The process of converting the value of one data type (int, float, double, etc.) into another data type is known as Type Casting. Type Casting is the temporary conversion of a variable from its original data type to some other data type, like being cast for a part in a play or movie.

With primitive data types if a cast is necessary from a less inclusive data type to a more inclusive data type it is done automatically. If a cast is necessary from a more inclusive data type to a less inclusive data type the cast must be done explicitly by the programmer.

Читайте также:  Android java send broadcast
Conversion between Primitive Data Types: Cast Operator

The Cast Operator manually lets you convert a value of the data type into another data type. It can be done by Writing the cast operator in front of the expression that needs to be converted.

Syntax : (dataTypeName) expression;

When casting from a double to an int, the fractional part will be discarded.

Example :

int x;
double y = 2.5;
x = (int)y;

Here, int is the Cast Operator.

Java compiles the code with the cast operator with no problems. In this case, the variable y has a value of 2.5 (the floating-point value) which must be converted to an integer. The value that is returned and stored in variable x would be truncated, which means the fractional part of the number is lost to accommodate the integer data type. Thus, x=2 and, the value of the variable y is not changed at all: y=2.5

Types of Type Casting in Java:
  1. Widening or Automatic Type Casting
  2. Narrowing or Explicit type Casting
Widening Type Casting in Java:

Widening Type Casting is also known as Automatic Type Casting. When you assign the value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion. For better understanding, please have a look at the following image.

Type Casting in Java with Examples

It happens when the two data types are compatible and when we assign the value of a smaller data type to a bigger data type.

Example of Widening or Automatic Type Casting in Java:
package Demo; public class AutomaticTypeConversion < public static void main (String args[]) < int intVariable = 100; long longVariable = intVariable; float floatVariable = longVariable; System.out.println ("Integer Value is : " + intVariable); System.out.println ("Float Value is : " + floatVariable); System.out.println ("Long Value is : " + longVariable); >>
Output:

Example of Widening or Automatic Type Casting in Java

Narrowing Type Casting in Java:

Narrowing Type Casting is also known as Explicit type Casting. This is useful for incompatible data types where automatic conversion cannot be done. It happens when the two data types are not compatible and when we want to assign a value of a larger data type to a smaller data type.

Example of Narrowing or Explicit Type Casting in Java:
package Demo; public class ExplicitTypeCasting < public static void main (String[]args) < double doubleVariable = 100.04; long longVariable = (long) doubleVariable; int intVariable = (int) longVariable; System.out.println ("Double Value is : " + doubleVariable); System.out.println ("Long Value is : " + longVariable); System.out.println ("Integer Value is : " + intVariable); >>
Output:

Example of Narrowing or Explicit Type Casting in Java

In the next article, I am going to discuss Operators in Java with Examples. Here, in this article, I try to explain Type Casting in Java with Examples and I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Источник

Type casting in java with example

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Java Type Casting

Before you learn about Java Type Casting, make sure you know about Java Data Types.

Type Casting

The process of converting the value of one data type ( int , float , double , etc.) to another data type is known as typecasting.

In Java, there are 13 types of type conversion. However, in this tutorial, we will only focus on the major 2 types.

To learn about other types of type conversion, visit Java Type Conversion (official Java documentation).

Widening Type Casting

In Widening Type Casting, Java automatically converts one data type to another data type.

Example: Converting int to double

The integer value: 10 The double value: 10.0 

In the above example, we are assigning the int type variable named num to a double type variable named data .

Here, the Java first converts the int type data into the double type. And then assign it to the double variable.

In the case of Widening Type Casting, the lower data type (having smaller size) is converted into the higher data type (having larger size). Hence there is no loss in data. This is why this type of conversion happens automatically.

Note: This is also known as Implicit Type Casting.

Narrowing Type Casting

In Narrowing Type Casting, we manually convert one data type into another using the parenthesis.

Example: Converting double into an int

The double value: 10.99 The integer value: 10 

In the above example, we are assigning the double type variable named num to an int type variable named data .

Here, the int keyword inside the parenthesis indicates that that the num variable is converted into the int type.

In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into lower data types (having smaller size). Hence there is the loss of data. This is why this type of conversion does not happen automatically.

Note: This is also known as Explicit Type Casting.

Let’s see some of the examples of other type conversions in Java.

Example 1: Type conversion from int to String

The integer value is: 10 The string value is: 10 

In the above program, notice the line

String data = String.valueOf(num); 

Here, we have used the valueOf() method of the Java String class to convert the int type variable into a string.

Example 2: Type conversion from String to int

The string value is: 10 The integer value is: 10 

In the above example, notice the line

int num = Integer.parseInt(data); 

Here, we have used the parseInt() method of the Java Integer class to convert a string type variable into an int variable.

Note: If the string variable cannot be converted into the integer variable then an exception named NumberFormatException occurs.

Table of Contents

Источник

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.

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

Источник

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