Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      Type Casting

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      Type Casting

      Java Type Casting (Type Conversion)

      Type casting is a technique that is used either by the compiler or a programmer to convert one data type to another. For example, converting int to double, double to int, short to int, etc. Type typing is also known as Type conversion.
      There are two types of cast typing allowed in Java programming:
      • Widening type casting
      • Narrowing type casting

      Widening Type Casting

      Widening Type Casting is also known as implicit type casting in which a smaller type is converted into a larger type, it is done by the compiler automatically.
      Here is the hierarchy of widening type casting in Java:
      byte > short > char > int > long > float > double
      The compiler plays a role in the type conversion but not the programmers. It changes the type of the variables at the compile time. Also, type conversion occurs from the small data type to large data type only.

      Example 1: Widening Type Casting

      In the example below, we demonstrated that we can get an error when the compiler tries to convert a large data type to a small data type. Here, we created the num1 integer and num2 double variable. The sum of num1 and num2 will be double, and when we try to store it to the sum of the int type, the compiler gives an error.
      package com.tutorialspoint;
      
      public class Tester {
      // Main driver method
      public static void main(String[] args) {
      // Define int variables
      int num1 = 5004;
      double num2 = 2.5;
      int sum = num1 + num2;
      // show output
      System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
      }
      }
      Compile and run Tester. This will produce the following result

      Output

      Exception in thread "main" java.lang.Error: Unresolved compilation problem:
      Type mismatch: cannot convert from double to int
      
      at com.tutorialspoint.Tester.main(Tester.java:9)

      Example 2: Widening Type Casting

      In the example below, we created the num1 and num2 variables as same in the first example. We store the sum of both numbers in the sum variable of double type. In the output, we can observe the sum of double type.
      package com.tutorialspoint;
      
      public class Tester {
      // Main driver method
      public static void main(String[] args) {
      // Define int variables
      int num1 = 5004;
      double num2 = 2.5;
      double sum = num1 + num2;
      // show output
      System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
      }
      }
      Compile and run Tester. This will produce the following result

      Output

      The sum of 5004 and 2.5 is 5006.5

      Narrowing Type Casting

      Narrowing type casting is also known as explicit type casting or explicit type conversion which is done by the programmer manually. In the narrowing type casting a larger type can be converted into a smaller type.
      When a programmer changes the variable type while writing the code. We can use the cast operator to change the type of the variable. For example, double to int or int to double.

      Syntax

      Below is the syntax for narrowing type casting i.e., to manually type conversion:
      double doubleNum = (double) num;
      The above code statement will convert the variable to double type.

      Example: Narrowing Type Casting

      In the example below, we define the num variable of integer type and initialize it with the value. Also, we define the doubleNum variable of double type and store the num variable's value after converting it to the double.
      Next, We created the 'convertedInt' integer type variable and stored the double value after type casting to int. In the output, we can observe the value of the double and int variables.
      package com.tutorialspoint;
      
      public class Tester {
      // Main driver method
      public static void main(String[] args) {
      // Define int variable
      int num = 5004;
      // Type casting int to double
      double doubleNum = (double) num;
      // show output
      System.out.println("The value of " + num + " after converting to the double is " + doubleNum);
      // Type casting double to int
      int convertedInt = (int) doubleNum;
      // show output
      System.out.println("The value of " + doubleNum + " after converting to the int again is " + convertedInt);
      }
      }
      Compile and run Tester. This will produce the following result

      Output

      The value of 5004 after converting to the double is 5004.0
      The value of 5004.0 after converting to the int again is 5004