Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
Now Reading
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Various industries widely use Java, which is a popular programming language. The language was designed to be written once and be able to run the program without any modifications across multiple platforms. Java has a safe environment with sound security, delivering high flexibility and user-friendliness. This is why it is a widely used programming language.
Type casting in Java is a vital method programmers use to change the data type from one form to another. There are two distinguished kinds of type casting in Java: implicit and explicit type casting.
This tutorial primarily deals with the meaning of type casting in Java and its types and explains the processes with the help of code examples for gaining a clearer understanding.
Here are the types of type casting in Java:
Type casting Java is a process of converting a value of one data type to another data type. Widening type casting is also known as implicit type casting. It is a type of type casting where the data type of a variable is automatically converted to a larger data type. This is done without the need for any explicit conversion.
For instance, if we have a variable "a" of type "int" (that can be used only with integer values) with a value of “10”. Then we assign the value of "a" to a variable "b" of type "double" (that can be used with decimal values). Then this is an example of widening type casting. This is because "double" is a larger data type than "int." Also, the value of "a" can be represented without any loss of precision in a "double" variable.
Here's a widening type casting example:
public class WideningTypeCastingExample {
public static void main(String[] args) {
int myInt = 10;
double myDouble = myInt;
System.out.println("myInt: " + myInt);
System.out.println("myDouble: " + myDouble);
}
}
In this example, we declare an integer variable myInt, with a value of “10”. We then assign this value to a double variable, “myDouble,” using widening type casting. This is done since double is a larger data type than int.
Narrowing type casting is also known as explicit type casting. It is a type of type casting where the data type of a variable is explicitly converted to a smaller data type. This can hold less data without losing precision.
For instance, if we have a variable "a" of type "double" with a value of 10.5. If we assign the value of "a" to a variable "b" of type "int," Then this is an example of narrowing type casting. This is because "int" is a smaller data type than "double." It is to be noted that some of the information in "a" may be lost when it is converted to an "int" variable.
Here's an example code that demonstrates narrowing type casting:
public class NarrowingTypeCastingExample {
public static void main(String[] args) {
double a = 10.5;
int b = (int) a;
int c = b + 5;
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
}
}
In this code, we first perform narrowing type casting to convert the value of "a" to an "int" value of “10”. We then use the result of the narrowing type casting in an arithmetic operation. In essence, we add “5” to it. Then, we store the result in a variable "c." Then we print the values of "a," "b," and "c." We can see that "a" retains its original value of “10.5”. "b" is the truncated value of "a" after narrowing type casting. "c" is the result of adding “5” to "b."
Two ways we can change the type from one to another:
Type casting
In Java, type casting is the process of converting a variable of one data type to another data type. This can be done explicitly using a cast operator. This can also be done implicitly in some cases where the conversion is safe and automatic. There are two types of type casting: widening and narrowing. These are already explained in detail above.
Type conversion
Type conversion and casting in Java are two related concepts. Type conversion is a more general term that refers to converting a value from one data type to another. This can either be done implicitly or explicitly. This may include type casting as well as other forms of conversion, such as converting a string to a numeric data type.
For example:
public class TypeConversionExample {
public static void main(String[] args) {
String myString = "10";
int myInt = Integer.parseInt(myString);
System.out.println("myString: " + myString);
System.out.println("myInt: " + myInt);
}
}
In Java, explicit type casting can also be applied to user-defined data types, such as classes and interfaces. However, the rules for type casting user-defined types differ slightly from those for primitive types.
To perform an explicit type cast on a user-defined data type, the type being cast must either be a subclass of the target type or implement the target interface. This is because the target type must be able to "accept" the type being cast. This is only possible if the type being cast has all of the properties and methods required by the target type.
For instance, suppose we have two classes, “Animal” and “Dog,” where “Dog” is a subclass of “Animal”:
public class Animal {
public void eat() {
System.out.println("Eating...");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Barking...");
}
}
To cast a “Dog” object to an “Animal” object, we can use the cast operator as follows:
Dog myDog = new Dog();
Animal myAnimal = (Animal) myDog;
Since “Dog” is a subclass of “Animal,” we can safely cast a “Dog” object to an “Animal" object. The resulting “Animal” object will have all of the properties and methods of “Animal.” However, any properties or methods specific to “Dog” will be "hidden" or inaccessible.
However, if we try to cast an “Animal” object to a “Dog” object, we will get a runtime error. This is simply because not all “Animal” objects can be treated as “Dog” objects:
Animal myAnimal = new Animal();
Dog myDog = (Dog) myAnimal;
In this case, the “Animal” object does not have all of the properties and methods required by “Dog.” As a result, the cast fails, and a “ClassCastException” is thrown at runtime.
In summary, explicit type casting on user-defined data types is only possible if the type being cast is a subclass of the target type or implements the target interface. Otherwise, it will result in a runtime error.
Explicit downcasting in Java converts an object of a superclass type to an object of its subclass type. This is done explicitly using a cast operator. It is only allowed when the object being cast was initially created as an instance of the subclass.
Here is an example of explicit downcasting in Java:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
public void fetch() {
System.out.println("The dog fetches a ball");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.makeSound();
Dog myDog = (Dog) myAnimal;
myDog.fetch();
}
}
In Java, explicit upcasting refers to converting a reference to a more specific class type to a reference to a less specific class type. This is because we are widening the scope of the reference variable to a more general type. This is also known as widening conversion.
Here is an example of explicit upcasting in Java:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
public void fetch() {
System.out.println("The dog fetches a ball");
}
}
public class UpcastingExample {
public static void main(String[] args) {
Dog myDog = new Dog();
Animal myAnimal = (Animal) myDog;
myAnimal.makeSound();
}
}
Explicit type casting in Java is beneficial when we want to convert a value of one data type to another data type. There can be various applications of explicit type casting. Some of those are as follows:
int num1 = 10;
double num2 = 3.14;
int result = (int) (num1 + num2);
String userInput = "50";
int num = Integer.parseInt(userInput);
double[] myArray = { 1.5, 2.7, 3.2 };
int[] newArray = new int[3];
for (int i = 0; i < myArray.length; i++) {
newArray[i] = (int) myArray[i];
}
Automatic type casting in Java is also known as implicit type casting. It is useful when Java automatically converts one data type's values to another. This can occur in various situations. Some of these situations are as follows:
int num1 = 10;
double num2 = num1;
int num1 = 10;
int num2 = 3;
double result = num1 / num2;
public void myMethod(int num) {
}
public void myMethod(double num) {
}
int num1 = 10;
double num2 = 3.14;
myMethod(num1);
myMethod(num2);
This tutorial will help aspiring programmers gauge the uses and correct usage of type casting in Java. Learners can also avail of courses offered by reputed online learning platforms like upGrad to master programming languages like Java and much more. This will help them get a career boost if they want to explore the field of computer application and computer science.
1. What are the differences between implicit type casting and explicit type casting in Java?
There are a few differences between implicit and explicit type casting in Java.
Implicit type casting is done automatically by Java. Explicit type casting is done manually by the programmer. Implicit type casting is generally safer because the conversion is done automatically. Explicit type casting can be risky if the programmer is not careful about potential data loss or errors.
2. What is data loss in type casting in Java?
Data loss occurs when a value of one data type is converted to another, and some information is lost in the process. For instance, if a double value is cast to an int, the decimal portion of the value will be truncated. Therefore, this results in a loss of precision.
3. How can you cast a variable in Java?
To cast a variable in Java, you use syntax such as "(int) myDouble" to cast a double to an int. The data type being cast is enclosed in parentheses before the variable name.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...