Java Language Elements Exercises

  < Previous  Next >
  1. Locate examples the following terms in the Java code below:
    1. Identifier
    2. Variables
    3. Variable declarations
    4. Variable initialization
    5. Data type
    6. Primitive data type
    7. Keywords
    8. Reserved literal
    9. Assignment statement
    10. Literal
    11. Operator
    12. Multi-line comment
    13. Single line comment
    /* Description: Calculates the probability that two people in a group will have
     *              the same birthday.
     * Author:      Hyrum D. Carroll
     * Date:        February 4, 2019
     */
    import java.util.Scanner;
    
    public class ProbabiltySameBirthday {
       public static void main (String[] args) {
           final int NUM_DAYS_YEAR = 366;  // includes leap day, February 29
           Scanner stdinScanner = new Scanner(System.in);
           int numPeople;  // n
    
           // Get n from the user
           System.out.print("Please enter the number of people in the room: ");
           numPeople = stdinScanner.nextInt();
    
           /* probability that two people do NOT share a birthday:
    	  = 366! / (366^n * (366 - n)!)  (where n = numPeople)
              = 366*365*364*...*(366-n) / 366^n (because the denominator factorial
    	                                     cancels the part of the numerator
    					     factorial)
    	*/
    
           // Calculate the numerator: 366*365*364*...*(366-n)
           double numerator = 1;
           for( int i = NUM_DAYS_YEAR; i > (NUM_DAYS_YEAR - numPeople); --i){
    	   numerator *= i;
           }
           // System.out.println("DEBUGGING: Numerator: " + numerator);
    
           // Calculate the denominator: 366^n
           double denominator;
           denominator = Math.pow( NUM_DAYS_YEAR, numPeople);
           // System.out.println("DEBUGGING: Denominator: " + denominator);
    
           // Calculate the probability of two people SHARING a birthday 
           double probability = (1.0 - numerator / denominator) * 100.0;
    
           // Display the result
           System.out.println("For " + numPeople + ", there's a " + probability + "% chance that two or more people share a birthday!");
       }
    }
    
  2. What are the two rules for naming identifiers (for example, variables)?
  3. List three examples of valid identifiers:
  4. List three examples of invalid identifiers:
  5. Java (currently) has 51 (active) keywords and 3 reserved words. We will be covering the underlined ones in this course. Research 3 keywords that we're going to use this semester and explain how they're used to someone else.
    Keywords: abstract   assert   boolean   break   byte   case   catch   char   class   continue   default   do   double   else   enum   exports   extends   final   finally   float   for   if   implements   import   instanceof   int   interface   long   module   native   new   package   private   protected   public   requires   return   short   static   strictfp   super   switch   synchronized   this   throw   throws   transient   try   void   volatile   while  
    Reserved literals: false   null   true  
  6. In general, there are two style guidelines for naming identifiers:
    1. words_separated_by_underscores
    2. wordsWithFirstLetterCapitalized
    Tell someone which one are you going to use.
  7. List the five compound assignment operators in Java:
  8. In the following code, identify invalid code (syntax errors):
    /** 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);
        }
    }
    
  9. Which of the following primitive data types store their contents as a number:
    • boolean
    • char
    • int
    • double
  10. Discuss with someone have many bytes does an int and a double require in Java. Namely, does it vary depending on the machine's architecture or is it predictable and fixed?
  11. What is the range of possible values for the following primitive data types:
    • boolean
    • char
    • int
    • long
    • float
    • double
  12. Body Mass Index (BMI) is calculated as 703 * weight_in_lbs / height_in_inches2. What does the following code display and why?
    final int BMI_SCALAR = 703;
    int weight = 10; // pounds
    int height = 20; // inches
    int calculation = weight / (height * height);
    double bmi = BMI_SCALAR * calculation;
    System.out.println( "BMI: " + bmi );
  13. In Java, what's a promotion? What are the rules for promotion?
  14. What does the following display and why?
    int counter = 0;
    if( counter++ != 1 ){
        System.out.println("counter: " + counter );
    }else{
        System.out.println("increment operators are cool!");
    }
  15. Write the last two statements as an equivalent single Java statement:
    Scanner stdin = new Scanner( System.in );
    int j = stdin.nextInt();
    int k = stdin.nextInt();
    
    k = k + 1;
    j = k;
  16. Write the last two statements as an equivalent single Java statement:
    Scanner stdin = new Scanner( System.in );
    int j = stdin.nextInt();
    int k = stdin.nextInt();
    
    j = k;
    k = k + 1;
  17. Declare a constant (primitive) variable with the value of 100 (using common coding conventions).