• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » DataType » Type Conversion in Java Example
Next →
← Prev

Type Conversion in Java Example

By Dinesh Thakur

Java has a wide variety of data types from which we can choose the suitable for a particular purpose. To operate on variables from two different types of data we have to convert Both types to the same.

In Java, the expressions and assignments may involve variables of different data types. This type can derive from the structure of the expression and the types of variables and literals used in the expression. It is possible to write an expression that is inappropriate for the type context. In some cases, this leads to an error in compilation of the program, but in another context can accept type which is similar or related to the type of the expression. To evaluate such expressions and assignments, there is a need to convert a variable of one data type to another. Consider an example in which we declare variables of type integer, but we may need the result to be of floating point number. In such situations, we need type conversion. This property of converting a variable of one data type to another data type is known as type conversion.

Type conversion can occur in some situations like in an assignment statement, in arithmetic expressions involving different data types and in returning value from the function in which the type of the expression differs from the return type.

Specific conversion from type S to type T allow the expression of type S treated as an expression of type T during the execution of the program. In some cases this will require validation conversion. Here are some examples:
1. Conversion from type Object to a String require verification during execution to verify that the value is a correct instance of type String or any class of heirs String.
2. Convert a String to Object does not require verification. A string is the successor of the Object and can convert to its base class without risk of error or loss of data.
3. Conversion from type int to long can be done without check during the performance because there is no danger of losing data.
4. Conversion from type double to long conversion requires 64 – bit floating point value to a 64-bit integer. Depending on value can be obtained data loss because it is
necessary to convert types explicitly. In Java, not all types can convert to any other, but only specific.

We’ll be covering the following topics in this tutorial:

  • Type conversion is usually classified in two categories.
  • Converting to string

Type conversion is usually classified in two categories.

1) Implicit or Automatic Type Conversion
2) Explicit Type Casting or Type Casting

Implicitly (Automatic) Type Conversion

Implicit (hidden) type conversion is only possible when there is no possibility of data loss in the conversion, i.e., When you convert type to a smaller range to type with greater (for example from int to long). To make implicit conversion is not needed to use any operator, so-called hidden.
The conversion is done automatically by the compiler when mapping value of the small-scale variable in a broader scope, or when expression types have a different scope. Then convert it to type with a greater range. This is known as widening a type.

The rules in the sequence in which they checked are as follows,

1. If either operand is a double, the entire expression is promoted to double before the operation is carried out.
2. Otherwise, if either operand is the float, the other is promoted to float before the operation is carried out.
3. Otherwise, if either operand is long, the other is promoted to long before the operation is carried out.
4. Otherwise, if either operand is int, the other operand is promoted to int.
5. If neither operand is double, float, long or int, both operands promoted to int.

Implicit Type Conversion – Example

Here is an example of implicit (implicit) type conversion :

int VarInt = 5;
System.out.println(VarInt); // 5
long Varlong = VarInt;
System.out.println(Varlong); // 5
System.out.println(Varlong + VarInt); // 10

Possible Transformations Implied

These are possible implicit conversion of primitive types in Java:

Conversion of types from small-scale to a larger no loss of data. The numerical value remains the same after conversion. As with any rule, there are few exceptions. When convert type int to type float ( 32-bit values), the difference is an int that uses all your bits for a single integer including as part of the float bits used for the presentation of Float. Hence, it is possible in the conversion of int to float to a loss of accuracy due to rounding. The same concerns the conversion of 64-bit long to double.

For example: In the statements,
int i = 10;
double j = 5.6;

Suppose we want to compute i + j, the arithmetic expression i + j involves two variables of different data types int and double; the compiler evaluates this expression by converting the int data type of variable i into double according to rules of implicit conversion discussed — this converted value stored in the temporary double variable before being added to the variable j.
After the conversion, addition performed that results in 15.6. This conversion takes place automatically without any information to the programmer. The implicit type conversion show below

 

Similarly,
1/2 = 0 (int), 8/2.0 = 4.0 (double)
1.2/2 = 0.5 (double), 8.0/2.0 = 4.0 (double)

The following program shows how implicit type conversion is performed.

//program to show implicit type converstion
public class ImplicitConv {
   public static void main(String[] args) {
     byte i = 10;
long j = i + 8;
     double k = i * 2.5 + j;
     System.out.println(“i = “ +i);
     System.out.println(“j = “ +j);
     System.out.println(“k = “ +k);
   }
}
Output: i = 10 j = 18 k = 43.0

