Java Conditionals Test Flashcards

(55 cards)

1
Q

What is the if statement?

A

The “if” statement is used to create a decision structure, which allows a program to have more than one path of execution. The “if” statement causes one or more statements to execute only when a boolean expression is true.

In a decision structure’s simplest form, a specific action is taken only when a condition exists. If the condition does not exist, the action is not performed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is one way to code with the if statement?

A

One way to code a decision structure in Java is with the if statement. Here is the general format of the if statement:

if (BooLeanExpression)
statement;

The if statement is simple in the way it works:

The BooleanExpression that appears inside the parentheses must be a boolean expression.

A boolean expression is one that is either true or false. If the boolean expression is true, the very next statement is executed. Otherwise, it is skipped.

The statement is conditionally executed because it executes only under the condition that the expression in the parentheses is true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is used in an boolean expression?

A

Typically, the boolean expression that is tested by an if statement is formed with a relational operator.

A relational operator determines whether a specific relationship exists between two values. For example, the greater than operator (>) determines whether one value is greater than another. The equal to operator (==) determines whether two values are equal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the relational operators?

A

> Greater Than
< Less Than
= Greater Than or Equal to
<= Less Than or equal to
== Equal to
!= Not equal to

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does enclosing a group of statements inside braces create?

A

The previous examples of the if statement conditionally execute a single statement. The if statement can also conditionally execute a group of statements, as long as they are enclosed in a set of braces. Enclosing a group of statements inside braces creates a block of statements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does this code execute?

double sales = 55000, bonus, commissionRate, daysOff = 0;

        if (sales > 50000)
        {
            bonus = 500.0;
            commissionRate = 0.12;
            daysOff += 1;
        }
A

If sales is greater than 50,000, this code will execute all three of the statements inside these braces, in the order they appear.

If the braces are accidentally left out, however, the if statement conditionally executes only the very next statement. In this case, only “bonus = 500.0” will execute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a flag?

A

A flag is a boolean variable that signals when some condition exists in the program. When the flag variable is set to false, it indicates the condition does not yet exist. When the flag variable is set to true, it means the condition exists.

Flag variable — boolean data type and we have to monitor it to see if the variables is holding true or false
Used to signal if something else is true or not

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is used to test character data?

A

You can use the relational operators to test character data as well as numbers. Example 1 uses the == operator to compare it to the character ‘A’:

    String userInput;
    char ch;
    System.out.println("Please enter a character: ");
    userInput = keyboard.nextLine();
    ch = userInput.charAt(0);

Example 1
if (ch == ‘N’)
System.out.println(“The letter is N.”);

The != operator can also be used with characters to test for inequality.

You can also use the >, <, >=”, and <= operators to compare characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do computers store charcaters?

A

Computers do not actually store characters, such as A, B, C, and so forth, in memory.

Instead, they store numeric codes that represent the characters. Java uses Unicode, which is a set of numbers that represents all the letters of the alphabet (both lowercase and uppercase), the printable digits 0 through 9, punctuation symbols, and special characters.

When a character is stored in memory, it is actually the Unicode number that is stored.

When the computer is instructed to print the value on the screen, it displays the character that corresponds with the numeric code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is unicode?

A

Unicode is an international encoding system that is extensive enough to represent all the characters of all the world’s alphabets.

In Unicode, letters are arranged in alphabetic order. Because ‘A’ comes before ‘B’, the numeric code for the character ‘A’ is less than the code for the character ‘B’.

In Unicode, the uppercase letters come before the lowercase letters, so the numeric code for ‘A’ (65) is less than the numeric code for ‘a’ (97). In addition, the space character (code 32) comes before all the alphabetic characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the if-else statement?

A

The if-else statement will execute one group of statements if its boolean expression is true, or another group if its boolean expression is false.

Like the if statement, a boolean expression is evaluated.

If the expression is true, a statement or block of statements is executed.

If the expression is false, however, a separate group of statements is executed.

The if-else statement is an expansion of the if statement.
See the following format:

                if (BooleanExpression)
                        Statement or block
                else
                        statement or block

