Car Purchase Program

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.
go to previous page   go to home page   hear noise   go to next page

Answer:

The boolean expression is true

34 > 2   ||   5 == 7
------        -----
 true         false
   --------------
       true

because all OR needs is one true.

Car Purchase Program

The above expression evaluates to true because at least one operand was true. In fact, as soon as the first true is detected, you know that the entire expression must be true, because true OR anything is true.

34 > 2   ||   5 == 7
------        -----
 true         does not matter
   --------------
       true

As an optimization, Java evaluates an expression only as far as needed to determine its value. When program runs, as soon as 34 > 2 is found to be true, the entire expression is known to be true, and evaluation goes no further. This type of optimization is called short-circuit evaluation. (Just as it is with AND.)

Here is a full Java program that implements the car purchase decision.

// Sports Car Purchase
//
// You need $25000 in cash or credit
//
import java.util.Scanner;

class HotWheels
{
  public static void main (String[] args) 
  { 
    Scanner scan = new Scanner( System.in ); 
    int cash, credit ; 

    // get the cash
    System.out.print("How much cash? ");
    cash = scan.nextInt() ; 

    // get the credit line
    System.out.print("How much credit? ");
    credit = scan.nextInt() ; 

    // check that at least one qualification is met
    if ( cash >= 25000  ||  credit >= 25000 )
      System.out.println("Enough to buy this car!" );
    else
      System.out.println("What about a Yugo?" );

  }
}

Compile and run the program with various values of cash and credit to check that you understand how OR works.

QUESTION 19:

What does the program do if the user enters negative numbers?