Java Language Exercises

  < Previous  Next >
  1. In the following code, identify improper code or violations of style guidelines:
    /** Valid and invalid code used for an exercise to identify proper and improper coding syntax and guidelines.  
     * @author:      Hyrum D. Carroll
     * @version:     0.2 (September 14, 2019)
     */
    public class VariablesExercise {
        public static void main (String[] args) {
    
    	int peopleInAmerica = 325,782,231;  /* Source: United States Census Bureau */
    
    	double gross_domestic_product = 19.39e12;  //  USD (2017) Source: Bureau of Labor Statistics
    	double unemploymentRate = 4.0%;  // (Feb 2019) Source: Bureau of Labor Statistics
    
    	int gdppc = gross_domestic_product/peopleInAmerica;
    
    	System.out.println("The gross domestic product per person (in the United States of America) is " + gdppc);
        }
    }
    
  2. What will be displayed and why?
    public static boolean echo( int num){
        System.out.println("\techo(" + num + ")");
        return true;
    }
    
    public static void main (String[] args) {
    
        System.out.println("false &&");
    
        if( false && echo( 0 ) ){
            System.out.println( "\tfalse && echo(0)");
        }else if( true && echo( 1 ) ){
            System.out.println( "\ttrue && echo(1)");
        }else{
            System.out.println( "\telse");
        }
    
        System.out.println();
        System.out.println("true &&");
        if( true && echo( 2 ) ){
            System.out.println( "\ttrue && echo(2)");
        }else if( false && echo( 3 ) ){
            System.out.println( "\tfalse && echo(3)");
        }else{
            System.out.println( "\telse");
        }
    
    
        System.out.println();
        System.out.println("false ||");
        if( false || echo( 3 ) ){
            System.out.println( "\tfalse || echo(3)");
        }else if( true || echo( 4 ) ){
            System.out.println( "\ttrue || echo(4)");
        }else{
            System.out.println( "\telse");
        }
    
        System.out.println();
        System.out.println("true ||");
        if( true || echo( 1 ) ){
            System.out.println( "\ttrue || echo(1)");
        }else if( false || echo( 0 ) ){
            System.out.println( "\tfalse || echo(0)");
        }else{
            System.out.println( "\telse");
        }
    
    }
    
  3. In Java, rounding to 1 decimal place is often written as:
    Math.round( number * 10.0 ) / 10.0;
    Could it be written as:
    Math.round( number * 10 ) / 10.0;
    What if number were an int? A float? A double?
  4. Declare a constant (primitive) variable with the value of 100 (using common coding conventions). What needs to be added to make it a class constant?