The first one that the else if statement is true will print the block of code underneath and won’t test the rest – ignore the rest of the code after
If you take out the else from else if – can print out multiple because multiple statements can be true
else if – exclusive
Only one trailing else possible with else if statements – if none of the above statements are found to be true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What happens when division by zero in Java occurs?

A

The program below uses the if-else statement to handle a classic programming problem: division by zero. In Java, a program crashes when it divides an integer by 0. When a floating-point value is divided by 0, the program doesn’t crash. Instead, the special value “Infinity” is produced as the result of the division.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does this code do:

double number1, number2; // Division operands
double quotient; // Result of division

        // Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(System.in);
       
        // Get the first number.
        System.out.print("Enter a number: " );
        number1 = keyboard.nextDouble();
       
        // Get the second number.
        System.out.print("Enter another number: ");
        number2 = keyboard.nextDouble();
       
        if (number2 == 0)
            {
                System.out.println("Division by zero is not possible.");
                System.out.println("Please run the program again and ");
                System.out.println("enter a number other than zero.");
            }
        else
            {
                quotient = number1 / number2;
                System.out.print("The quotient of " + number1);
                System.out.print(" divided by " + number2);
                System.out.println(" is " + quotient);
            }
A

The value of number2 is tested before the division is performed. If the user enters 0, the block of statements controlled by the if clause executes, displaying a message that indicates the program cannot perform division by zero. Otherwise, the else clause takes control, which divides number1 by number2 and displays the result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are nested if statements?

A

To test more than one condition, an if statement can be nested inside another if statement. Sometimes an if statement must be nested inside another if statement.

For example, consider a banking program that determines whether a bank customer qualifies for a special interest rate on a loan. To qualify, two conditions must exist: (1) the customer’s salary must be at least $30,000, and (2) the customer must have held his or her current job for at least two years.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How would you code asks the user to enter a numeric test score and displays a letter grade for the score. The program uses nested decision structures to determine the grade.

A

int testScore; // Numeric test score
String input; // To hold the user’s input

    // Get the numeric test score.
    input = JOptionPane.showInputDialog("Enter your numeric " +
                     "test score and I will tell you the grade: ");
    testScore = Integer.parseInt(input);
   
    // Display the grade.
    if (testScore < 60)
    {
        JOptionPane.showMessageDialog(null, "Your grade is F.");
    }
    else
    {
        if (testScore < 70)
        {
            JOptionPane.showMessageDialog(null, "Your grade is D.");
        }
        else
        {
            if (testScore < 80)
            {
                JOptionPane.showMessageDialog(null, "Your grade is C.");
            }
            else
            {
                if (testScore < 90)
                {
                    JOptionPane.showMessageDialog(null, "Your grade is B.");
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Your grade is A.");
             }
         }
               
     }
           
    }
System.exit(0);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is an if-else-if statement?

A

The if-else-if statement tests a series of conditions. It is often simpler to test a series of conditions with the if-else-if statement than with a set of nested if-else statements.

Example:

