1. Home
  2. Explore
  3. Computer Science
  4. Java Programming Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Java Programming Fundamentals

  • 119Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Java Program Structure

What is the Java Development Kit (JDK), and what important components does it provide for building Java applications?

119 questions

  1. 1

    What is the Java Development Kit (JDK), and what important components does it provide for building Java applications?

    Model answer

    The JDK is a software development environment for Java. It includes the Java compiler, reusable code libraries, and a Java Runtime Environment.

    Explanation

    The compiler and libraries support development, while the runtime environment supports running Java programs.

  2. 2

    What is an IDE or code editor used for when developing Java, and which editor was used in the tutorial?

    Model answer

    An IDE or code editor is used to write and manage application code. The tutorial used IntelliJ IDEA Community Edition, which is free; NetBeans and Eclipse were also mentioned as popular alternatives.

    Explanation

    A developer can use a different editor if they prefer; the Java concepts are not tied to IntelliJ.

  3. 3

    What file extension should a Java source-code file have?

    Model answer

    A Java source-code file should use the .java extension.

    Explanation

    For example, a class named Main is stored in a file named Main.java.

  4. 4

    What does a Java package do, and how can a base package name be chosen by convention?

    Model answer

    A package groups related classes and creates a namespace for them. By convention, a project's base package can use the company's domain name written in reverse order.

    Explanation

    A reversed domain such as com.example helps organize classes and avoid naming conflicts; it does not require owning a registered domain.

  5. 5

    What is a class in Java, and why are classes used?

    Model answer

    A class is a container for related methods and other members. Classes help organize a program's code.

    Explanation

    A class groups code that belongs together, much like a section groups related products in a store.

  6. 6

    What is the difference between a function and a method in the terminology used in the tutorial?

    Model answer

    A function is a block of code that performs a task; when a function belongs to a class, it is called a method.

    Explanation

    Java methods are defined within classes, whereas some languages also allow standalone functions.

  7. 7

    What are the main parts of a method declaration?

    Model answer

    A method declaration specifies a return type, a descriptive name, parentheses for parameters, and a body enclosed in braces.

    Explanation

    The body contains the code that performs the method's task; parameters provide a way to pass values into it.

  8. 8

    What does the return type void mean for a Java method?

    Model answer

    void means that the method does not return a value.

    Explanation

    Methods that produce a value instead specify an appropriate return type, such as a number or date.

  9. 9

    What is the role of the main method in a Java program?

    Model answer

    The main method is the program's entry point: when the program is run, its code begins executing there.

    Explanation

    A basic Java program needs a class containing a main method so execution has a starting point.

  10. 10

    What is the minimum basic structure of a Java program described in the tutorial?

    Model answer

    It has at least one class containing a main method.

    Explanation

    The class provides the container, and the main method provides the entry point.

  11. 11

    What does an access modifier determine in Java?

    Model answer

    An access modifier determines whether other classes or methods can access a class or method.

    Explanation

    public and private are examples of access modifiers.

  12. 12

    What does the public access modifier indicate?

    Model answer

    It indicates that the declared class or method can be accessed from other parts of the program, subject to Java's access rules.

    Explanation

    The tutorial commonly uses public on class and method declarations.

  13. 13

    How do Pascal naming convention and camel naming convention differ in the tutorial's Java examples?

    Model answer

    Class names use Pascal case, with the first letter of each word capitalized. Method names use camel case, with the first word starting lowercase and later words capitalized.

    Explanation

    For example, a class may be named MainClass, while a method may be named sendEmail.

  14. 14

    Where does Java conventionally place the opening brace for a method declaration?

    Model answer

    Java conventionally places the opening brace on the same line as the method declaration.

    Explanation

    The tutorial contrasts this with styles in some other languages that put the opening brace on a new line.

  15. 15

    What is the purpose of a comment in Java, and do comments execute as program instructions?

    Model answer

    A comment explains code to readers and does not execute as part of the program.

    Explanation

    A line comment begins with two slashes, //.

  16. 16

    What happens during the compilation step when a Java program is built?

    Model answer

    The Java compiler translates Java source code into Java bytecode, which is stored in .class files.

    Explanation

    The compiler is supplied with the JDK; an IDE can run this compilation step for the developer.

  17. 17

    What is Java bytecode, and what is an important property of it?

    Model answer

    Java bytecode is the compiled representation of Java source code. It is platform-independent.

    Explanation

    The same bytecode can be run on different operating systems when a suitable Java runtime is available.

  18. 18

    What role does the Java Virtual Machine (JVM) play when a Java program runs?

    Model answer

    The JVM loads Java bytecode and translates it into native code for the underlying operating system.

    Explanation

    A Windows JVM translates bytecode for Windows, while a JVM on another operating system translates it for that system.

  19. 19

    What is the relationship between the Java Runtime Environment (JRE) and the JVM?

    Model answer

    The JRE provides the environment for running Java programs and includes the JVM, which executes the bytecode.

    Explanation

    The tutorial distinguishes the JRE, which a user can install to run programs, from the JDK used to develop them.

  20. 20

    Why are Java applications described as portable or platform-independent?

    Model answer

    Java source code is compiled to platform-independent bytecode, which can run on any supported system with a Java runtime and JVM.

    Explanation

    The JVM handles the conversion from bytecode to the native instructions of the host operating system.

  21. 21

    What are the two broad stages involved when a Java program runs?

    Model answer

    The two stages are compilation and execution: the source is compiled to bytecode, then the bytecode is run by the JVM.

    Explanation

    An IDE can perform both stages behind the scenes when the developer runs a program.

  22. 22

    How can a developer compile a Java source file from a terminal, according to the tutorial?

    Model answer

    Use the Java compiler command javac followed by the source filename, such as javac Main.java.

    Explanation

    The source filename's capitalization must match the actual filename on case-sensitive systems.

  23. 23

    How is a class with a package typically identified when launching it with the Java command?

    Model answer

    It is identified by its fully qualified class name, which includes the package name followed by the class name.

    Explanation

    The JVM uses the package path to locate the compiled class file.

  24. 24

    What does an IDE commonly hide when a developer runs a Java program?

    Model answer

    It commonly hides the separate compilation and execution steps, including the use of the compiler and JVM.

    Explanation

    The IDE can build the bytecode and launch the program through a single run action.

  25. 25

    What are the four Java editions listed in the tutorial, and what broad uses were associated with them?

    Model answer

    Java Standard Edition is the core platform; Java Enterprise Edition adds support for large-scale distributed systems; Java Micro Edition is a subset for mobile devices; and Java Card is for smart cards.

    Explanation

    The editions provide different libraries and capabilities for different application settings.

  26. 26

    What is the difference between primitive types and reference types?

    Model answer

    Primitive types store simple values, such as numbers, Boolean values, or single characters. Reference variables hold references to objects, such as dates or messages.

    Explanation

    The tutorial presents primitive and reference types as the two broad categories of Java types.

  27. 27

    What is a variable, and what does initializing a variable mean?

    Model answer

    A variable is a named memory location for temporarily storing data. Initializing it means assigning its initial value before using it.

    Explanation

    For example, declaring an integer variable and assigning it a starting value makes that value available for later use.

  28. 28

    What do a variable's type, identifier, assignment operator, and initial value represent in a declaration such as int age = 30;?

    Model answer

    int is the type, age is the identifier, = is the assignment operator, and 30 is the initial value.

    Explanation

    The type determines what kind of value the variable can store.

  29. 29

    Why are descriptive variable names recommended?

    Model answer

    Descriptive names make a variable's purpose clear to people reading the code.

    Explanation

    Names such as viewsCount communicate more than vague names such as v or n.

  30. 30

    Why does the tutorial recommend declaring one variable per line rather than several on one line?

    Model answer

    Declaring one variable per line makes the code easier to read and less cluttered.

    Explanation

    Java permits declaring multiple variables on one line, but the tutorial advises against it as a readability practice.

  31. 31

    How does assigning one primitive variable to another affect the two variables?

    Model answer

    The value is copied, so the variables are independent; changing one does not change the other.

    Explanation

    Primitive variables store their values directly rather than a shared object reference.

  32. 32

    How many bytes do the integer primitive types byte, short, int, and long use, respectively?

    Model answer

    They use 1, 2, 4, and 8 bytes, respectively.

    Explanation

    In general, types with more storage can represent a wider range of whole-number values.

  33. 33

    Which Java primitive types are used for whole numbers, and which are used for numbers with decimal parts?

    Model answer

    byte, short, int, and long are used for whole numbers; float and double are used for numbers with decimal parts.

    Explanation

    The tutorial presents float and double as floating-point types, with double using more memory than float.

  34. 34

    What are char and boolean used to store?

    Model answer

    char stores a single character, while boolean stores either true or false.

    Explanation

    A sequence of characters is represented by a string rather than a single char.

  35. 35

    Why might a long literal need an L suffix even when its receiving variable is declared as long?

    Model answer

    Java treats an unsuffixed whole-number literal as an int by default, so a value too large for int needs an L suffix to be treated as a long.

    Explanation

    An uppercase L is clearer than a lowercase l, which can look like the digit one.

  36. 36

    Why does a decimal literal assigned to a float variable need an F suffix?

    Model answer

    Java treats a decimal literal as a double by default, so the F suffix marks it as a float literal.

    Explanation

    This avoids a type mismatch between the default double literal and the float variable.

  37. 37

    How should a single character and a string literal be enclosed in Java source code?

    Model answer

    A single character is enclosed in single quotes, while a string is enclosed in double quotes.

    Explanation

    For example, a character uses 'A', whereas a string uses "ABC".

  38. 38

    What is a Java constant, and how is one declared in the tutorial?

    Model answer

    A constant is a value that cannot be reassigned after initialization. It is declared with the final keyword.

    Explanation

    The tutorial also uses uppercase letters by convention when naming constants.

  39. 39

    What is the difference between a class and an object?

    Model answer

    A class defines a template or blueprint, and an object is an instance created from that class.

    Explanation

    A class such as Human could be used to create individual human objects.

  40. 40

    Why does code generally use the new operator when creating an object from a reference type?

    Model answer

    The new operator creates an object and allocates memory for it.

    Explanation

    The tutorial contrasts this with primitive variables, whose memory is handled by the Java runtime without explicitly using new.

  41. 41

    How does the value stored in a reference variable differ from the value stored in a primitive variable?

    Model answer

    A primitive variable stores its simple value; a reference variable stores a reference to an object in memory.

    Explanation

    Copying a reference copies the reference, not a separate copy of the object.

  42. 42

    What happens when two reference variables refer to the same object and that object is changed through one variable?

    Model answer

    The change is visible through both variables because they refer to the same object.

    Explanation

    The variables are not independent copies of the object; they share its reference.

  43. 43

    How does a package help when two classes have the same name?

    Model answer

    Packages create separate namespaces, so classes with the same name can exist in different packages without conflicting.

    Explanation

    A class from another package can be imported when it is needed.

  44. 44

    Why can a Java program use classes from java.lang without writing an import statement?

    Model answer

    The java.lang package is imported automatically.

    Explanation

    The tutorial uses String and System as examples of classes available from this package.

  45. 45

    What is the usual shorthand for initializing a Java string, and how does it differ from explicitly using new?

    Model answer

    A string can be initialized directly with a string literal, such as String message = "Hello";. This is shorthand for creating a string without explicitly writing new String(...).

    Explanation

    Strings are reference types even though their common literal syntax resembles primitive assignment.

  46. 46

    How can two strings be joined together in Java?

    Model answer

    The + operator can concatenate, or join, strings.

    Explanation

    For example, a message can be combined with another string using message + "!".

  47. 47

    What do the string methods startsWith and endsWith test?

    Model answer

    They test whether a string begins or ends with a specified character sequence, respectively.

    Explanation

    Each method returns a Boolean result.

  48. 48

    What does the string method length return?

    Model answer

    It returns the number of characters in the string.

    Explanation

    It can be used, for example, to check whether a user-entered username is too long.

  49. 49

    What does indexOf return when the requested character or substring is present, and what does it return when it is absent?

    Model answer

    It returns the index of the first occurrence when present, and -1 when absent.

    Explanation

    This makes it possible to test whether a string contains a specified character or substring.

  50. 50

    What does the string method replace do, and does it change the original string?

    Model answer

    It returns a string in which occurrences of a target sequence are replaced by a replacement sequence; it does not change the original string.

    Explanation

    Strings are immutable in Java, so operations that produce modified text return a new string.

  51. 51

    What do toLowerCase and toUpperCase do to a string?

    Model answer

    They return new strings with the characters converted to lowercase or uppercase, respectively.

    Explanation

    Because strings are immutable, the original string is not modified.

  52. 52

    What does the string method trim do?

    Model answer

    It returns a string with extra whitespace removed from the beginning and end.

    Explanation

    It is useful for cleaning up spaces a user may have typed around form input.

  53. 53

    How can a double quote be included inside a Java string literal?

    Model answer

    Escape it with a backslash, as in \".

    Explanation

    Without escaping, the quote would be interpreted as the end of the string literal.

  54. 54

    How can a literal backslash be included in a Java string?

    Model answer

    Write two backslashes, \\, in the source string to produce one backslash in the string value.

    Explanation

    The first backslash escapes the second one.

  55. 55

    What do the escape sequences \n and \t represent in a Java string?

    Model answer

    \n represents a new line, and \t represents a tab.

    Explanation

    These escape sequences allow line breaks and tabs to be included in string content.

  56. 56

    What is an array used for, and how is an array's length determined when it is created?

    Model answer

    An array stores a list of items of a specified type. Its length is specified when the array is created.

    Explanation

    For example, an integer array can be created with space for a fixed number of values.

  57. 57

    How are array elements accessed, and what index identifies the first element?

    Model answer

    Array elements are accessed using an index in square brackets; the first element has index 0.

    Explanation

    An index identifies an element's position in the array.

  58. 58

    What happens if a program accesses an array using an invalid index?

    Model answer

    Java raises an exception, and the program may terminate if the exception is not handled.

    Explanation

    An index must refer to an element within the array's bounds.

  59. 59

    What default values did the tutorial identify for unassigned elements of integer and Boolean arrays?

    Model answer

    Unassigned integer array elements default to 0, and unassigned Boolean array elements default to false.

    Explanation

    These are the defaults described for those primitive array types.

  60. 60

    Why might printing an array directly fail to show its elements, and how can a one-dimensional array be displayed?

    Model answer

    Printing an array directly produces a string based on the array object's identity rather than a readable list of its elements. Arrays.toString returns a readable string representation of a one-dimensional array.

    Explanation

    The Arrays utility class provides methods for representing and manipulating arrays.

  61. 61

    What is method overloading, as illustrated by the Arrays.toString method?

    Model answer

    Method overloading means providing multiple implementations of a method name with different parameter types or signatures.

    Explanation

    The tutorial notes that Arrays.toString has implementations for different array types.

  62. 62

    How can an array be initialized concisely when its elements are already known?

    Model answer

    Use an array initializer with curly braces and list the elements, such as int[] numbers = {2, 3, 5};.

    Explanation

    This avoids separately allocating an array and assigning each element one by one.

  63. 63

    Can an array's length be changed after the array is created?

    Model answer

    No. A Java array has a fixed length after creation.

    Explanation

    A collection class is needed when the program needs to add or remove items dynamically.

  64. 64

    How can the Arrays class sort an array?

    Model answer

    Call Arrays.sort and pass the array to it.

    Explanation

    The tutorial uses this method to put the array's values in sorted order.

  65. 65

    What is a multidimensional array, and how are its elements accessed?

    Model answer

    A multidimensional array is an array whose elements are themselves arrays. Accessing an element requires an index for each dimension, such as a row index and a column index.

    Explanation

    A two-dimensional array can represent a matrix; additional dimensions can represent more complex data.

  66. 66

    Which Arrays method should be used to display the nested contents of a multidimensional array?

    Model answer

    Use Arrays.deepToString.

    Explanation

    The ordinary Arrays.toString method does not display nested array contents as a readable matrix.

  67. 67

    What does the modulus operator return?

    Model answer

    The modulus operator returns the remainder after division.

    Explanation

    It can be used to determine whether an integer is divisible by another integer by checking whether the remainder is zero.

  68. 68

    What result does integer division produce when both operands are whole-number types?

    Model answer

    It produces a whole-number result, discarding any fractional part.

    Explanation

    To retain a fractional result, at least one operand must be converted to a floating-point type.

  69. 69

    What is an expression in programming?

    Model answer

    An expression is a piece of code that produces a value.

    Explanation

    For example, an arithmetic calculation produces a numeric value, while a comparison produces a Boolean value.

  70. 70

    What is the difference between the prefix and postfix increment operators when used in an assignment?

    Model answer

    Postfix increment uses the variable's original value in the expression and then increments it; prefix increment increments the variable first and uses the new value.

    Explanation

    If x is 1, assigning x++ to another variable gives that variable 1, while assigning ++x gives it 2.

  71. 71

    What do compound assignment operators such as +=, -=, *=, and /= do?

    Model answer

    They combine an arithmetic operation with assignment, updating the variable using its current value and another operand.

    Explanation

    For example, x += 2 is equivalent to assigning x + 2 back to x.

  72. 72

    What is the order of precedence for parentheses, multiplication and division, and addition and subtraction?

    Model answer

    Parentheses have the highest precedence, followed by multiplication and division, then addition and subtraction.

    Explanation

    Parentheses can be used to change the order in which an arithmetic expression is evaluated.

  73. 73

    What is implicit casting, and when does it generally occur?

    Model answer

    Implicit casting is automatic conversion between compatible types when the conversion does not risk losing data, such as converting a smaller whole-number type to a larger one.

    Explanation

    Java can also convert an integer to a floating-point type when evaluating a mixed numeric expression.

  74. 74

    What is explicit casting, and why might it be used?

    Model answer

    Explicit casting is a conversion written by the programmer, such as (int) value. It is used when Java cannot perform the conversion automatically or when the programmer intends to accept possible data loss.

    Explanation

    Converting a decimal number to an integer removes its fractional part.

  75. 75

    Why can a numeric string not be converted to an integer simply by casting it?

    Model answer

    A string and an integer are incompatible types, so a cast cannot convert the string's text into a numeric value.

    Explanation

    A parsing method, such as Integer.parseInt, is used to interpret numeric text.

  76. 76

    How can a string containing a whole number be converted to an integer?

    Model answer

    Use Integer.parseInt and pass it the string.

    Explanation

    The wrapper class Integer provides this method for parsing an integer value from text.

  77. 77

    What should be used to parse a string containing a decimal number rather than an integer?

    Model answer

    Use an appropriate floating-point parsing method, such as Double.parseDouble or Float.parseFloat.

    Explanation

    Trying to parse a decimal string as an integer can cause an exception.

  78. 78

    What does Math.round do, and what return types did the tutorial describe for its overloads?

    Model answer

    It rounds a floating-point value to a whole-number value. The overload taking a float returns an int, while the overload taking a double returns a long.

    Explanation

    The return type matters when choosing the type of the variable that will store the result.

  79. 79

    How do Math.ceil and Math.floor differ?

    Model answer

    Math.ceil returns the smallest integer-valued number greater than or equal to its input; Math.floor returns the largest integer-valued number less than or equal to its input.

    Explanation

    For example, for a value just above one, the ceiling is two and the floor is one.

  80. 80

    What do Math.max and Math.min return?

    Model answer

    Math.max returns the greater of two values, and Math.min returns the lesser.

    Explanation

    The methods are overloaded to work with multiple numeric types.

  81. 81

    What range of values does Math.random produce, and how can its result be scaled?

    Model answer

    It produces a double value from zero up to, but not including, one. Multiplying the result by a number such as one hundred scales the range accordingly.

    Explanation

    Casting or rounding can then be used if a whole-number result is required.

  82. 82

    How can a Java program format a number as currency or as a percentage?

    Model answer

    Obtain a suitable NumberFormat object using getCurrencyInstance or getPercentInstance, then call its format method.

    Explanation

    The currency formatter adds currency formatting and separators, while the percent formatter presents a decimal as a percentage.

  83. 83

    Why can a NumberFormat object not be created directly with new in the tutorial's example?

    Model answer

    NumberFormat is abstract, so it cannot be instantiated directly; its factory methods return a usable formatter object.

    Explanation

    A factory method creates and returns an appropriate instance for the requested formatting task.

  84. 84

    What is method chaining?

    Model answer

    Method chaining is calling one method on the value returned by another method, without storing the intermediate result in a separate variable.

    Explanation

    For example, a formatter can be obtained and its format method called in the same expression.

  85. 85

    What do Java comparison operators produce, and what are some examples?

    Model answer

    They produce Boolean values. Examples include equality, inequality, greater-than, less-than, and their inclusive forms.

    Explanation

    An expression such as x == y evaluates to either true or false.

  86. 86

    How does the logical AND operator combine conditions?

    Model answer

    The logical AND operator, &&, evaluates to true only when both conditions are true.

    Explanation

    It short-circuits: if the first condition is false, Java does not need to evaluate the second condition.

  87. 87

    How does the logical OR operator combine conditions?

    Model answer

    The logical OR operator, ||, evaluates to true if at least one condition is true.

    Explanation

    It short-circuits when the first condition is true because the whole expression is already true.

  88. 88

    What does the logical NOT operator do?

    Model answer

    The logical NOT operator, !, reverses a Boolean value: true becomes false and false becomes true.

    Explanation

    It can express a condition such as requiring that a person does not have a criminal record.

  89. 89

    How does an if statement choose which code to execute?

    Model answer

    It evaluates a Boolean condition and executes its associated statement or block when the condition is true; else if and else clauses provide alternatives.

    Explanation

    This lets a program make decisions based on values such as temperature or user input.

  90. 90

    When are braces needed around the body of an if or else clause?

    Model answer

    Braces are needed when the clause contains multiple statements; the tutorial notes that some programmers also use them for single statements as a style choice.

    Explanation

    A braced block groups statements that should be controlled by the same condition.

  91. 91

    How can a Boolean variable be assigned directly from a condition instead of using an if and else?

    Model answer

    Assign the Boolean expression itself to the variable, such as hasHighIncome = income > threshold;.

    Explanation

    The expression already evaluates to true or false, so a separate branch assigning those values is unnecessary.

  92. 92

    What is the ternary operator, and when is it useful?

    Model answer

    The ternary operator has the form condition ? valueIfTrue : valueIfFalse and selects one of two values based on a condition.

    Explanation

    It is useful when assigning one of two values, such as choosing a class name based on a customer's income.

  93. 93

    How does a switch statement select code to execute?

    Model answer

    It compares an expression with case values and executes the matching case; an optional default clause handles cases with no match.

    Explanation

    A switch can be a clear alternative to several branches that compare the same expression against distinct values.

  94. 94

    What is the purpose of break in a traditional Java switch statement?

    Model answer

    break exits the switch block after the selected case's code runs.

    Explanation

    Without it, execution can continue into following case bodies instead of stopping at the matched case.

  95. 95

    Which kinds of values did the tutorial say can be used in the demonstrated switch statement?

    Model answer

    It demonstrated strings and integral types such as byte, short, and int; it noted that long was not included in those examples.

    Explanation

    The cases must be compatible with the type of the switch expression.

  96. 96

    Why should more specific conditions be checked before more general conditions in a sequence of if and else if clauses?

    Model answer

    A general condition checked first may match and prevent a more specific condition from being reached.

    Explanation

    In the FizzBuzz example, divisibility by both five and three must be checked before divisibility by either one alone.

  97. 97

    How can divisibility be tested with the modulus operator, and how does that support a FizzBuzz-style program?

    Model answer

    A number is divisible by another number when their remainder is zero. Testing remainders allows a program to choose different output for multiples of five, three, or both.

    Explanation

    The combined case must be checked before the individual cases to produce the intended result.

  98. 98

    What are the three main parts of a for loop header?

    Model answer

    A for loop header has an initialization, a Boolean continuation condition, and an update expression.

    Explanation

    The initialization runs first, the condition is checked before each iteration, and the update runs after each iteration.

  99. 99

    How can a for loop repeat a task a set number of times?

    Model answer

    Use a counter variable, a condition that limits the counter, and an update that advances it on each iteration.

    Explanation

    For example, a counter starting at zero and continuing while it is less than five executes the loop body five times.

  100. 100

    When is a while loop generally more suitable than a for loop?

    Model answer

    A while loop is useful when the number of repetitions is not known in advance and depends on a condition, such as user input.

    Explanation

    A for loop is often clearer when the number of repetitions is known ahead of time.

  101. 101

    How does a do-while loop differ from a while loop?

    Model answer

    A do-while loop checks its condition after executing the body, so it always runs at least once; a while loop checks first and may run zero times.

    Explanation

    Both repeat a block while their condition permits it, but the condition is checked at different times.

  102. 102

    What is the difference between the break and continue statements inside a loop?

    Model answer

    break terminates the loop; continue skips the rest of the current iteration and moves to the next one.

    Explanation

    They provide different ways to change the normal flow through a loop.

  103. 103

    What risk comes with using while (true), and how can the loop be made to terminate?

    Model answer

    It creates a loop that would continue indefinitely unless code exits it. A suitable break statement can terminate it when the required condition occurs.

    Explanation

    For example, a loop reading user input can break when the user enters a quit command.

  104. 104

    What is a for-each loop used for, and how does it work?

    Model answer

    A for-each loop iterates over the elements of an array or collection, assigning each element in turn to a loop variable.

    Explanation

    It avoids explicitly managing an index when only the elements are needed.

  105. 105

    What are two limitations of a for-each loop compared with a traditional for loop?

    Model answer

    A for-each loop proceeds forward and does not provide the element's index directly.

    Explanation

    A traditional for loop is preferable when the program needs reverse traversal or index-based operations.

  106. 106

    How can a Java program read input from the terminal using Scanner?

    Model answer

    Create a Scanner with System.in as its input source, then call an appropriate method such as nextInt, nextDouble, or nextLine.

    Explanation

    The scanner methods read values from the terminal in different formats.

  107. 107

    What is the difference between Scanner.next and Scanner.nextLine when reading text?

    Model answer

    next reads one token, stopping at whitespace; nextLine reads the entire line, including spaces between words.

    Explanation

    Use nextLine when the input may contain a full name or other text with spaces.

  108. 108

    Why might a program call trim on a line read from a user?

    Model answer

    It removes leading and trailing whitespace from the returned string.

    Explanation

    This helps prevent accidental spaces around user input from affecting later processing or display.

  109. 109

    Why should a Scanner object generally be created outside a loop that repeatedly reads user input?

    Model answer

    Creating it once avoids constructing a new scanner on every iteration when the same input source can be reused.

    Explanation

    The tutorial describes repeated scanner creation as unnecessary and a poor memory-management practice.

  110. 110

    How can a program keep asking a user for a value until it passes validation?

    Model answer

    Place the prompt and input-reading code in a loop, check whether the value is valid, and exit the loop when it is valid; otherwise display an error and ask again.

    Explanation

    An infinite loop with a conditional break is one approach demonstrated for repeated validation.

  111. 111

    Why can moving a variable declaration inside a loop or conditional block cause an error when the variable is used afterward?

    Model answer

    The variable's scope is limited to the block where it was declared, so code outside that block cannot access it.

    Explanation

    Declare the variable in an enclosing scope if it must be used after the block.

  112. 112

    How should an annual interest rate expressed as a percentage be converted to a monthly rate for the mortgage calculation described?

    Model answer

    Divide the annual percentage by one hundred to convert it to a decimal, then divide by twelve to obtain the monthly rate.

    Explanation

    This converts the rate's representation and accounts for twelve months in a year.

  113. 113

    How is the number of monthly mortgage payments calculated from a loan period in years?

    Model answer

    Multiply the number of years by twelve.

    Explanation

    There are twelve monthly payments per year, so the result is the total payment count used in the calculation.

  114. 114

    What purpose does Math.pow serve in the mortgage-payment calculation described?

    Model answer

    Math.pow raises a value to a specified power, which is needed for the payment formula's term involving the monthly rate and number of payments.

    Explanation

    The method takes a base and an exponent as arguments.

  115. 115

    Why does the tutorial recommend using named constants instead of unexplained numeric literals in calculations?

    Model answer

    Named constants explain what a number represents and avoid magic numbers, making code easier to understand and maintain.

    Explanation

    For example, a constant named for the number of months in a year is clearer than repeatedly writing an unexplained twelve.

  116. 116

    How did the tutorial choose types for the mortgage calculator's principal, annual interest rate, and loan period?

    Model answer

    It used an int for the principal, a float for the annual interest rate, and a byte for the number of years.

    Explanation

    The choices reflect the expected ranges and precision of these values in the example.

  117. 117

    What kinds of invalid input can make the initial mortgage calculator behave incorrectly or fail?

    Model answer

    Non-numeric input can cause the program to fail, and negative values can lead to an invalid calculation.

    Explanation

    Input validation is needed to reject values outside the allowed range and give the user another chance.

  118. 118

    What does the programming principle DRY stand for, and what concern does it address?

    Model answer

    DRY stands for β€œDon't Repeat Yourself.” It discourages unnecessary duplication of code or logic.

    Explanation

    The tutorial also notes that avoiding repetition can involve trade-offs, such as making control flow more nested and harder to read.

  119. 119

    Why does the tutorial emphasize meaningful names and clean, readable code?

    Model answer

    Meaningful names and clear structure help people understand and maintain code.

    Explanation

    Code should be understandable to human readers, not merely executable by a computer.

1 of 119
Question 1 of 119

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent