Decisions 25.0
5.1Comparison between String values in Java
  1. Primitive Data-Type Variable: To begin with, after the declaration and initialization of a Primitive data-type variable; in a bid to access its (content) value, the (Primitive) variable identifier directly links to and returns the value which the variable had been initialized or updated with. Variable-Identifier —→ Data-Value
  2. Non-Primitive (or Derived) Data-Type Variable: However, after the declaration and initialization of a Non-Primitive data-type variable; in a bid to access its (content) value, the (Non-Primitive) variable identifier directly points to an object-reference which, in turn, links to and returns the value that the variable had been initialized or updated with. Variable-Identifier —→ Object-Reference —→ Data-Value

Since a String is essentially a Non-Primitive data type; therefore, variables declared and initialized as String data-type basically follow the aforementioned pattern for referencing and accessing contents stored in a Non-Primitive (or Derived) data-type variable: Variable-Identifier —→ Object-Reference —→ Data-Value.

In that regard, it is important to mention that a String data-type variable (in Java programming) can be declared and initialized via any of the following two (2) approaches, viz:
  1. String Literal (Primitive-like) approach: This involves declaring and initializing a String data-type variable using the standard or syntax employed for Primitive data types; for example: String str1 = "Programming Lessons";. Since a String is a Non-Primitive data type, this approach adhers to the form: Variable-Identifier —→ Object-Reference —→ Data-Value. Thus, the content or value of this String data-type variable is stored (by the Java Virtual Machine) in a special segment of primary memory called the "String (Constant) Pool" for the sake of re-usability. If another String data-type variable were to be declared and initialized still with employing the String Literal (or Primitive-like) approach, for example: String str2 = "Programming Lessons"; then the Java Virtual Machine will, first of all, check inside the "String (Constant) Pool" to find out whether the content or value of this new String variable, str2, already exists in the "String (Constant) Pool". Hence, if the content or value of str2 does exist exactly same in the "String (Constant) Pool"; the Java Virtual Machine points str2 to the same object-reference as the previous variable, str1, which both bear exactly same content. Otherwise, if the content/value of a new String data-type variable does not exist exactly same in the "String (Constant) Pool"; then this content will be introduced as a new value into the "String (Constant) Pool".
    String Literal (Primitive-like) approach
    Caption: String Literal (Primitive-like) approach

  2. new Keyword (OOP-like) approach: This involves declaring and initializing a String data-type variable using the standard syntax employed for instantiating an object of a class-block in Java programming. An example is: String str1 = new String("Programming Lessons");. Again, since a String is a Non-Primitive data type, this approach adhers to the form: Variable-Identifier —→ Object-Reference —→ Data-Value. So, the content or value of this String data-type variable is stored (by the Java Virtual Machine) in a segment of primary memory called the "Heap Memory". If another String data-type variable were to be declared and initialized still with employing the new Keyword (or OOP-like) approach, for example: String str2 = new String("Programming Lessons"); then the Java Virtual Machine is forced to create a new/unique content or value with respect to this new String variable, str2, irrespective of whether this content/value already exists in the "Heap Memory". Hence, just as the name implies, the new keyword technically creates a new/unique/distinct object-reference which is associated with a String data-type variable that is created via the new Keyword (or OOP-like) approach. In other words, when employing this approach, every String data-type variable that is declared and initialized always points to a unique/distinct object-reference which can either link to contents bearing exactly the same value or different values.
    new Keyword (OOP-like) approach
    Caption: new Keyword (OOP-like) approach

Consequently, it is quite important to note that when comparing the contents or values of any two (2) variables using the Equal-To (==) operator; this operator can only view/reference just one-step ahead. Hence, using the Equal-To (==) operator to compare any two (2) Primitive data-type variables will always compare the actual data contents/values of these variables. However, using the Equal-To (==) operator to compare any two (2) Non-Primitive data-type variables will always compare the object-references pointed to by these variables. Thus, using the String data-type variables created in the previous example, comparing str1 and str2 using the Equal-To (==) operator will always make a comparison with respect to the object-references of str1 and str2. Therefore, employing the equals() method is the most effective approach for comparing the actual data contents or values of any two (2) String data-type variables.
using equals operator to compare Primitive data-type variables
Caption: Using the == operator to compare Primitive data-type variables


using equals operator to compare Non-Primitive data-type variables
Caption: Using the == operator and the equals() method to compare Non-Primitive data-type variables


/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		String str1 = "Programming Lessons"; //Primitive-like approach
        String str2 = "Programming Lessons"; //Primitive-like approach
        
        if (str1 == str2) { //returns TRUE: Object-Reference comparision
        	System.out.println("== operator: Same object-reference {1,2}");
        }
        
        if (str1.equals(str2)) { //returns TRUE: Data-Value comparision
        	System.out.println("equals() method: Same content {1,2}");
        }
        
        
        String str3 = new String("Programming Lessons"); //OOP-like approach
        String str4 = new String("Programming Lessons"); //OOP-like approach
        
        if (str3 == str4) { //returns FALSE: Object-Reference comparision
        	System.out.println("== operator: Same object-reference {3,4}");
        }
        
        if (str3.equals(str4)) { //returns TRUE: Data-Value comparision
        	System.out.println("equals() method: Same content {3,4}");
        }
        
        
        String str5 = "Programming Lessons"; //Primitive-like approach
        String str6 = str5.substring(0, 11); //OOP-like approach
        
        if (str6 == "Programming") { //returns FALSE: Object-Reference comparision
        	System.out.println("== operator: Same object-reference {6,'...'}");
        }
        
        if (str5.substring(0, 11) == str5.substring(0, 11)) { //returns FALSE: Object-Reference comparision
        	System.out.println("== operator: Same object-reference {6,6}");
        }
                
        if (str6.equals("Programming")) { //returns TRUE: Data-Value comparision
        	System.out.println("equals() method: Same content {6,'...'}");
        }
	}
	
} 
Code Snippet: Using the == operator and the equals() method to compare String (Non-Primitive) data-type variables

Notice that in the code snippet above, the equals() method remains the best approach which always compares the actual data values (not object-references) of two (2) String data-type variables.
  1. equals() method: This is a case-sensitive approach for comparing the actual data values or contents of any two (2) Non-Primitive data-type variables; for example: String data-type, etc. This method returns a boolean value, of either true or false, dependent on whether the compared data values are equal or not equal, respectively.
  2. equalsIgnoreCase() method: This is the case-insensitive approach with respect to the equals() method.
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		String str7 = "programming lessons"; //Primitive-like approach
        String str8 = new String("PrOgrAmMiNg LEsSoNs"); //OOP-like approach
        
        boolean retVal1 = str7.equals(str8);
        System.out.println(retVal1); //PRINT: false
        
        boolean retVal2 = str7.equalsIgnoreCase(str8);
        System.out.println(retVal2); //PRINT: true
        
        boolean retVal3 = str7.equalsIgnoreCase("PrOgrAmMiNg");
        System.out.println(retVal3); //PRINT: false
        
        if (str7.equals(str8)) { //returns FALSE
        	System.out.println("equals() method: Same content");
        }
        else if (str7.equalsIgnoreCase(str8)) { //returns TRUE
        	System.out.println("equalsIgnoreCase() method: Same content");
        }
        else { //returns FALSE
        	System.out.println("equals() and equalsIgnoreCase() methods: Different content");
        }
        
        /* Testing for "empty" String value */
        String str9 = "";
        
        if (str7.equals("")) {
        	System.out.println("equals() method: Variable 'str7' is empty!");
        }
        if (str8.equalsIgnoreCase("")) {
        	System.out.println("equalsIgnoreCase() method: Variable 'str8' is empty!");
        }
        
        if (str9.equals("")) {
        	System.out.println("equals() method: Variable 'str9' is empty!");
        }
        if (str9.equalsIgnoreCase("")) {
        	System.out.println("equalsIgnoreCase() method: Variable 'str9' is empty!");
        }
        else if (str9.equalsIgnoreCase("") == false) {
        	System.out.println("equalsIgnoreCase() method: Variable 'str9' is not empty");
        }
        
        if (str9.length() == 0) {
        	System.out.println("length() method: Variable 'str9' is empty!");
        }
        else if (str9.length() != 0) {
        	System.out.println("length() method: Variable 'str9' is not empty");
        }
	}
	
} 
Code Snippet: Comparing the data values or contents of String data-type variables

  1. compareTo() method: This is a case-sensitive approach for comparing the actual data values or contents of any two (2) String data-type variables based on the Unicode/ASCII value of each character that is present in both String values. Thus, this method returns zero (x == 0) if the two (2) String values are exactly same; otherwise, it returns a non-zero (x != 0).
  2. compareToIgnoreCase() method: This is the case-insensitive variant of the compareTo() method.
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		String str7 = "programming lessons"; //Primitive-like approach
        String str8 = new String("PrOgrAmMiNg LEsSoNs"); //OOP-like approach
        
        int compRes1 = str7.compareTo(str8);
        System.out.println(compRes1); //PRINT: 32
        
        int compRes2 = str7.compareToIgnoreCase(str8);
        System.out.println(compRes2); //PRINT: 0
        
        int compRes3 = "PrOgrAmMiNg".compareToIgnoreCase(str7);
        System.out.println(compRes3); //PRINT: -8
        
        if (str7.compareTo(str8) == 0) { //returns FALSE
        	System.out.println("compareTo() method: Same content");
        }
        else if (str7.compareToIgnoreCase(str8) == 0) { //returns TRUE
        	System.out.println("compareToIgnoreCase() method: Same content");
        }
        else { //returns FALSE
        	System.out.println("compareTo() and compareToIgnoreCase() methods: Different content");
        }
	}
	
} 
Code Snippet: Comparing the data values or contents of String values using the compareTo() method and the compareToIgnoreCase() method



