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.
Soundcheck
-
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 C# program? Describe that process in simple terms.
When you run a C# 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).
-
What’s the difference between Console.Write() and System.out.println()? When would you use each?
Console.Write() prints text and keeps the cursor on the same line. System.out.println() prints text and moves the cursor to a new line. Use Write() when you want output to continue on the same line, and WriteLine() 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.
-
Explain the difference between compiled and interpreted programming languages. Describe how C# 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.
-
C# 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
leadGuitarist
is 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
nineteenthNervousBreakdown
instead. -
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.java
1 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
Scanner
class in Java and provide an example of how it is used to get user input.The
Scanner
class 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
void
mean in a method definition?void
means 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, andname
ingreet(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.
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
if
statement and anif-else
statement?An if statement allows you to execute a block of code only if a certain condition is true. An if-else statement 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 switch statement to run one code block from multiple options based on the value of an expression. Alternatively, you can use an if-else if structure to chain multiple if-else statements together, allowing you to handle more than two options.
6. Loops
-
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.
-
Give an example of an indefinite loop.
An example of an indefinite loop is a program that asks the user to guess a number and keeps prompting the user until they guess correctly. The loop repeats until the user’s input matches the target number. Another example is a loop that reads user input until a specific sentinel value is entered, indicating the end of input.
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. -
What are some strategies you can use when you’re frustrated by a bug in your code?
When you’re frustrated by a bug in your code, take a break to clear your mind and return with fresh eyes. Use output statements to track variables and execution flow, clean up your code for better readability, and break down the problem into smaller parts. If needed, seek help from others and stay patient, knowing that debugging is a valuable part of the learning process.
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.
-
What is an ArrayIndexOutOfBoundsException and when does it occur?
An
ArrayIndexOutOfBoundsException
is 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. -
How can loops be used to traverse an array? Provide an example of a for loop that sums the elements of an integer array.
Loops can be used to traverse an array by iterating through each element, performing operations such as reading, modifying, or accumulating values. Here is an example of a for loop that sums the elements of an integer array:
1 2 3 4 5 6
int[] scores = {90, 85, 95, 88, 92}; int sum = 0; for (int i = 0; i < scores.length; i++) { sum += scores[i]; } System.out.println("The sum of the scores is " + sum);
In this example, the for loop iterates through each element of the scores array, adding each element’s value to the sum variable. After the loop completes, the total sum of the array elements is printed.
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
super
keyword 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
BankAccount
can hold instances of bothCheckingAccount
andSavingsAccount
, 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.