Skip to content

Instantly share code, notes, and snippets.

@ionelh
Created February 1, 2020 16:59
Show Gist options
  • Save ionelh/180df167d2c4c37ab0219a07a8e9766d to your computer and use it in GitHub Desktop.
Save ionelh/180df167d2c4c37ab0219a07a8e9766d to your computer and use it in GitHub Desktop.
// With numeric types, you can automatically cast from smaller types
int tenInt = 10;
long tenLong = tenInt;
// Otherwise use (TYPE) newValue
double someDouble = 1.234;
int someInt = (int) someDouble;
System.out.println(someInt); // 1
// Most numeric types have methods to convert to string
String piStr = Double.toString(3.14);
System.out.println(piStr);
// Similarly, you can convert strings to numeric types
int intFromStr = Integer.parseInt("20000");
float floatFromStr = Float.parseFloat("1.68");
boolean boolFromStr = Boolean.parseBoolean("true");
byte byteFromStr = Byte.parseByte("42");
System.out.println(intFromStr);
System.out.println(floatFromStr);
System.out.println(boolFromStr);
System.out.println(byteFromStr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment