Java Tips for Beginners (2): Mixed Data Types & The Ternary Operator

Previous post: Java Tips for Beginners (1) : Data Types

I will add two tips from module 1.

Mixed data types

Pay attention when using mixed data types: If you use two data types in one expression, it will automatically take the more general type. Double is the more general type compared to Int.

Example 1:
double avg = 2 is allowed;
int avg = 3.2 is not allowed.
Example 2:
int avg = (int) 3.2 is allowed
The conversion requires the explicit cast, which
will drop decimal places and get avg = 3.
Example 3:
int avg = (3+4)/2
will get avg = 3
Example 4:
Double avg = (5+6)/2 
will get avg = 5.0, because the right-hand side is computed first
Example 5:
Double avg = (double)(5+6)/2

In this case (double) 11 will be computed first,

so this time you will get avg = 5.5

The ternary operator


max = (a > b) ? a : b;

is equivalent with

if (a > b) {
  max = a;
else {
  max = b;

More examples:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s