5.2Variants of the switch {} Statement
Just like the if {} statement, the switch {} statement is yet another construct in Java programming which we can employ towards implementing decision logic and scenarios in a Java program. To this end, the switch {} statement possesses the following characteristics, viz:
  1. With reference to a decision variable, a switch {} statement can possess one or more case blocks.
  2. Each case block must be used to capture an explicitly stated value with reference to the decision variable, and not a range of values denoted via relational operator(s).
  3. Each case block may be delimited with an optional break keyword which prevents the flow of control from entering into another case block after a case-block match has been found.
  4. The switch {} statement is considered as a fall-through construct such that if the optional break keyword is omitted from a case block, then all case blocks after the first case-block match is executed.
  5. Also, a switch {} statement may possess an optional default block; and this block serves as a "catch-all" block for all values (of the decision variable) that were not explicitly specified by a case block.
  6. A switch {} statement may be nested within another switch {} statement depending on the programming and/or implementation logic requirement(s).

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		int decsnVar;
        
        decsnVar = 53;
        /* 'case' blocks delimited with 'break' keywords */
        switch (decsnVar) {
	        case 50: //if decsnVar == 50
	        	System.out.println("Grade may be: D-");
	        	break;
	        case 53: //if decsnVar == 53 (this is outputted)
	        	System.out.println("Grade may be: D");
	        	break;
	        case 57: //if decsnVar == 57
	        	System.out.println("Grade may be: D+");
	        	break;
	        default: //if decsnVar != 50 and 53 and 57
	        	System.out.println("Grade may be above or below: D");
        }
        
        decsnVar = 52;
        /* 'case' blocks without 'break' keywords */
        switch (decsnVar) {
	        case 48: //if decsnVar == 48
	        	System.out.println("Grade may be: D-");
	        case 52: //if decsnVar == 52 (this is outputted)
	        	System.out.println("Grade may be: D");
	        case 58: //if decsnVar == 58 (this is outputted)
	        	System.out.println("Grade may be: D+");
	        default: //if decsnVar != 48 and 52 and 58 (this is outputted)
	        	System.out.println("Grade may be above or below: D");
	    }
	}
	
} 
Code Snippet 1: switch {} statement implementation in Java

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		String decsnGrd;
        
        decsnGrd = "Grade: C";
        /* 'case' blocks delimited with 'break' keywords */
        switch (decsnGrd) {
	        case "Grade: C-": //if decsnGrd == "Grade: C-"
	        	System.out.println("Score may be within: 60 - 62");
	        	break;
	        case "Grade: C": //if decsnGrd == "Grade: C" (this is outputted)
	        	System.out.println("Score may be within: 63 - 66");
	        	break;
	        case "Grade: C+": //if decsnGrd == "Grade: C+"
	        	System.out.println("Score may be within: 67 - 69");
	        	break;
	        default: //if decsnGrd != "Grade: C-" and "Grade: C" and "Grade: C+"
	        	System.out.println("Score may be above 69 or below 60");
        }
        
        decsnGrd = "Grade: C";
        /* 'case' blocks without 'break' keywords */
        switch (decsnGrd) {
	        case "Grade: C-": //if decsnGrd == "Grade: C-"
	        	System.out.println("Score may be within: 60 - 62");
	        case "Grade: C": //if decsnGrd == "Grade: C" (this is outputted)
	        	System.out.println("Score may be within: 63 - 66");
	        case "Grade: C+": //if decsnGrd == "Grade: C+" (this is outputted)
	        	System.out.println("Score may be within: 67 - 69");
	        default: //if decsnGrd != "Grade: C-" and "Grade: C" and "Grade: C+" (this is outputted)
	        	System.out.println("Score may be above 69 or below 60");
        }
	}
	
} 
Code Snippet 2: switch {} statement implementation in Java

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		String province = "Quebec", city = "Montreal";
        
        //Parent Nest: switch() statement
        switch (province) {
	        case "Alberta":
	        	//Child Nest: switch() statement
	            switch (city) {
	    	        case "Edmonton":
	    	        	System.out.println("Your city's Mayor is: Amarjeet Sohi");
	    	        	break;
	    	        case "Calgary":
	    	        	System.out.println("Your city's Mayor is: Jyoti Gondek");
	    	        	break;
	    	        default:
	    	        	System.out.println("Your province's Premier is: Danielle Smith");
	            }
	        	break;
	        case "Quebec":
	        	//Child Nest: switch() statement
	            switch (city) {
	    	        case "Montreal":
	    	        	System.out.println("Your city's Mayor is: Valerie Plante");
	    	        	break;
	    	        case "Lasalle":
	    	        	System.out.println("Your city's Mayor is: Crystal Meloche");
	    	        	break;
	    	        default:
	    	        	System.out.println("Your province's Premier is: Fran├žois Legault");
	            }
	        	break;
	        default:
	        	System.out.println("Canada's current Prime Minister is: Justin Trudeau");
        }
	}
	
}
Code Snippet 3: switch {} statement implementation in Java



5.3exit() method in Java
The exit() method is a method that is defined and resident in the System class block (packaged within the java.lang package), and which is responsible for terminating the current execution of a Java program whenever and/or wherever the exit() keyword is encountered within a Java program (or source code). Therefore, this method possesses the following characteristics, viz:
  1. Its syntax is as follows: System.exit(int_error_code);
  2. The int error code passed as an argument to this method acts as an exit or termination code for the Java program.
  3. A zero (int_error_code == 0) exit-error code is usually used by programmers to indicate a normal program termination.
  4. A non-zero (int_error_code != 0) exit-error code is usually used to denote an abnormal program termination.

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		int intVar = 45;
        if (intVar > 10) {
        	System.out.println("Got here: 1");
        	System.exit(0); //Program terminates and exits at this point
        	System.out.println("Never got here: 2");
        	System.out.println("Never got here: 3");
        }
    	System.out.println("Never got out: 4");
	}
	
} 
Code Snippet 1: System.exit(int_error_code) method in Java program

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		int intVar = 40;
        switch (intVar) {
	        case 40:
	        	System.out.println("Got here: 1");
	        	System.exit(40); //Program terminates and exits at this point
	        	System.out.println("Never got here: 2");
	        case 50:
	        	System.out.println("Never got here: 3");
	        	System.out.println("Never got here: 4");
	        case 60:
	        	System.out.println("Never got here: 5");
	        default:
	        	System.out.println("Never got here: 6");
	    }
    	System.out.println("Never got out: 7");
	}
	
} 
Code Snippet 2: System.exit(int_error_code) method in Java program



5.4"Dangling-else" Problem in an if-else {} Statement
"Dangling-else" problem
  1. Inasmuch as the curly parantheses, {...}, are not compulsory for an if-else {} statement; it is quite important to include them so as to avoid the "Dangling-else" problem.
  2. If the curly parantheses, {...}, are omitted in a nested if-else {} statement; then the else {} block (of the outermost if-else {} statement) gets associated with the nearest if {} block above it.
  3. The aforementioned "Dangling-else" problem can simply be resolved via enclosing each block of an if {}, if-else {}, or if-else-if {} statement with the appropriate curly parantheses, {...}.
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		double rentCost = 1000;
        
        /* if {} and if-else {} statements with the "Dangling-else" problem */
        if (rentCost > 600)
        	if (rentCost == 800) //if {} statement
        		System.out.println("Rental cost is now: $800");
        else
        	/* 
        	 Prints out the line below despite the fact that the program logic
        	 is not supposed to flow into this "else {}" block.
        	 */
        	System.out.println("Rental cost is <= $600");
	}
	
} 
Code Snippet: "Dangling-else" problem in Java

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		double rentCost = 1000;
		
		/* if {} and if-else {} statements without the "Dangling-else" problem */
        if (rentCost > 600) {
        	if (rentCost == 800) {//if {} statement
        		System.out.println("Rental cost is now: $800");
        	}
        	//Nothing gets printed to the screen since no "else {}" block is associated with the "if {}" block above
        }
        else {
        	//Program logic never flows into this "else {}" block.
        	System.out.println("Rental cost is <= $600");
        }
	}
	
} 
Code Snippet: Refixed program eliminating the "Dangling-else" problem



5.5Enumerated Data-Types in Java
This is a special type of data type in Java programming that defines a variable which is comprised of a fixed list (or set) of identifiers; and these identifiers serve as direct values of this variable. The enum data type possesses the following characteristics, viz:
  1. The declaration/initialization syntax is: enum <variableIdentifier> {valueIdentifier_1, ..., valueIdentifier_n}
  2. The values of the enum data-type variable, which are enclosed within the curly parantheses {...}, must be identifiers that conform to the standard rule for defining identifier(s) in Java.
  3. Access to each value of the enum data type is via the dot-notation syntax as follows: <variableIdentifier>.<valueIdentifier_n>
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
  
public class Decisions2 {
	
	public static void main(String[] args) {
		enum months {January, February, March, May, June, July, August, September, October, November, December}
        enum letterGrades {A, B, C, D, E, F}
        
        System.out.println("A random month of the year is: " + months.August);
        System.out.println("My grade this term is: " + letterGrades.A);
	}
	
} 
Code Snippet: enum data type in Java



5.6De Morgan's Laws with respect to Conjunction (&&) and Disjunction (||) in Java
De Morgan's Laws with respect to Conjunction (&&)
  1. Law: !(A && B) ≣ !A || !B
  2. Code Snippet: if (!(1 <= varTemp && varTemp <= 100)) {...}
  3. Equivalence to Code Snippet: if (!(1 <= varTemp) || !(varTemp <= 100)) {...}

De Morgan's Laws with respect to Disjunction (||)
  1. Law: !(A || B) ≣ !A && !B
  2. Code Snippet: if (!(1 <= varTemp || varTemp <= 100)) {...}
  3. Equivalence to Code Snippet: if (!(1 <= varTemp) && !(varTemp <= 100)) {...}



5.7Validation of Data Input in Java Programming
In the previous chapter, we had already discussed about quite a couple of user-input (extraction) methods, which are already prefined in the Scanner class, that can be employed to extract or request input(s) from users. In this regard, and for each of the user-input (extraction) methods discussed in the previous chapter, there exist a corresponding user-input validation method. Each of these validation methods is used to ensure and validate that only an input of the stipulated data type is returned to the corresponding user-input (extraction) method. Thus, the table below displays a list of these user-input validation methods.

User-Input Method
Extraction method() Validation method()
nextByte() hasNextByte()
nextShort() hasNextShort()
nextInt() hasNextInt()
nextLong() hasNextLong()
nextFloat() hasNextFloat()
nextDouble() hasNextDouble()
nextBoolean() hasNextBoolean()
next() hasNext()
nextLine() hasNextLine()

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
 
import java.util.Scanner; 
  
public class Decisions2 {
	
	public static void main(String[] args) {
		// Create an instance-variable of the "Scanner" class.
        Scanner usrInput = new Scanner(System.in);
		
		//Prompt user for inputs
		System.out.print("Please enter an Integer: ");

		//Comparison logic
		if (usrInput.hasNextInt()) {
			int i1 = usrInput.nextInt();
			
			System.out.println("Good: " + i1 + " is a valid integer.");
		}
		else {
			System.out.println("Error: Input is not a valid 'integer' data type.");
		}

		//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
        usrInput.close();
	}
	
} 
Code Snippet: User-input validation method with regard to hasNextInt() method

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Decisions 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */
 
import java.util.Scanner; 
  
public class Decisions2 {
	
	public static void main(String[] args) {
		// Create an instance-variable of the "Scanner" class.
        Scanner usrInput = new Scanner(System.in);
        
        //Declaration of variables
		double d1, d2;
		
		//Prompt user for inputs
		System.out.print("Please enter two (2) numbers separated by a space character: ");

		//Comparison logic
		if (usrInput.hasNextDouble()) {
			d1 = usrInput.nextDouble();
			
			if (usrInput.hasNextDouble()) {
				d2 = usrInput.nextDouble();
				
				if (d1 == d2) {
					System.out.println(d1 + " is equal to " + d2);
				}
				else {
					System.out.println((d1 > d2) ? (d1 + " is greater than " + d2) : (d1 + " is lesser than " + d2));
				}
			}
			else {
				System.out.println("Error: Number-2 is not a valid 'double' data type.");
			}
		}
		else {
			System.out.println("Error: Number-1 is not a valid 'double' data type.");
		}
		
        //Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
        usrInput.close();
	}
	
} 
Code Snippet: User-input validation method with regard to hasNextDouble() method



5.8Practice Exercise
  1. What is the expected output with reference to the code snippet below?
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Decisions 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
     
    import java.util.Scanner; 
      
    public class Decisions2 {
    	
    	public static void main(String[] args) {
    		Scanner usrInput = new Scanner(System.in);
    		Integer v1;
    		
    		System.out.print("Please enter an Integer: ");
    		
    		if (usrInput.hasNextInt()) {
    			int i1 = usrInput.nextInt(); //ENTER: 10
    			
    			if (i1 < 100); {
    				v1 = i1;
    			}		
    			if (i1 > 100); {
    				v1 = i1 * 2;
    			}
    			if (i1 == 100); {
    				v1 = i1 * 3;
    			}
    			
    			System.out.println("The processed output value is: " + v1);
    		}
    		else {
    			System.out.println("Error: Input is not a valid 'integer' data type.");
    		}
    
    		usrInput.close();
    	}
    	
    } 
    

  2. What is the expected output with reference to the code snippet below?
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Decisions 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
     
    import java.util.Scanner; 
      
    public class Decisions2 {
    	
    	public static void main(String[] args) {
    		Scanner usrInput = new Scanner(System.in);
    		Integer v1;
    		
    		System.out.print("Please enter an Integer: ");
    		
    		if (usrInput.hasNextInt()) {
    			int i1 = usrInput.nextInt(); //ENTER: 5
    			
    			if (i1 < 100); {
    				v1 = i1;
    			}		
    			if (i1 > 100); {
    				v1 = i1 * 2;
    			}
    			if (i1 == 100) {
    				v1 = i1 * 3;
    			}
    			
    			System.out.println("The processed output value is: " + v1);
    		}
    		else {
    			System.out.println("Error: Input is not a valid 'integer' data type.");
    		}
    
    		usrInput.close();
    	}
    	
    } 
    

  3. Given the code snippet below, what will be the appropriate approach to test if a user entered the value: 75?
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Decisions 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    import java.util.Scanner; 
    
    Scanner usrInput = new Scanner(System.in);
    
    System.out.print("Please enter an Integer: ");
    String i1 = usrInput.next(); //ENTER: 75
    
    • if (i1 == "75") {...}
    • if (i1 = "75") {...}
    • if (i1.equals("75")) {...}
    • if (i1.compareTo("75")) {...}
    • None of the above

  4. TRUE or FALSE: In Java programming, the switch {} statement can employ relational operator(s) within its case block with respect to the value of a decision variable?

  5. TRUE or FALSE: In Java programming, the switch {} statement is not a fall-through construct?

  6. What is the expected output with reference to the code snippet below?
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Decisions 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
     
    import java.util.Scanner; 
      
    public class Decisions2 {
    	
    	public static void main(String[] args) {
    		Scanner usrInput = new Scanner(System.in);
    		int v1;
    		
    		System.out.print("Please enter an Integer: ");
    		
    		if (usrInput.hasNextInt()) {
    			int i1 = usrInput.nextInt(); //ENTER: 55
    			
    			if (i1 < 100) {
    				v1 = i1++;
    			}		
    			if (i1 > 100) {
    				v1 = i1--;
    			}
    			else {
    				v1 = i1++ + ++i1;
    			}
    			
    			System.out.println("The processed output value is: " + v1);
    		}
    		else {
    			System.out.println("Error: Input is not a valid 'integer' data type.");
    		}
    
    		usrInput.close();
    	}
    	
    } 
    

  7. What is the expected output with reference to the code snippet below?
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Decisions 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
     
    import java.util.Scanner; 
      
    public class Decisions2 {
    	
    	public static void main(String[] args) {
    		Scanner usrInput = new Scanner(System.in);
    		int v1;
    		
    		System.out.print("Please enter an Integer: ");
    		
    		if (usrInput.hasNextInt()) {
    			int i1 = usrInput.nextInt(); //ENTER: 75
    			
    			if (i1 < 100) {
    				v1 = i1++;
    			}		
    			if (i1 > 100); {
    				v1 = i1-- - 6;
    			}
    			if (i1 == 100) {
    				v1 = i1++ + ++i1;
    			}
    			
    			System.out.println("The processed output value is: " + v1);
    		}
    		else {
    			System.out.println("Error: Input is not a valid 'integer' data type.");
    		}
    	
    		usrInput.close();
    	}
    	
    } 
    

  8. Which of the following if {...} statements, with regard to the code snippet below, will resolve to or return TRUE?
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Decisions 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    int accStatus = 0;
    boolean loginStatus = false;
    
    • if (accStatus) {...}
    • if (accStatus == "false") {...}
    • if (accStatus = 0) {...}
    • if (loginStatus) {...}
    • if (loginStatus == false) {...}

  9. TRUE or FALSE: In Java programming, a switch {} statement can be nested (as a child statement) within another switch {} statement?

Sponsored Ads