Casting in Java, What is it?

Java has sort of unique understanding of the primitive data types in java (if you are comparing it with Javascript) because those eight primitive data types which are byte, char, short, int, long, float, and double it formed with a number(we will take about each of those data types later!). Now in Javascript, if you are declaring a variable with a number for instance “var num = 10”, later with coding you can always override with different values such as “num = 3.14”. In JS this act is totally fine and there is no error, or wrong with the syntax. However, Java doesn’t work that way, and let’s take a look.

Resources: https://www.worldofitech.com/java-programming-typecasting/
public class Casting {public static void main(String[] args) {int myInteger= 10;double myDouble = 3.14;//In java this is called casting, and it's totally noraml!myDouble= myInteger;// Well, this' doesn't work, and it will throw you an compile error.myInteger= myDouble;//To fixe above error, we must do casting!myInteger= (int) myDouble;   }}

As you might figure out in Java it’s impossible to compare if data types are not the same. In the example above we’ve tried to compare with “int”(integer) to “double” data types that java doesn’t understand what that code is exactly mean! To make it easy to understand we were trying to compare with an apple and grape! Both are fruits but not the same type of fruit. So back to code again, Java is smart enough to catch an error and it’ll warn with a compile error, and also understand that when converting from small data types to larger data types, there won’t be any problem such as losing data. Therefore when we are comparing with a smaller data type like “int” to a much larger one “double”, it was fine. However, if we reverse the action, since we are converting from larger data to smaller data, Java thinks that there will be a loss of data, so before even that happens, Java will let us in advance by throwing an error!

So What is casting? Let’s look at the code again.

Public class Casting {public static void main(String[] args) {int myInteger= 10;double myDouble = 3.14;myDouble= (double) myInteger; //Here Java is actually doing this!
but it was hidden -> (double).
myInteger= (int) myDouble; //Similar to above,but this time we must
put casting ->(int) in order to aovid
complie error!
}
}

There you go, now we casting in Java we can simply convert with each of the primitive data types without an error!