Liner Notes
Sample answers to "Check Yourself…" questions
When you buy an album on vinyl, the liner notes (or "jacket notes") are the information that’s printed on the back of the sleeve or, for music on CD or cassette, in a booklet inside the plastic case. Basic liner notes are just the song titles, and the names of the artists and producers. But sometimes you get lucky, and the liner notes have blurbs written by the artists, or maybe even the complete lyrics to the songs. In other words, a cheat sheet that really helps you understand the music.
These liner notes have answers and basic explanations to the Check Yourself… questions from the chapters. These aren’t meant to be comprehensive answers, just a little information so you can confirm you’re…well, I hate to say it, but…on the right track.
The review questions are intended to be a little open-ended, so your answers will vary from these.
Sound Check
-
What does JDK stand for?
Java Development Kit
-
What is an example of an Integrated Development Environment?
Visual Studio Code, eclipse, IntelliJ, and many others.
1. Computers and Coding
-
What is the primary role of a programming language in the context of computer programming?
The primary role of a programming language is to act as a bridge between human language and machine language. It allows humans to write instructions in a way that is easier for them to understand and use, which can then be accurately translated into machine language that a computer can execute.
-
What happens when you run a Java program? Describe that process in simple terms.
When you run a Java program, your code gets compiled (translated) into something the computer can understand, then the computer follows your instructions step by step and shows the results (like printing text or doing math).
There are likely many other good ways to explain this to an 8-year-old!
What’s the difference between System.out.println() and System.out.print()? When would you use each?::
System.out.print() prints text and keeps the cursor on the same line. System.out.println(), which we pronounce "print line", prints text and moves the cursor to a new line. Use print() when you want output to continue on the same line, and println() when you want it to start a new line afterward.
- How would you explain what a “program” is to an 8-year-old?
-
A program is like a list of instructions you give to a computer—kind of like a recipe. The computer follows the steps exactly to do something, like showing a message or solving a puzzle.
There are likely many other good ways to explain this to an 8-year-old!
- Explain the difference between compiled and interpreted programming languages. Describe how Java is both compiled *and interpreted.*
-
-
Compiled languages are those where the source code is translated into machine language by a compiler before the program is run. This machine language file can then be executed directly by the computer. An example of a compiled language is C.
-
Interpreted languages are those where the source code is translated into machine language on the fly, as the program is running, by an interpreter. An example of an interpreted language is Python.
-
Java is a somewhat unique case, as it is both compiled and interpreted. The source code is first compiled into an intermediate language called CIL, which is then interpreted by the .NET runtime (CLR) when the program is executed. This allows C# to have some of the performance benefits of compiled languages while still being able to run on different platforms.
-
2. Variables and Data Types
-
What is a variable, and why do we use them in programming?
A variable is a named storage location in a program that holds a value which can change as the program runs. We use variables to store, update, and reuse data.
-
Which C# data type would you use for each of the following?
-
The number of people in The Rolling Stones →
int -
The full name of the Rolling Stones' drummer →
string -
Whether the Stones are a great band (yes or no) →
bool -
The price of Sticky Fingers on vinyl →
double -
Mick Jagger’s middle initial (it’s P, incidentally) →
char
-
-
Write a line of code that declares a variable named importantYear and sets it to 1964.
[source,java]int importantYear = 1964;
-
What will the following code print? Why?
1 2 3 4
string leadGuitarist = "Brian Jones"; leadGuitarist = "Mick Taylor"; leadGuitarist = "Ronnie Wood"; System.out.println(leadGuitarist);
The code will print "Ronnie Wood" because the variable
leadGuitaristis first set to "Brian Jones" and then changed to "Mick Taylor". Then it is changed to "Ronnie Wood". The most recent value assigned to the variable is what gets printed. -
What happens if you try to store a word (like "hello") in a variable declared as int?
The program will not compile. You can’t assign a value of one data type to a variable of another (incompatible) data type. You also can’t change the data type of a variable after you’ve declared it.
-
What’s wrong with this variable name:
19thNervousBreakdown?A Java variable name can’t start with a number. You could call it
nineteenthNervousBreakdowninstead. -
True or False: You must always assign a value to a variable at the same time you declare it
False. You can declare a variable and assign a value to it later:
int albums; albums = 12; -
What are compound assignment operators in Java? Provide examples of how they are used in arithmetic operations.
Compound assignment operators combine an arithmetic operation with assignment. Examples:
int numStones = 4; numStones -= 1; // Rest in peace, Charlie Watts! -
Write a short program that asks for the user’s name and the number of Rolling Stones albums they own, and then prints a personalized message like: “Hello Bianca, you have 5 Stones albums.”
StonesGreeting.java1 2 3 4 5 6 7 8 9 10 11 12 13 14
import java.util.Scanner; public class StonesGreeting { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("What is your name? "); String name = input.nextLine(); System.out.print("How many Rolling Stones albums do you own? "); int albums = input.nextInt(); System.out.println("Hello " + name + ", you have " + albums + " Stones albums."); } }
-
Explain the purpose of the
Scannerclass in Java and provide an example of how it is used to get user input.The
Scannerclass is used to read input from various sources, including the keyboard. It allows you to get user input and store it in variables.
3. Methods
-
What is a method, and why would you use one in your code?
A method is a named block of code that does something—like a mini-program inside your program. You use methods to organize your code, avoid repetition, and make your program easier to understand and manage. (Like reusable LEGO chunks.)
-
What’s the difference between calling a method and defining a method?
Defining a method is writing what the method does. Calling a method is telling it to actually run. You define once, but can call it as many times as you want.
-
What does the keyword
voidmean in a method definition?voidmeans the method doesn’t return anything. It just does something, like printing text, but doesn’t give a value back. -
Consider the code below. a. What does it do? b. How would you call it to greet someone named "Darryl Jones"?
1 2 3 4
static void greet(string name) { System.out.println($"Hello, {name}!"); }
greet("Darryl Jones"); -
Why is it a good idea to define reusable code inside a method instead of copying and pasting it everywhere?
Defining reusable code inside a method is better than copying and pasting because it makes your code cleaner, easier to read, and less error-prone. If you need to change the code later, you only have to do it in one place instead of everywhere you pasted it. It also ensures that each copy of the code does the same thing, reducing the chance of mistakes.
-
Consider the code below. a. Overload the method by accepting the name of a band to introduce. b. Demonstrate how to call each version of the method.
1 2 3 4
static void announceBand() { System.out.println("Ladies and gentlemen, The Beatles!"); }
-
Overloaded method:
1 2 3 4
static void announceBand(string bandName) { System.out.println("Ladies and gentlemen, " + bandName + "!"); }
-
Calling each version:
1 2
announceBand(); // Calls the original method announceBand("The Rolling Stones"); // Calls the overloaded method
-
-
What happens if you define a method with a parameter but forget to provide an argument when you call it?
If you define a method with a parameter but forget to provide an argument when you call it, the program will not compile. The compiler will give an error because it expects an argument for the parameter.
-
What do we call the variable inside a method’s parentheses? How is it different from an argument?
The variable inside a method’s parentheses is called a parameter. It’s a placeholder for the value that will be passed to the method when it’s called. An argument is the actual value you provide when you call the method. For example, in
greet("Darryl Jones"), "Darryl Jones" is the argument, andnameingreet(string name)is the parameter.
4. Classes and Objects
- What is the primary difference between procedural programming and object-oriented programming (OOP)?
-
Procedural programming organizes programs as a collection of tasks or methods that need to be performed in a specific order. In contrast, OOP organizes programs as a collection of interacting objects, each representing a real-world entity with attributes (data) and behaviors (methods).
- Explain the concept of a class and how it relates to objects in OOP.
-
A class is a blueprint or template for creating objects. It defines the attributes and behaviors that the objects created from the class will have. An object is an instance of a class, meaning it is created with the fields and methods implemented in the class.
- What is encapsulation, and why is it important in OOP? Provide an example.
-
Encapsulation is the concept of hiding the internal state of an object and requiring all interaction to be performed through the object’s methods. This is important because it protects the object’s data from unintended or harmful modifications. For example, in a bank account class, the balance field is private and can only be accessed or modified through a public getter method, and modified through public deposit and withdraw methods.
- What are “fields” (instance variables) in a class, and how do they differ from local variables in methods?
-
Fields are variables defined inside a class but outside any method. Each object of the class gets its own copy of these variables. Local variables, on the other hand, exist only inside a method; they are created when the method runs and destroyed when it finishes.
- What is a constructor in Java, and what is its purpose when creating an object?
-
A constructor is a special method that has the same name as the class and no return type. Its purpose is to initialize a new object, typically by giving initial values to the object’s fields.
- What is “instantiation” in Java? Give an example of how you would instantiate an object of a class called
RecordPlayer. -
Instantiation is the process of creating an actual object from a class blueprint. For example:
RecordPlayer myPlayer = new RecordPlayer(); - In a program using classes and objects, what is the role of a driver class (a.k.a., demo class or test class)?
-
A driver class contains the main method and is used to create objects, call their methods, and test how the program works. It’s essentially the “entry point” for running and demonstrating your classes.
- What does the
thiskeyword refer to inside a class method or constructor, and when is it useful? -
thisrefers to the current object—the object whose method or constructor is running. It’s useful when you need to distinguish between fields and parameters with the same name (e.g.,this.volume = volume;) or when passing the current object to another method.
5. Decisions
-
Explain what Boolean expressions are and how they are used to make decisions in Java.
Boolean expressions are statements that evaluate to either true or false. In Java, they are used to make decisions by determining which blocks of code to execute based on the evaluation of these expressions.
-
Explain the difference between a relational operator and a logical operator.
Relational operators compare two values and determine their relationship, such as equality (==), inequality (!=), less than (<), and greater than (>). Logical operators, on the other hand, combine multiple Boolean expressions to form a single, more complex expression, such as AND (
&&), OR (||), and NOT (!). -
What is the difference between an
ifstatement and anif-elsestatement?An if statement allows you to execute a block of code only if a certain condition is true. An
if-elsestatement extends this by providing an alternative block of code to execute if the condition is false, allowing you to choose between two possible actions. -
How can you write code that runs one code block from multiple options?
You can use a
switchstatement to run one code block from multiple options based on the value of an expression. Alternatively, you can use anif-else ifstructure to chain multipleif-elsestatements together, allowing you to handle more than two options. -
What is the purpose of the
switchstatement, and when might you prefer it over multipleif-elsestatements?A
switchstatement is used to select one of many code blocks to execute based on the value of a single variable or expression. You might prefer it over multipleif-elsestatements when you have a variable that can take on many discrete values, as it can make the code cleaner and easier to read. -
What is a nested if statement? When might nesting be useful?
A nested
ifstatement is anifstatement that is placed inside anotheriforelseblock. Nesting can be useful when you need to make multiple levels of decisions based on different conditions, allowing for more complex (hierarchical) decision-making processes within your code. -
How do you compare two
Stringobjects for equality in Java?In Java, you compare two
Stringobjects for equality using the.equals()method (or.equalsIgnoreCase()for case-insensitive comparison) instead of the==operator, which does not behave as expected forStringcomparisons. -
Explain the the difference between the AND (
&&) and OR (||) logical operators.The AND (
&&) operator returnstrueonly if both operands aretrue; if either operand isfalse, the result isfalse. The OR (||) operator returnstrueif at least one of the operands istrue; it only returnsfalseif both operands arefalse.
6. Loops
-
What is the difference between a definite loop and an indefinite loop?
A definite loop runs a specific number of times, and that number is known before the loop starts. An indefinite loop continues to run until a specified condition is met, and the number of iterations is not known in advance.
-
Describe the difference between a while loop and a do-while loop.
A while loop checks the condition before executing the block of code, meaning the code might not execute at all if the condition is false initially. A do-while loop, on the other hand, checks the condition after executing the block of code, ensuring that the code is executed at least once.
-
What is a control variable, and how is it used in loops?
A control variable is a variable used to control the execution of a loop. It is typically initialized before the loop starts, checked in the loop’s condition to determine whether the loop should continue, and updated within the loop to eventually meet the condition that stops the loop.
-
What are the three main types of loops provided by Java?
forloops,whileloops, anddo-whileloops. -
When would you use a
forloop instead of a while loop?A
forloop works well for a definite loop (when you know ahead of time how many times the loop should run) or when the loop has a clear counter that needs initialization, updating, and a stopping condition. -
What is the syntax of a basic for loop? What are its three main parts?
for (statement 1; statement 2; statement 3) { // loop body }The three statements are the initialization (which sets up the loop control variable), the condition (which is checked to determine if the loop should continue), and the update (which modifies the control variable after each iteration).
-
What can happen if you forget to update the loop variable (or loop condition) inside a
whileorforloop?The loop may never reach its stopping condition, resulting in an infinite loop.
-
What are
breakandcontinuestatements usedforin loops?breakandcontinueadjust the normal flow of a loop.breakexits the loop entirely;continueskips the rest of the current iteration and moves on to the next one. -
What is a “for-each” (enhanced
for) loop in Java, and when might you use it instead of a regularforloop?A for-each loop automatically iterates through each item in a collection or array. It is most useful when we don’t need the index and just want to access each element directly.
7. Debugging and Generative AI
-
What is the difference between a compile-time error and a runtime error?
Compile-time errors occur when the compiler cannot translate the source code into machine code due to syntax or semantic issues. These errors must be fixed before the program can run. Runtime errors, on the other hand, occur during the execution of the program and are often due to logic errors, causing the program to behave unexpectedly or crash.
-
How can using output statements help in debugging a program?
Output statements, such as
print()statements, allow you to monitor the values of variables and the flow of execution in your program. This visibility helps you pinpoint where things are going wrong, making it easier to identify and correct errors. -
Explain two strategies you can use when you’re frustrated by a bug in your code.
One strategy is to take a short break and come back with fresh eyes, which often makes mistakes easier to spot. Another is to simplify the problem by testing smaller pieces of the code or explaining your logic out loud (even to an inanimate object).
-
What is a breakpoint in an IDE, and how does it help with debugging?
A breakpoint is a marker you place on a line of code that pauses the program while it runs. This allows you to inspect variables and step through the code one line at a time to see exactly what’s happening.
-
What is the purpose of a "watch window" in your IDE’s debugger?
A watch window displays the current values of selected variables while the program is paused. It helps you monitor how values change as you step through the code.
-
What does it mean to "step into" a method while debugging?
Stepping into a method means the debugger enters the method and shows each line of code inside it as it executes, instead of running the method all at once.
-
How might a generative AI tool assist you with debugging or writing code?
A generative AI tool can help explain error messages, suggest possible fixes, or provide example code. It can also help rephrase or simplify code, but the programmer is still responsible for understanding and testing the results.
8. Arrays
-
What is an array and how does it differ from a single variable?
An array is a data structure that allows you to store multiple pieces of data in a single collection. Unlike a single variable, which can only store one piece of data at a time, an array can hold multiple values, each of which is referred to as an element. Each element in an array is accessed using its unique index, which starts at 0 for the first element and increments by 1 for each subsequent element.
-
How do you declare and create a new array of integers with space for 10 elements?
int[] numbers = new int[10]; -
How do you find the number of elements of an array?
You use the array’s
lengthproperty. For example,albumTracks.lengthreturns the number of elements in thealbumTracksarray. -
What is an ArrayIndexOutOfBoundsException and when does it occur?
An
ArrayIndexOutOfBoundsExceptionis a runtime error that occurs when you try to access an element at an index that is outside the bounds of the array. This means you are trying to access an index that is either less than 0 or greater than or equal to the length of the array. For example, if an array has 10 elements, valid indices are 0 through 9. Attempting to access the element at index 10 or higher will result in this exception. -
Explain what it means to traverse an array.
Traversing an array means visiting each element in the array, usually one at a time, often using a loop.
-
Give an example of a
forloop to traverse an array calledalbumTracks.1 2 3
for (int i = 0; i < albumTracks.length; i++) { System.out.println(albumTracks[i]); }
-
What is the difference between a traditional
forloop and a "for-each" loop when working with arrays?A traditional
forloop uses an index and allows you to access element positions. A for-each loop iterates through each element directly without the use of an index. -
Why might you use a loop when working with an array instead of accessing each element individually?
Using a loop is generally more efficient and flexible, especially when the array has many elements or its size might change. It avoids repetitive code and reduces errors.
9. Inheritance
-
What is inheritance in object-oriented programming, and what are its benefits
Inheritance is a feature in object-oriented programming that allows a class (subclass) to inherit attributes and methods from another class (superclass), promoting code reuse and organization by enabling the creation of hierarchical relationships between classes.
-
How do you override a method in a subclass, and why might you want to do this?
To override a method in a subclass, you define a method in the subclass with the same name, return type, and parameters as the method in the superclass. This allows the subclass to provide a specific implementation of the method, which can be used to customize or extend the behavior of the inherited method.
-
Explain how to use the
superkeyword in a constructor.The super keyword is used in a subclass constructor to call the constructor of its superclass. This must be the first statement in the subclass constructor and is used to ensure that the superclass is properly initialized before the subclass adds its own initialization code. For example: super(parameter1, parameter2);.
-
Explain how different subclasses can be managed in a single array.
Different subclasses can be managed in a single array by declaring the array to be of the type of their common superclass. This allows the array to hold instances of any subclass, enabling polymorphism. For example, an array of type
BankAccountcan hold instances of bothCheckingAccountandSavingsAccount, and common methods can be called on these instances through the superclass reference.
10. Graphical User Interfaces
-
What is a Graphical User Interface (GUI) and why is it important for end users?
A Graphical User Interface (GUI) is a type of user interface that allows users to interact with electronic devices using graphical elements such as windows, icons, and buttons, rather than text-based commands. It is important for end users because it makes software more accessible and easier to use, especially for those who are not familiar with command-line interfaces.
-
Explain the role of the Swing library in Java and why it is preferred for beginners over JavaFX.
The Swing library in Java provides a set of pre-built GUI components that developers can use to create graphical user interfaces. It is preferred for beginners over JavaFX because it is simpler to use, does not require additional installations, and the concepts learned in Swing can be easily transferred to JavaFX.
-
Describe the process of creating a simple GUI using Swing, including the main components involved.
To create a simple GUI using Swing, you start by importing the necessary Swing classes, then instantiate a JFrame object to serve as the main window. You can set attributes like the title and size of the window, and add other components such as JLabel, JButton, and JTextField to the frame. Finally, you make the frame visible by calling the setVisible(true) method.
-
What is event-driven programming in the context of GUIs, and how does it differ from console-based programming?
Event-driven programming in the context of GUIs involves writing code that responds to user actions, such as clicking a button or entering text. This is different from console-based programming, where the program runs sequentially from top to bottom and waits for user input at specific points. In event-driven programming, the program continuously listens for events and executes the corresponding event handlers when an event occurs.