if (testScore < 60)
JOptionPane.showMessageDialog(null, “Your grade is F.”);
else if (testScore < 70)
JOptionPane.showMessageDialog(null, “Your grade is D.”);
else if (testScore < 80)
JOptionPane.showMessageDialog(null, “Your grade is C.”);
else if (testScore < 90)
JOptionPane.showMessageDialog(null, “Your grade is B.”);
else
JOptionPane.showMessageDialog(null, “Your grade is A.”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the AND operator?

A

Connects two boolean expressions into one. Both expressions must be true for the overall expression to be true.

&&

The && operator is known as the logical AND operator. It takes two boolean expressions as operands and creates a boolean expression that is true only when both subexpressions are true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the OR operators?

A

Connects two boolean expressions into one. One or both expressions must be true for the overall expression to be true. It is only necessary for one to be true, and it does not matter which one.

The || operator is known as the logical OR operator. It takes two boolean expressions as operands and creates a boolean expression that is true when either subexpression is true.

||

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the NOT operator?

A

The ! operator reverses the truth of a boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true.

The ! operator performs a logical NOT operation. It is a unary operator that takes a boolean expression as its operand and reverses its logical value. In other words,
if the expression is true, the ! operator returns false, and if the expression is false, it returns true.

!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What logical operators does Java provide?

A

Java provides two binary logical operators, && and ||, which are used to combine two boolean expressions into a single expression. It also provides the unary ! operator, which reverses the truth of a boolean expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How does this code work:

double temperature;
Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter a temperature: ");
    temperature = keyboard.nextDouble();
   
    if (!(temperature > 100))
    {
        System.out.println("This is below the maximum temperature.");      
    }
    else
    {
        System.out.println("This is above the maximum temperature.");  
    }
A

First, the expression (temperature > 100) is tested and a value of either true or false is the result. Then the ! operator is applied to that value. If the expression (temperature > 100) is true, the ! operator returns false. If the expression (temperature > 100) is false, the ! operator returns true. The previous code is equivalent to asking: “Is the temperature not greater than 100?”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What do you use to determine a range?

A

Sometimes you will need to write code that determines whether a numeric value is within a specific range of values or outside a specific range of values. When determining whether a number is inside a range, it’s best to use the && operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you determine whether a number is outside a range?

A

When determining whether a number is outside a range, it’s best to use the || operator. It’s important not to get the logic of these logical operators confused

24
Q

What do you use to compare String objects?

A

You cannot use relational operators to compare String objects. Instead you must use a String method.

Remember that a string object is referenced by a variable that contains the object’s memory address. When you use a relational operator with the reference variable, the operator works on the memory address that the variable contains, not the contents of the string object.

25
How do you compare the contents of two string objects?
To compare the contents of two string objects correctly, you should use the String class's equals method. StringReference1.equals(StringReference2) StringReference1 is a variable that references a String object, and StringReference2 is another variable that references a String object. The method returns true if the two strings are equal, or false if they are not equal. Here is an example: if (name1.equals(name2)) Assuming that name1 and name2 reference String objects, the expression in the if statement will return true if they are the same, or false if they are not the same.
26
How do you compare two strings by character?
When you use the compareTo method to compare two strings, the strings are compared character by character. This is often called a lexicographical comparison. Example: String name1 = "Apple", name2 = "Mark", name3 = "Bob"; // Compare "Apple" and "Mark" // ASCII code for A is 65 // ASCII code for M is 77 // ASCII code for B is 66 // ASCII code for a is 97 // ASCII code for a is 97 if (name1.compareTo(name2) < 0) { System.out.println(name1 + " is less than " + name2); } if (name1.compareTo(name3) == 0) { System.out.println(name1 + " is equal to " + name3); } if (name3.compareTo(name1) > 0) { System.out.println(name3 + " is greater than " + name1); } compareTo method is case sensitive
27
What do the equals and compareTomethod perform?
The equals and compareTo methods perform case -sensitive comparisons, which means that uppercase letters are not considered the same as their lowercase counterparts. In other words, "A" is not the same as "a". This can obviously lead to problems when you want to perform case-insensitive comparisons.
28
What methods are used to ignore case?
The String class provides the equalsIgnoreCase and compareToIgnoreCase methods. These methods work like the equals and compareTo methods, except the case of the characters in the strings is ignored.
29
How does the compareToIgnoreCase work compared to compareTo?
The compareToIgnoreCase method works exactly like the compareTo method, except the case of the characters in the strings being compared is ignored.
30
What is the switch statement?
The switch statement is a multiple alternate division structure. It allows you to test the value of a variable or an expression and then use that value to determine which statement or set of statements to execute. The switch statement will recognize either uppercase or lowercase letters. case 'a': case 'A':
31
How is teh switch statement different from an if statement?
Use if statements for evaluating complex boolean conditions, ranges, or when only a few distinct choices are involved. Use switch statements for handling multiple, discrete choices based on a single variable You can’t put more than one condition in a switch statement -- you have to look at only one variable -- it’s not even a boolean, it’s what is its state? If you need to evaluate two conditions/variables then you have to use an if statement -- that’s the difference between if and switch statements
32
Why is the break sentence added in switch statements?
The break statement is added in switch statements to terminate the execution of the switch block once a matching case is found and executed Without the break statement, the program "falls through" all of the statements below the one with the matching case expression. Sometimes this is what you want. Each case needs a break statement after -- its breaks out of switch statement -- if you remove the first break statement in the example, all the cases will print until it means a break statement or until the switch statement ends
33
What is the case in a switch statement?
The case sentence (or more commonly, case label) is a fundamental part of a switch statement because it acts as a specific entry point to execute code based on a value
34
What is default in a switch statement?
The default case catches any value that does not match a specific case No, a default case is not strictly required in a Java switch statement. The default case is runs if matches none of the cases -- you don’t need a statement after the default one but it’s good to
35
What can a switch statement be?
If you are using a version of Java prior to Java 7, a switch statement's testExpression can be a char, byte, short, or int value. Beginning with Java 7, however, the testExpression can also be a String.
36
Can you join two methods together?
You can join two methods together to parse it to a string and then make it lower case -- would always be lower case so it wouldn’t matter which case the user uses input = keyboard.nextLine().toLowerCase();
37
What is the System.out.printf?
The System.out.printf method allows you to format output in a variety of ways. The method's general format is as follows: System.out.printf(FormatString, ArgumentList) In the general format, FormatString is a string that contains text, special formatting specifiers, or both. ArgumentList is a list of zero or more additional arguments, which will be formatted according to the format specifiers listed in the format string. The print F statement -- formats the output The string is called a format string -- contains a format list You need a \n because the print statement doesn’t advance cursor on its own (not like println) f means you are expecting a float
38
What is %f?
System.out.printf("Our sales are %f for the day.\n", sales); Inside the format string, the %f is a format specifier. The letter f indicates that a floating-point value will be inserted into the string when it is displayed. Following the format string, the "sales" variable is passed as an argument. This argument corresponds to the %f format specifier that appears inside the format string. The % is a format specifier -- %f is a placeholder -- whatever sales is put it here (places it at the format specifier “, sales” -- format list -- when there is a format specifier, there needs to be a variable
39
What is this System.out.printf("The temperatures are %f and %f degrees.\n", temp1, temp2);
There is a one-to-one correspondence between the format specifiers and the arguments that appear after the format string. The first format specifier corresponds to the first argument after the format siring (the temp1 variable), and the second format specifier corresponds to the second argument after the format string (the temp2 variable).
40
What is the format for an integer value?
If you want to format an integer value, you must use the %d format specifier. The d conversion character stands for decimal integer, and it can be used with arguments of the int, short, and long data types. Here is an example that displays an int: System.out.printf("I worked %d hours this week.\n", hours);
41
What else can format specifiers?
Format specifiers also have the ability to format the values that they correspond to. When displaying numbers, the general syntax for writing a format specifier is: %[flags][width][.precision][conversion]
42
How do you display numbers of decimal points?
There may be instance when you want numbers to display a certain way. For example, you can change the number of decimal points that are displayed, as shown in the following example: double temp = 78.42819; System.out.printf("The temperature is %.2f degrees.\n", temp); The .2 causes the value of the temp variable to be rounded to two decimal places. System.out.printf("%.1f %.2f %.3f\n", value1, value2, value3); you can specify precision only with floating-point point values. If you specify a precision with the %d format specifier, an error will occur at runtime.
43
What is a minimum feild width?
A format specifier can also include a "minimum field width", which is the minimum number of spaces that should be used to display the value. The following example prints a floating-point number in a field that is 20 spaces wide: System.out.println("Example 1: Field Width"); Example 1: Field Width double number = 12345.6789; System.out.printf("The number is:%20f\n", number); It printed the output using 20 spaces of field width and right aligned -- the number isn’t 20 spaces so it just used blank spaces Field width vs. format specifier - field width has no decimal point in front
44
How do you code a feild that is one space wide?
Example 2: Field Width With Limited Field The following example prints a floating-point number in a field that is only one space wide: double numberTwo = 12345.6789; System.out.printf("The number is:%1f\n", numberTwo); The value of the number variable requires more than one space, so the field width automatically expands to accommodate the entire number.
45
What is feild width with rounding?
Example 3: Field Width With Rounding the following code displays two numbers in a field of 12 spaces, rounded to two decimal places: double numberThree = 12345.6789; System.out.printf("numberThree is:%12.2f\n", numberThree); 12 is the number of spaces and 2 formats the amount of precision Don’t put a space before % -- with add another space
46
What is field width with integers?
Example 3: Field Width With Integers int numberFour = 200; System.out.printf("The number is:%6d\n", numberFour); The f changes to a d because we are using integers Format -- %(field width).(format of precision points)(f/d depending on float or integer)
47
How do you make columns and a field of 8 spaces with 2 decimal places?
// Example 3: Columns double num1 = 127.899; double num2 = 3465.148; double num3 = 3.776; // Display each variable in a field of // 8 spaces with 2 decimal places. System.out.printf("%8.2f\n", num1); System.out.printf("%8.2f\n", num2); System.out.printf("%8.2f\n", num3);
48
What are the optional flags that you can insert into a format specifier that causes a value to be formatted?
There are several optional flags that you can insert into a format specifier to cause a value to be formatted in a particular way. We will be looking at the following: To display numbers with comma separators To pad numbers with leading zeros To left-justify numbers
49
How do you add comma separators?
Example 1: Comma Separators Large numbers are easier to read if they are displayed with comma separators. double amount = 1234567.89; System.out.printf("%,f\n", amount); // No rounding System.out.printf("%,.2f\n", amount); // Same number but rounded With format specifier -- % + comma + . + amount of precision + f // Example 2: Comma Separators double monthlyPay = 5000.0; double annualPay = monthlyPay * 12; System.out.printf("Your annual pay is $%,.2f\n", annualPay);
50
What is comma separators with integers?
// Example 3: Comma Separators With Integers // The following example displays an int with comma separators, // with a minimum field width of 10 characters: int number = 20000; System.out.printf("The number is:%,10d", number);
51
What is padding numbers with leading zeros?
// Example 4: Padding Numbers With Leading Zeros double numberTwo = 123.4; System.out.printf("The number is:%08.1f\n", numberTwo); // The 0 in front to the 8 specifies that you want to pad the result // with leading zeros. Put a zero -- still has the correct field width BUT instead of spaces, we tell the computer to put leading zeros instead -- covers fields widths but puts zeros to fulfill it
52
What is left justfying numbers?
// Example 5: Left Justifying Numbers int num1 = 123; int num2 = 12; int num3 = 45678; int num4 = 456; int num5 = 1234567; int num6 = 1233; // Display each variable left-justified // in a field of 8 spaces. System.out.printf("%-8d%-8d\n", num1, num2); System.out.printf("%-8d%-8d\n", num3, num4); System.out.printf("%-8d%-8d\n", num5, num6); No minus -- justify to the right
53
How do format string arguments?
// Example 6: Formatting String Arguments String name1 = "George"; String name2 = "Franklin"; String name3 = "Jay"; String name4 = "Ozzy"; String name5 = "Carmine"; String name6 = "Dee"; System.out.printf("%10s%10s\n", name1, name2); System.out.printf("%10s%10s\n", name3, name4); System.out.printf("%10s%10s\n", name5, name6); // The %10s format specifier prints a string in a field that is // ten spaces wide. This code displays the values of the variables // in a table with three rows and two columns, eath column has a // width of ten spaces.
54
How do you do arguments with different data types?
// Example 7: Arguments With Different Data Types int hours = 40; double pay = hours * 25; String name = "Jay"; System.out.printf("Name: %s, Hours: %d, Pay: $%,.2f\n", name, hours, pay);
55
Can you put a double in the f string list?
You can’t put a double in the list and use %d -- will say error because you can’t convert a double to an integer -- narrowing conversion You can use %f with an integer - widening conversion -- the answer will have a .0