More Complicated Expressions

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

int a = 7, b = 21;
System.out.println( "The min is: " + (a < b ? a : b ) );

More Complicated Expressions

Here is a slightly more interesting example:

A program computes the average grade each student in a class. Students whose average grade is below 60 are given a bonus of 5 points. All other students are given a bonus of just 3 points.

Here is the program fragment that does this:

... average grade is computed here ...

average += (average < 60 ) ?  5 : 3 ;

The subexpressions that make up a conditional expression can be as complicated as you want. Now say that student grades below 60 are to be increased by 10 percent and that other grades are to be increased by 5 percent. Here is the program fragment that does this:

... average grade is computed here ...

average += (average < 60 ) ? average*0.10 : average*0.05;

This is probably about as complicated as you want to get with the conditional operator. If you need to do something more complicated than this, do it with if-else statements.

QUESTION 4:

Write an assignment statement that adds one to the integer number if it is odd, but adds nothing if it is even.

Click here for a