DEV Community

Cover image for Data Types
Greg Ross
Greg Ross

Posted on

Data Types

Declaring Information

New to Java and statically typed languages. So needing to declare every single instance of data was a foreign concept at first. Conceptually this approach is logical. You need to know exactly the type of data you want to call and exactly what kind of data you want to return.

int numberOfToads = 5; 
double costOfGroceries = 23.21;
boolean isReal = false;
String letters = 'info'; 
char lastLetter = 'o'; 
Enter fullscreen mode Exit fullscreen mode

Type Casting

Changing one data's value into another data type.

int wholeNumber = 8; 
double decimalNumber = wholeNumber; // 8.0
Enter fullscreen mode Exit fullscreen mode

Two styles of casting

1 Widening: automatic conversion from small to larger type

// byte -> short -> char -> int -> long -> float -> double
Enter fullscreen mode Exit fullscreen mode

2 Narrowing: manual conversion from larger to smaller type

// double -> float -> long -> int -> char -> short -> byte
Enter fullscreen mode Exit fullscreen mode

Evaluate Expressions

Performing calculations on data. Fundamental math rules apply.

int total; 
total = 4 + 4;     // addition
total = total - 3; // subtraction
total = total * 5; // multiplication
total = total / 5; // division 
total = total % 3; // remainder of 
Enter fullscreen mode Exit fullscreen mode

Real Use Case

int player1 = 75;
int player2 = 87;
int player3 = 92;

int averagePoints = (player1  + player2  + player3 ) / 3;  
double averagePoints = (player1  + player2  + player3 ) / 3.0; 

Enter fullscreen mode Exit fullscreen mode

Top comments (0)