Weeks 1-4; Elementary, Conditionals, Loops Flashcards
What are the two types of Java programs?
Applications: Standalone programs. Applets: Require a Java-enabled browser to run.
What are the three looping structures in Java?
while (pre-test loop), do-while (post-test loop), for (pre-test loop with control).
What is the difference between while and do-while?
while tests the condition first; do-while executes at least once before testing.
How do you structure a basic if statement?
An if statement checks a condition, and if it is true, executes a block of statements.
How do you structure a for loop?
A for loop combines initialization, condition check, and update in one line.
What is a flag in Java?
A boolean variable that monitors a condition in a program, e.g., boolean highScore.
How do you generate a random number in Java?
Use the Random class and methods like nextInt() or nextDouble() to generate numbers.
How are comments written in Java?
Single-line: // comment; Multi-line: /* comment /; Javadoc: /* comment */.
What is the purpose of the break statement?
Terminates a loop prematurely.
What is the purpose of the continue statement?
Skips the current iteration and moves to the next iteration.
How are strings compared in Java?
Use .equals(), .equalsIgnoreCase() for equality; .compareTo() for lexicographical order.
What is the syntax for a switch statement?
A switch statement evaluates a value and matches it against multiple cases for execution.
How do you create a constant in Java?
Use the final keyword to declare a constant value that cannot change.
How is input validated using a loop?
Use a while loop to repeatedly prompt the user until valid input is entered.
What is the purpose of curly braces {} in loops?
To group multiple statements into a block to execute together.
What are escape sequences in Java?
Examples: \n (newline), \t (tab), \ (backslash), “ (double quote).
What is the purpose of the Scanner class?
To read input from the user using methods like nextInt() or nextLine().
What are the three parts of a for loop?
Initialization: Sets the control variable. Condition: Tests the loop variable. Update: Modifies the control variable.
What is a sentinel value?
A special value indicating the end of input, e.g., -1 in a list of positive numbers.
What is the ternary operator?
A compact form of if-else: result = (condition) ? value1 : value2.
What is the Random class used for?
To generate random numbers using methods like nextInt() and nextDouble().
How is an infinite loop caused?
Forgetting to update the control variable or setting a condition that is always true.
What is a nested loop?
A loop inside another loop where the inner loop completes all iterations for each outer loop iteration.
What are Java reserved keywords?
Examples: abstract, class, void, static, if, else, while, etc.