About casting in java

Casting between primitive Java types

Changing a value from one data type to a variable of another type is known as data type conversion.

There are two types of casting,

Primitive Type Casting

Casting between primitive types enables you to convert the value of one type to another primitive type is called Primitive Type Casting. This is most commonly occurs with the numeric data types . But boolean primitive type can never be used in a cast. Its values must be either true or false and cannot be used in a casting operation.

There are two basic types of Primitive Type Casting widening and narrowing.

Widening conversions (Implicit casting)

A value of narrower(lower size) data type can be converted to a value of a broader (higher size) data type without loss of information is called Widening conversion. This conversion also known as implicit casting .

In above example, an Automatic Type Casting take place, that is an integer variable (4 Byte) converted into double variable(8 Byte). The casting happened from a lower data type to a higher data type, so there is no data loss .

Widening conversions in Java

From a byte to a short, an int, a long, a float, or a double From a short to an int, a long, a float, or a double From a char to an int, a long, a float, or a double From an int to a long, a float, or a double From a long to a float or a double From a float to a double

Читайте также:  Html to launch an application

NOTE: A widening conversion of an int or a long value to a float value , or of a long value to double value, may result in loss of precision . That is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode.

Narrowing Conversions (Explicit Casting)

Converting from a broader data type (higher size) to a narrower data type (lower size) is called narrowing conversion. This type of conversion can result in loss of information. This is not done implicitly by the JVM and requires explicit casting .

In above example a double variable(8 Byte) converted into integer variable (4 Byte) . The casting happened from a higher data type to a lower data type, so can result in loss of information.

Narrowing conversions in Java

From a byte to a char From a short to a byte or a char From a char to a byte or a short From an int to a byte, a short, or a char From a long to a byte, a short, a char, or an int From a float to a byte, a short, a char, an int, or a long From a double to a byte, a short, a char, an int, a long, or a float

An implicit conversion is performed automatically, with no additional input from the developer. An explicit conversion , on the other hand, is not performed automatically and is, instead, dictated by the developer.

Reference Type Casting

Objects of classes also can be cast into objects of other classes when the source and destination classes are related by inheritance and one class is a subclass of the other. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java. There are two types of Reference Type Casting in Java, they are :

Up-casting is casting to a supertype, while downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException.

Upcasting

Casting a subtype object into a supertype and this is called upcast. In Java, we need not add an explicit cast and you can assign the object directly. Compiler will understand and cast the value to supertype. By doing this, we are lifting an object to a generic level. If we prefer, we can add an explicit cast and no issues.

Downcasting

Casting a supertype to a subtype is called downcast. This is the mostly done cast. By doing this we are telling the compiler that the value stored in the base object is of a super type. Then we are asking the runtime to assign the value. Because of downcast we get access to methods of the subtype on that object. When performing downcasting, that you’re well aware of the type of object you’ll be casting.

Источник

Type Casting in Java

If you want to be a programmer in any language, then type casting variables is something that you should definitely be very familiar with.

What is Type Casting in Java?

Type casting means taking an Object of one particular type and “turning it into” another Object type. This process is called type casting a variable.

This topic is not specific to Java, as many other programming languages support casting of their variable types. But, as with other languages, in Java you cannot cast any variable to any random type.

What are the Rules behind Casting Variables?

It’s fairly simple, you remember our talk about how everything in Java is an Object, and any Object you create extends from Object? This was inheritance, and this is important to understand when dealing with casting.

If you are going to cast a variable, you’re most likely doing what’s known as a downcast. This means that you’re taking the Object and casting it into a more “specific” type of Object. Here’s an example:

Object aSentenceObject = "This is just a regular sentence"; String aSentenceString = (String)aSentenceObject;

You see what we’ve done here? Since the type Object is a very broad type for a variable, we are “downcasting” the variable to be a String type. Now, the question is, is this legal? Well, you can see that the value stored in the aSentenceObject is just a plain old String , so this cast is perfectly legal. Let’s look at the reverse scenario, an “upcast”:

String aSentenceString = "This is just another regular sentence"; Object aSentenceObject = (Object)aSentenceString;

Here we are taking a variable with a more specific type ( String ) and casting it to a variable type that’s more generic ( Object ). This is also legal, and really, it is always legal to upcast.

What are the benefits of casting variables?

There are times when you want to get more specific functionality out of a generic Object. For example, in my line of work, I deal with web applications, and I’m always dealing with something called a “model”. This “model” represents data that I want to display on a webpage, and the model is essentially a generic Map . The Map stores key/value pairs, where the key is a String and the value is usually just the generic Object type. So, an example of what would appear in this model would be:

“name” -> “Trevor Page”
“email” -> “tpage@ecosim.ca”
“birthday” -> “07-01-83”

Here’s what that Map would look like in code:

This Map is a candidate for casting, and here’s how we would deal with the casting:

String name = (String)model.get("name"); String email = (String)model.get("email"); Date birthday = (Date)model.get("birthday");

You see how we did three separate casts there? Since all the objects stored in the map are of type Object , this means that they are very generic and could most likely be downcasted. Since we know that the “name” is a String, and the “email” is a String, and the “birthday” is a Date, we can do these three downcasts safely.

This would then give us more flexibility with those three variables, because now we have an actual birthday Date object, so we have access to methods like getTime() instead of just the default Object methods.

This is quite a valuable approach to storing Object s in a Map , because if we had created the Map with something more specific than Object as the value, then we would be constrained to only storing Object s of that specific type (and its sub-classes).

What are the downsides to Casting?

Well, there is a certain amount of risk that goes along with downcasting your variables. If you were to try to cast something like a Date object to an Integer object, then you’ll get a ClassCastException . This is what’s known as a run-time exception, as it’s really only detectable when your code is running. So, unless you’re doing something with error handling, then your program will likely exit or you’ll get an ugly error message on your webpage.

So just make sure that if you are doing any downcasting, that you’re well aware of the type of object you’ll be casting.

The Best 7 Java Programming Resources

Alright, so if you’re read this far down the article, then you’re clearly interested in learning how to code. We actually have a free guide that outlines the best 7 resources for Java programmers.

When you sign up you’ll receive the guide immediately and you’ll also receive a few emails a week that will help you speed up your Java learning process so you can get up and running as fast as possible.

Go ahead an click the button below to get started!

Summary

To sum up, casting is a very useful mechanism that allows you to write more generic code that will allow you to handle many coding situations. But this mechanism can introduce some risk if you’re not careful with what you will be casting.

Источник

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