+ 1

Type casting in java

Hello! Could somebody please explain type casting in java? I want to create a program, where the input is a string that contains digits and do a calculation with these ints. So i need to cast from char to int. Thanks a lot!

21st Dec 2016, 1:22 PM
quantic
3 odpowiedzi
+ 7
Type casting happens when you assign a value of one type to another variable of a different type. For example : int i = 10; long y = i; float x = y; but there is also explicit type casting, it happens when you are assigning a large variable to a smaller one. For example : double y = 10.04; long x = (long)y; int i = (int)x; To get/declare an int variable from a char variable , you need to use this line : int x = Character.getNumericValue(c); //c being a char that contains a number of course! I recommend making a function/statement that checks if 'c' is a character, because the conversation will work even if the char is not a number, which means that it won't produce an error, but instead, some other random number may appear.
21st Dec 2016, 1:38 PM
Wen Qin
Wen Qin - avatar
+ 2
If you're trying to convert a string to an integer, try this for exemple : String s = "1234567" ; int n = Integer.parseInt(s); System.out.println(n); n contains the integer 1234567 good luck 😊 !
21st Dec 2016, 1:40 PM
A B
0
Thank you, i used the "explicit type casting" and it worked out well.
21st Dec 2016, 6:49 PM
quantic