Here, the variable i is of byte data type and j is of the long data type. So during the evaluation of the expression i + 8, the data type of the variable is converted temporarily from byte data type to that of int data type so that it can add to int literal 8. Now both the temporary variable and literal 8 to be added are of the same type, the result obtained is of int type which again stored in a new temporary variable which is .created during its execution.
Since the datatype of variable j (i.e., long) on the lefthand side differs from the data type on the right side (i.e., int), so the int data type is converted into long and stored in a temporary variable created internally. Finally, the result assigned to variable j.
Similarly, an implicit conversion takes place for the expression k = i  * 2.5 + j;

Explicitly (explicit) Type Conversion

Explicit type conversion is needed when it is probable loss of data. When you convert a floating-point type to an integer type, there is always loss of data coming from the float and must use explicit conversion (double to long). To make such conversion is necessary to explicitly use operator for data conversion (cast operator): (type). possibly There may be data loss also when converting from type larger range to type with less (double to float or long to int). Explicit type conversion is also known as narrowing a type.

Explicit Type Conversion – Example

The following example illustrates the use of an explicit conversion types and data loss:

double VarDouble = 5.1d;
System.out.println(VarDouble); // 5.1
long Varlong = (long)VarDouble;
System.out.println(Varlong); // 5
VarDouble = 5e9d; // 5 * 10^9
System.out.println(VarDouble); // 5.0E9
int VarInt = (int) VarDouble;
System.out.println(VarInt); // 2147483647
System.out.println(Integer.MAX_VALUE); // 2147483647

The first line of the example you assign a value to the variable 5.1 VarDouble. Once you convert it (explicitly) by the operator (long) long to type and print the console variable Varlong, we see that the variable is the value lost after float (for long to integer). Then on the seventh row Assign variable VarDouble 5 billion. finally convert VarDouble to int by the operator (int) and print variable VarInt. Then same result as when print Integer MAX_VALUE, this is because VarDouble incorporates more value of the range of int.

Loss of Data Type Conversion

Example of loss of information on type conversion:

long Varlong = Long.MAX_VALUE;
int VarInt = (int)Varlong;
System.out.println(Varlong); // 9223372036854775807
System.out.println(VarInt); // -1

Conversion operator can be used in implicit conversion. This makes for code readability, reduces chance of errors and is considered good practice by many programmers.
Here are a few examples of the type conversion:

float height = 1.74f; // Explicit conversion
double MaxH = height; // Implicit
double MinH = (double) height; // Explicit
float AHeight = (float) MaxH; // Explicit
float MaxHFloat = MaxH; // Compilation error!

In the example, the last line we have an expression that will generate error compilation. This is because we are trying to implicitly convert type double to type float, which may be a loss of data. Java is strictly typed programming language and does not allow this kind assign values​​.

Possible Explicit Transformations

These are possible explicit transformations and all of them have the possibility of data loss, so be careful:
1. Short to byte or char
2. Char to byte or short
3. Int to byte, short or char
4. Long to byte, short, char or int
5. Float to byte, short, char, int, or long
6. Double to byte, short, char, int, long or float

These transformations can lose as information about the size the number, and information about its accuracy (precision).
When you convert a byte to char have the first secret of converting byte to int, then it explicit conversion from int to char.

Converting to string

If necessary, we can convert to string each type including the value null. Conversion of strings happens automatically whenever you use the concatenation operator and any argument is of type string. In this case, the argument is converted, forms a string to the operator returns a new string representing the concatenation of two strings.
Another way to convert objects to different types such as string is call method toString () of the variable.

Converting to string – example
Let us examine some examples of the conversion of different types of data to a string:

int a = 5;
int b = 7;
String s = “Sum=” + (a + b);
System.out.println(s);
String incorrect = “Sum=” + a + b;
System.out.println(incorrect);
System.out.println(“Perimeter = ” + 2 * (a + b) +”. Area = ” + (a * b) + “.”);

The results of the example is as follows:

Sum=25
Sum=57
Perimeter = 24.
Area = 35.

From the results it appears that a number attached to a string returns as a result the string, followed by the text representation of number. Note that the ‘+’ to glue strings can cause unpleasant effect the recovery of numbers because it has the same priority with the “+” collection. Unless explicitly change priority of operations by placing the brackets, they always run from left to right.

You’ll also like:

  1. Implicit Type Conversion in Java Example
  2. Difference Between Type Conversion and Type Casting
  3. Explicit Type Conversion (Type Casting)
  4. Write C++ program illustrates automatic type conversion from char to int.
  5. Type Casting in Java Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW