Java Type Conversion

By Kunal Kapoor
19-04-2018
591

In java a data type can be converted to other data types. There are certain cases when data types cannot be converted to other data types. eg char cannot be converted to Boolean and vice-versa .


  • 1.       Converting int to char

Conerting int to char gives the ASCII value equivalent of int data type

Eg

 int input = 48;

char output = (char)input;

 

in this case ouput will be equal to ‘0’;

 

  • 2.       Converting char to int

As in above case this converting

Eg

 char input = ‘A’;

int output = (int)input;

 

in this case ouput will be equal to 65;

 

  • 3.       Converting double to int

double double_val=213.34;

int int_val= (int)double_val;

 

output will be int_val=213.


eg.



myClass.java:

package java_type_conversion;

public class myclass {

	public static void main(String[] args) {
		
		int input = 48, int_val;
		char output,char_int='A';

		// int to char
		output=(char)input;
		// cahr to int
		int_val=(int)char_int;
		
		System.out.println("int " +input+"; to char = "+output);
		System.out.println("char "+char_int+"; to int = "+int_val);
		
		
	}

}


output:

int 48; to char = 0
char A; to int = 65



Related Tutorials