177 5 3MB
English Pages [222]

Topic Science
Subtopic Engineering & Technology
Learning Java Programming Course Guidebook Paulo Dichone Java Programmer
GREAT COURSES LEADERSHIP President & CEO. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PAUL SUIJK Chief Financial Officer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . BRUCE G. WILLIS Chief Marketing Officer. . . . . . . . . . . . . . . . . . . . . . . . . . . . CALE PRITCHETT SVP, Marketing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . JOSEPH PECKL VP, Customer Engagement. . . . . . . . . . . . . . . . . . . . . KONSTANTINE GELFOND VP, Technology Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . MARK LEONARD VP, Product Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . JASON SMIGEL VP, General Counsel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DEBRA STORMS VP, People. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . AUDREY WILLIAMS Sr. Director, Creative & Production. . . . . . . . . . . . . . . . . . . . . KEVIN BARNHILL Sr. Director, Content Development. . . . . . . . . . . . . . . . . . . . . . KEVIN MANZEL Director, Business Operations & Planning . . . . . . . . . . . . . . . . . . GAIL GLEESON Director, Editorial & Design Services . . . . . . . . . . . . . . . . . . FARHAD HOSSAIN Director, Content Research & Alternative Programming. . . . . . WILLIAM SCHMIDT
CREATORUP PRODUCTION TEAM Producers. .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Director . . . . . . . . . . . . . . . . . . . . . . . . . Casting. . . . . . . . . . . . . . . . . . . . . . . . . . Post-Production Supervisor . . . . . . . . . . . . Post-Production Coordinator . . . . . . . . . . . Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . Assistant Editor. . . . . . . . . . . . . . . . . . . . Post-Production Sound Designer. . . . . . . . . Head of Client Solutions. . . . . . . . . . . . . . Cinematographer. . . . . . . . . . . . . . . . . . . Second Camera Operator/Assistant Camera . Hair and Makeup Artist . . . . . . . . . . . . . . . Production Assistant. . . . . . . . . . . . . . . . . Head of Production & Creative Learning. . . . Production & Platform Manager . . . . . . . . . Associate Producer. . . . . . . . . . . . . . . . . . Production Associate . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DAVE O’BRIEN JOSELITO SELDERA . . . . JOSELITO SELDERA . . . . . . . . PERRIN DAVIS . . . . . . HARRISON KUNZ . . . . . ASHLEY MCGRAW . . . CHRISTOPHER ORDAZ . . . . MATTHEW HANISCH . . . . . . . . NICK WARNER CHRISTOPHER CUMMINGS . . . . . . . . . . ERIK SMITH . . . . . . MICHAEL GOMEZ . . . . . . . . . IEVA RADINA . . . . . . . . . . DELILA RIO MICHELLE KRAMER-PINO . . . . . . . DANNY BITTKER . . . BRIANNA MCFADDEN . . . CHRISTINA ROSALES
GREAT COURSES PRODUCTION TEAM Executive Producer. . . . . . . . Executive Content Developer . Quality Control Technicians . .
. . . . . . . . . . . . . . . . . . . . . . OCTAVIA VANNALL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . JAY TATE . . . . . . . . . . . . . . . . . . . . . . . MARGI WILHELM
Creator of Opening Title Animation .
FRANCISCO VÉLIZ-ORTIZ BRIAN SCHUMACHER
. . . . . . . . . . . . . . . .
GREAT COURSES EDITORIAL & DESIGN SERVICES Sr. Managing Editor. . . Sr. Graphic Designer. . Proofreader. . . . . . . . Transcript Editor. . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . BLAKELY SWAIN . . . . . . . . . . . . . . . . . . . . . . . . . . . KATHRYN DAGLEY . . . . . . . . . . . . . . . . . . . . . . . . . . . JESSICA MULLINS . . . . . . . . . . . . . . . . . . . . . . . . . . WILLIAM DOMANSKI
Paulo Dichone Java Programmer
Paulo Dichone is a software engineer, teacher, and consultant. Having earned his BS in Computer Science at Whitworth University, he now teaches Java, Android, and iOS mobile development to more than 100,000 students online in more than 175 countries. He is one of the top mobile development instructors on Udemy. His areas of expertise include Java, Kotlin, Dart, SwiftUI, Lua, and JavaScript. He also specializes in mobile game development and has built several mobile games for the Android and iOS platforms using Corona SDK, a 2D game engine now called Solar2D. As a consultant, he works with small start-ups in different industries, such as teledermatology and augmented reality, and designs and builds scalable business software. i
Table of Contents Introduction About Paulo Dichone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Guides 1
Welcome to Java! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2
Choose an Integrated Development Environment . . . . . . . . . . . . . . . . 8
3
Installing Android Studio for Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4
Installing Android Studio for Windows . . . . . . . . . . . . . . . . . . . . . . . . . 10
5
Create Your First Java Program! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
6
Java Code Structure, Syntax, and main Method . . . . . . . . . . . . . . . . 15
7
Declaring Variable Types: int and String . . . . . . . . . . . . . . . . . . . . . 18
8
Concatenating Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
9
Primitive Variable Types: boolean and char . . . . . . . . . . . . . . . . . . 30 ii
Table of Contents
10
Primitive Variable Types: byte, short, and long . . . . . . . . . . . . . . 33
11
Primitive Variable Types: float and double . . . . . . . . . . . . . . . . . . 38
12
Java Operators and Operator Precedence . . . . . . . . . . . . . . . . . . . . . . 41
QUIZ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
13
The while Loop in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
14
Java Branching Statements: if, if-else, and else-if . . . . . . . . . 57
15
Multiple Branches with the Java switch Statement . . . . . . . . . . . 66
16
The do-while Loop and the for Loop in Java . . . . . . . . . . . . . . . . . . 74
17
Arrays in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
18
Creating Objects in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
19
Class Constructors in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
20
Methods: Passing Arguments, Returning Values . . . . . . . . . . . . . . . 102
21
Java Getters and Setters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
22
Using the String Class as a Reference Type . . . . . . . . . . . . . . . . . . 115
23
Java Inheritance: Overriding Parent Methods . . . . . . . . . . . . . . . . . . 122
24
Java Inheritance: Invoking Parent Methods . . . . . . . . . . . . . . . . . . . . 130
QUIZ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 iii
Table of Contents
25
The Java Class Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
26
Java ArrayList and Object-Oriented Pros and Cons . . . . . . . . . . 140
27
Java Swing: Create a Simple User Interface . . . . . . . . . . . . . . . . . . . 147
28
Adding Buttons and Event Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . 154
29
Java Swing: BorderLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
30
Java Swing: FlowLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
31
Java Swing: BoxLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
32
Java Swing: Build a Fun Graphical User Interface . . . . . . . . . . . . . . 172
33
Android Studio: Setup, Emulator, and First App . . . . . . . . . . . . . . . . 184
34
Android Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
35
Android EditText and the strings.xml File . . . . . . . . . . . . . . . . . 197
36
Build an Inspiring Android App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
QUIZ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Supplementary Material Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
iv
Learning Java Programming A computer program is a set of instructions that’s explicitly written for computers to perform tasks. These instructions are often written in a highlevel programming language, such as Java. To instruct computers to do specific tasks, you must learn a programming language’s syntax, just like you would if you wanted to communicate well in a foreign language. This course takes you on a journey to learn how to write computer programs using Java—one of the world’s most popular programming languages. The course also exposes you to how Java is used to build desktop graphical user interfaces (GUIs) and Android mobile applications. In the first part of the course, you’ll learn how to set up your machine for Java development by installing the necessary tools to start learning Java programming. You’ll then learn how the Java compilation process works internally. You’ll explore how the Java Development Kit and the Java Runtime Environment work together to process and compile Java code into a different code format, bytecode, which holds the instructions that computers or devices can run. You will learn the Java program’s building blocks by looking at the Java code structure and Java basic syntax. Additionally, you’ll discover how to store data using predefined Java variable types. Because Java programs are dynamic entities—they allow for data manipulation and decision-making— you’ll learn how to control your programs’ flow by using conditional statements. You’ll also explore ways to execute code repeatedly. In the second part of the course, you’ll dive into a different realm of Java programming, object-oriented programming (OOP), a programming paradigm that looks at computer programs as a group of objects that interact with each other. You’ll explore how OOP enables the creation of robust, more complex Java programs. OOP provides a way for breaking down complexity into smaller, manageable pieces of code. You’ll write your first Java class—the blueprint of an object—and learn how to instantiate (create) an actual Java object from a Java class. You’ll learn how to construct a bullet-proof class that only exposes its internal state (behaviors and properties) through appropriate, 1
Scope
safe mechanisms to maintain the class’s integrity. Then, to further your OOP knowledge, you’ll explore Java Inheritance, which is a way to leverage preexisting class attributes and behaviors in a treelike class hierarchy. Java Inheritance is one of the most valuable Java features that allows you to reuse code. In other words, the code that’s already present in the parent class doesn’t have to be rewritten in the child class; the child class can inherit the parent class’s properties and behaviors, therefore reducing code redundancy. Understanding how Java OOP and Java Inheritance work and their benefits will give you a more holistic view of how software engineers build large software or break down complex problems into smaller pieces that are easy to solve. In the third part of the course, you’ll be introduced to Java Swing: a collection of Java classes used to build amazing GUIs. At this point in the course, you’ll have learned enough about Java to start building interactive user interfaces, such as creating windows that pop up on the computer screen with buttons and fields the user can interact with. You’ll learn how to leverage your Java knowledge along with Java Swing and Abstract Window Toolkit (AWT) to create virtually any GUI you’d like. You’ll learn how to lay out your GUI components on the screen using Java Swing built-in classes. You’ll finish this segment by building, from the ground up, a full-fledged Java GUI application that draws a circle in the middle of a window, and each time you click anywhere on the frame, the circle changes colors randomly. The fourth part of the course introduces Android mobile app development using the Java skills you’ve acquired throughout the course. You’ll start by learning what Android, as a mobile operating system, is. Next, you’ll learn about setting up Android Studio, the integrated development environment used to build Android mobile apps. You’ll then learn Android as a mobile development platform and use your Java skills to tap into the Android development platform. The final segment’s primary goal is to give you an overview of building Android apps with Java. You’ll also have a full understanding of the main Android building blocks, such as creating views, buttons, and a few other 2
Scope
Android user interface widgets. Additionally, you’ll learn how to run Android apps on a physical device. As a final project for this segment, you’ll build an Android app called Quotes, which randomly picks a quote from a list and displays it on the screen when a button is tapped. By the end of this segment, you’ll also have learned how Android projects are structured, how to design Android user interfaces, and how the user interface interacts with the Java code. By the time you complete this course, you will have a solid understanding of Java as a programming language. You’ll also know how to leverage Java to build stunning GUIs with Java Swing and AWT libraries as well as create Android mobile apps. This course takes you on a journey of learning Java programming and how versatile Java is—from writing simple Java programs, to building complex GUIs and software, to building mobile Android apps.
3
1 Welcome to Java!
TABLE OF CONTENTS
4
1 | Welcome to Java!
As one of the most popular programming languages, Java is used for various purposes in many industries. Java can be used to build desktop applications, web applications, mobile apps, back-end servers, and enterprise applications, such as streaming services and e-commerce websites. Java is also used in many development frameworks and tools for data analysis as well as artificial intelligence, self-driving cars, and smart-house devices like security cameras and thermostats. There are a few things to keep in mind as you go through this course: 1 If possible, type along with the presenter; programming is learned best by doing. 2 All code is available at this web address: www.TheGreatCourses.com/learningjava.
Java is a programming language that was first released in the 1990s. A programming language allows humans to give instructions to machines, such as computers and TVs. Machines only understand machine code (0s and 1s), so to interface with computers—in other words, to instruct devices to do something useful—you need a programming language, such as Java. So you write a set of instructions using Java, and then those instructions are translated into machine code (which most people find hard to read). Finally, the machine or device would run those instructions and do something (hopefully) useful.
TIP Java is a programming language. You can think of a programming language as a tool that enables programmers to solve computational problems and build software. 5
1 | Welcome to Java!
Here’s how Java works: First, a programmer writes Java code in a source file. Next, the source goes through a compilation process through a compiler, which checks the validity of the source code (for things like errors and syntax). Then, the compiler creates a new document coded into Java bytecode, which contains all the instructions machines can interpret/translate into something it can run. Here’s where Java shines: The bytecode is platform-independent, which means it can (potentially) run on any device. The only requirement is that the device must have a Java Virtual Machine (JVM), which is a piece of software that can be installed on devices. This is what reads the bytecode and runs those instructions on the device. JVM comes included in the Java Development Kit (JDK)—a collection of tools that enables you to write and run Java programs—so you won’t need to separately download JVM. You also won’t even need to download the JDK, because you’ll be downloading an integrated development environment (IDE) that includes the JDK packaged together with lots of other tools. You can think of an IDE as a code editor that has all of the tools and features needed for programmers to write code. Android Studio is the official IDE for Android development—for building Android mobile apps—and you can use it to write plain Java programs, too. There are other programming languages that can use JVM like Java does, such as Clojure, Scala, and Groovy. The main idea is that the JVM, as a piece of software, can be implemented by device manufacturers so that their devices have it installed when they ship those devices to the end users. This is what makes Java portable. And portability is what has made Java a very successful programming language to this day. 6
1 | Welcome to Java!
TIP It’s easy to get lost when trying to choose the best IDE or text editor when you first start learning programming. You don’t need an IDE or a fancy code editor to write Java programs. In fact, some may argue that it’s best to have a simple, basic code editor while learning Java and move on to an elaborate IDE once you’ve mastered the language.
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
7
2 Choose an Integrated Development Environment
TABLE OF CONTENTS
8
2 | Choose an Integrated Development Environment
There are many code editors and IDEs you can use to write Java code. Here are a few IDEs that are recommended for Java programming: 1 IntelliJ IDEA is versatile in that you can use it to write programs in multiple languages. Android Studio was built on top of IntelliJ, so most features you’d find in Android Studio you’ll also find in IntelliJ IDEA. However, in order to write Java programs using IntelliJ, you’ll need to download and install the JDK and set up the classpath as an environment variable. 2 NetBeans comes bundled with the JDK, so you wouldn’t need to do the extra setting up of the machine environment. NetBeans is a very powerful IDE because it simplifies the development of web, desktop, enterprise, and mobile applications that use Java and other web technologies. This is part of the reason why Oracle, the current sponsor of Java, highly recommends this IDE. If you want to develop web enterprise applications in the future with Java, NetBeans is a good choice. But you can also use it to learn to write simple Java programs.
9
3
4 TABLE OF CONTENTS
Installing Android Studio for Mac
Installing Android Studio for Windows 10
3 | Installing Android Studio for Mac 4 | Installing Android Studio for Windows
Let’s install Android Studio, which is the tool you’ll be using to learn Java and later to build an Android app. The installation process for both Windows and Mac users is straightforward. First, go to this link: https://developer.android.com/studio. Scroll to the bottom of the page and make sure that your machine meets the system requirements. Click on Download Android Studio. Once the download is complete, move the file onto your desktop and then double-click it to start the installation process. An Android installation wizard will appear, and the installation will start. After a few moments, the Android Studio wizard will prompt you with a Finish button. Click Finish.
For more detailed instructions, follow along with the video lesson.
11
5 Create Your First Java Program!
TABLE OF CONTENTS
12
5 | Create Your First Java Program!
Start Android Studio. First, you need to have an Android project and then create a Java lesson inside the Android project. 1 Click File > New > New module. Select Java Library and click Next. 2 Fill in the package name (com.learnjavateachco. firstjava) and click Finish.
You should now see a Java module inside your Android project. Next, let’s add some code. For now, you don’t need to understand what this code does.
public static void main(String[] args) { System.out.println("Hello World"); }
Now click Run and look at the bottom of the IDE to see Hello World printed out.
Hello World
Congratulations! You’ve created your first Java program.
TIP You can use a shortcut to write System.out.println in Android Studio (and IntelliJ). Simply start typing sout and hit the Enter key. 13
5 | Create Your First Java Program!
Next, let’s change the current code so that it prints out the text Java programming is fun!
To change the output, you simply replace the contents of println("") with Java programming is fun!
System.out.println("Java programming is fun!");
Run the program once again and you’ll see:
Java programming is fun!
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
14
6 Java Code Structure, Syntax, and main Method
TABLE OF CONTENTS
15
6 | Java Code Structure, Syntax, and main Method
Let’s take a closer look at this program:
public static void main(String[] args) {
System.out.println("Java programming is fun!"); }
At the top, you see FirstJava.java. The extension .java tells the compiler that inside of this file, it should expect Java code. Inside the source file is where you write Java code. The Java code must be written inside of a class, which represents a piece of your program. In this case, your class is called FirstJava.
public class FirstJava {
public static void main(String[] args) {
System.out.println("Java programming is fun!"); } }
Notice that at the very top of the file is a package keyword: com. learningjava.firstjava. That simply declares where the source file lives. The class must go within a pair of curly braces. A class may have one or more methods (yours only has one). Methods hold a set of statements.
16
6 | Java Code Structure, Syntax, and main Method
Now remove the semicolon after the System.out.println() statement and try running the program.
error: ';' expected
System.out.println("Java programming is fun!")
You should see an error telling you that something went wrong. First, you see a little warning in your code, and when you run the code, you receive a log in the console. The compiler is telling you that it can’t compile your source file because it found an error that needs to be fixed. In Java, the syntax is essential: If you miss something, your code most likely won’t run. Your code must follow Java basic syntax for it to compile.
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
17
7 Declaring Variable Types: int and String
TABLE OF CONTENTS
18
7 | Declaring Variable Types: int and String
The entry point to any Java program is the main method. Whatever you write inside of the main method runs first.
public static void main(String[] args) {
System.out.println("Java programming is fun!"); }
In this code, what you want to be printed out is written inside of the main method. Right now, this program is straightforward, but as you create more complex applications, you’ll have many different pieces (classes) that do different things, but in the end, everything must go through the main method to execute. Inside of the main method, you can 1 declare variables, 2 assign variables, 3 write statements, 4 use loops, and 5 use branching.
Almost all programming languages that inherit from C (another programming language) have a main method equivalent that serves as the main entry point to the program. 19
7 | Declaring Variable Types: int and String
Exercise Read the following Java statement and choose the correct answer.
String name = "Jeff";
a It’s assigning the variable name to "Jeff".
b It’s comparing name to "Jeff".
c "Jeff" is part of string theory.
TIP Almost all programming languages (if not all) have variables, or at least a similar concept. This makes sense because programs need data to work with, and variables are the simplest way of storing data in memory so programs can use that information to compute and then output something.
20
7 | Declaring Variable Types: int and String
TIP The double equal sign (==) is a binary operator in Java that is used to compare primitives. It always returns a boolean (true or false).
Solution a The Java statement is assigning a variable called name to hold "Jeff". The thing to remember from this exercise is that the equal sign (=) in Java means “assignment.” Whenever you want to store something into a variable, you use =. Java expresses “equals” with the double equal sign (==). In this statement, you’ve created a variable called name and assigned "Jeff" to it.
String name = "Jeff";
So now, whenever you want to access the text "Jeff", all you need to do is invoke the name variable. So now you can say something like this:
System.out.println(name);
And run this code. 21
7 | Declaring Variable Types: int and String
Notice how passing name inside of the parentheses gives you "Jeff" in the console. This tells you that a variable is simply a container—a holder for something (in this case, for "Jeff"). Variables are essential because they make it much easier for programmers to hold data (pieces of information), work on the data (change the data), and then output a result that can be passed on to another method (or variable, for that matter) for further processing, and so on. In this example, name was holding "Jeff" (a piece of data). Then, you called name inside println(), which printed the contents of the name variable. What’s great about variables is they can be changed to hold something else (hence the name variable). You can change the variable contents by changing the string "Jeff" to "Fred", like this:
String name = "Fred";
When you run this code, "Fred" is printed out in the console. The compiler will always acknowledge the last-added contents to the variable. The assumption is that the last occurrence of that variable should be the most up-to-date data by the logic of what programs do. Java programs are interpreted from top to bottom, so the compiler always starts reading the source file from the top of the file to the bottom. In the "Jeff" statement, the String keyword tells you what kind or type of variable you have. So this Java statement can be read as follows: Create a variable called name that only stores a string "Jeff". 22
7 | Declaring Variable Types: int and String
To declare a variable in Java, you must specify the type of the variable.
TIP In Java, variables must have types associated with them.
When you declare a variable, essentially you are telling the computer to allocate space in memory to store something. Java must specify what kind of space needs to be allocated for that variable. In other words, what type of stuff will the variable be holding? Types are fundamental in Java. Anytime you want to create a variable and assign it to something, you must include a type. Types in Java are important because all operations are checked for type compatibility, so illegal operations, such as creating a variable without a type, will not compile in Java. This is why having a strong type-checking helps prevent errors, making the language reliable. This makes Java a strongly typed programming language. Another common type in Java is int, which stands for integer, a whole number (1, 3, 19, 100, etc.). Here’s how to declare an int type:
int age = 25;
System.out.println(age);
Run the code and you will see the number printed out:
25
Pay close attention to the syntax! You don’t write Int or integer as the type. It must be the lowercase int. 23
7 | Declaring Variable Types: int and String
The general syntax for creating a variable is as follows:
Type name;
This creates a variable with a specific type, but nothing is assigned to it. So it would be like asking for the computer memory to allocate some space in memory that’s empty. Or you could have this:
Type name = something;
This creates a variable (with a specific type, of course) and assigns something to it. To create a string type, you must add double quotes (" ") around the word or text. Anything inside double quotes is considered a String in Java.
Exercise Declare three variables: 1 a String type called firstName (and assign James to it) 2 a String type called lastName (and assign Bond to it) 3 an int type called age (and assign 45 to it) 24
7 | Declaring Variable Types: int and String
Then, print out the following text:
"Hi, my name is James Bond, and I am 45 years old."
Solution The challenge here is that you’ll need to pass the variables you’ve declared previously in the println() as variables, so the contents of the variables are extracted out when you run the program. Essentially, your printout should look like this:
System.out.println("Hi, my name is firstName lastName, and I am age years old.")
(Hint: Google “Java string concatenation operator”.)
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
25
8 Concatenating Variables in Java
TABLE OF CONTENTS
26
8 | Concatenating Variables in Java
When you put strings together—one after another—it’s called concatenation in Java. It’s like gluing pieces of strings into one long string. Here you have two String types and the int type called age:
String firstName = "James"; String lastName = "Bond"; int age = 45;
Now print out the sentence along with your variables. The obvious solution would be to write the following:
System.out.println("Hi, my name is firstName lastName and I am age years old.");
But this doesn’t work. You get a lot of red squiggly lines. For you to pass variables along with text, you need to use a Java concatenation operator, the plus sign (+), like this:
System.out.println("Hi, my name is" + firstName + lastName + " and I'm "+ age + " years old.");
When you run this code, you have a nice output, but there are a few cosmetic issues:
Hi, my name isJamesBond and I am 45 years old. 27
8 | Concatenating Variables in Java
There are no spaces between is and James and Bond. To solve this issue, you need to add some empty spaces, like this:
System.out.println("Hi, my name is " + firstName +
" " + lastName + " and I'm " + age + " years old.");
In other words, you can add spaces by adding empty strings!
Exercise Try concatenating String and int variables: 1 Create two or three String variables and assign values to them. 2 Create one or two int variables and assign values to them. 3 Write a short story about yourself.
Here’s an output example:
"Hi, I'm Paulo and I'm 100 years old. I grew up in
a small town, called HappyVille. I was a very happy
child in Happyville. I have 13 brothers and sisters."
28
8 | Concatenating Variables in Java
Solution String name = "Paulo";
String bio = "I grew up in a small town, called
HappyVille. I was a very happy child in HappyVille."; int age = 100;
int siblings = 13;
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old. " + bio +" I have " +siblings + "brothers and sisters.");
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
29
9 Primitive Variable Types: boolean and char
TABLE OF CONTENTS
30
9 | Primitive Variable Types: boolean and char
In Java, different types of variables have different sizes. Java divides its types into 2 main categories: ^ primitive types ^ reference types Primitives are types that hold different sizes. There are eight primitives in Java. Each Java primitive has a set number (capacity) of bits it can hold. In computer jargon, a bit is the smallest unit of data or information. One bit essentially represents 1 or 0 (meaning “on” or “off,” respectively). The first primitive is a boolean, which can only hold either 1 or 0 (true or false). The size of a boolean type is 1 bit, and the value range is true or false. Here’s how to declare a boolean variable:
boolean isHappy = true; boolean isDone = false;
Notice that true and false are not inside of double quotes—they are not String types. Another primitive is char. A char represents one character only. A char can hold 16 bits, making it considerably larger than a boolean type. Another important visual distinction for char is that you use single quotes (' '), not double quotes.
31
9 | Primitive Variable Types: boolean and char
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
32
10 Primitive Variable Types: byte, short, and long
TABLE OF CONTENTS
33
10 | Primitive Variable Types: byte, short, and long
The most popular primitive you’ve learned about is the int, which represents a whole number. Generally, an int is the type you will be using the most, whenever you need a large enough type that can hold a bigger range of numbers. An int can hold 32 bits, which means it can hold four times as much as a char can hold (which is 16 bits). But remember that although these two are both primitives, they are still different types. But there are instances when you may need a small container to store data. That’s when you would use a byte, which holds 8 bits and has a smaller value range than int (32 bits) that it can hold. Here’s how you create a byte variable and add a value to it:
byte aByte = 78;
Now let’s test the value range for a byte type. Let’s start by assigning 124.
byte aByte = 124;
When you run the code, you see no errors. But when you increase the number to 128, the IDE tells you that this won’t work.
byte aByte = 128;
34
10 | Primitive Variable Types: byte, short, and long
The IDE even tries to help you by telling you to change the variable type to an int for this to work. This error tells you the value range for a byte: It can only hold values from −128 to 127. Beyond that range, you will get an error. In addition to byte and int, there’s a midrange type called short that holds 16 bits. In cases when you need a container that’s a little more than a byte (8 bits) and less than an int (32 bits), you use a short.
TIP Don’t try to memorize these value ranges and how many bits each primitive can hold. Just know that there are different types, each of which has a defined bit size and value range.
Here’s how you declare a short:
short aShort = 30000;
The value range for a short is −32768 to 32767.
Exercise Without writing this code in the IDE, do you think this will work? Why or why not?
int x = 13;
byte a = x;
35
10 | Primitive Variable Types: byte, short, and long
Solution Without writing the code in the editor, you would think that it would work (13 is certainly small enough to fit into a byte type). However, the compiler will always look at x as an integer, so it will not allow an integer to be added into a smaller container. Hence, this won’t work:
int x = 13;
byte a = x;
If you write this piece of code in the code editor, you’ll see that before you even attempt to run the program, errors will pop up. The key point to remember here is that you can’t forcibly mix types in Java.
The final numeric type for you to see is the long type, which you use when dealing with larger numbers. Here’s a long variable:
long aLong = 7876452;
A long is 64 bits and has a huge value range, too! So you’d use a long in cases where you know you’ll need a very large container to hold your numbers.
36
10 | Primitive Variable Types: byte, short, and long
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
37
11 Primitive Variable Types: float and double
TABLE OF CONTENTS
38
11 | Primitive Variable Types: float and double
So far, you’ve learned about ways to express whole numbers, from small to large. But what about decimal numbers? You can express decimal numbers, such as pi (3.14) or $34.99, with floats and doubles. A float is a type that holds any number that has decimal points. A float is 32 bits, and its value range varies. Here’s how to create a float and assign it 3.14:
float pi = 3.14f;
The f at the end of the number makes your variable a float in Java. A double is 64 bits, and its range value also varies. A double is the best type to express monetary value:
double expenses = 234.89;
The reason to use one instead of the other depends on the level of precision you want. In Java, doubles provide more precision than floats. A double provides more than 10 decimal points, whereas a float can only give 6 to 7 decimal points. As an example, let’s say you’re responsible for writing a program that calculates a precise location for a spaceship to land and that you need to divide the value of pi (3.14) by 212. Which should you use: a float or a double?
39
11 | Primitive Variable Types: float and double
When you run this code, you get this result:
double dPie = 3.14/212; float fPie = 3.14f/212;
System.out.println("Double location: " + dPie); System.out.println("Float location: " + fPie); Double location: 0.014811320754716981 Float location: 0.014811321
The location is more accurate when you use a double type—which has a precision of up to 18-digit decimal points—whereas float is less accurate. And with these two types, float and double, your learning about primitive types concludes.
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
40
12 Java Operators and Operator Precedence
TABLE OF CONTENTS
41
12 | Java Operators and Operator Precedence
In Java, you can do number crunching quite easily using +, -, *, /, and %.
Exercise 1 Create two variables of type double called a and b. 2 Assign 10 to a and 4 to b. 3 Create another variable of type double and call it sum. Assign sum the summation of a and b (add a to b). 4 Use the + operator to add a and b and assign the result to a variable sum. 5 Then, print out the sum variable, along with this sentence:
The sum of 10 and 4 is 14.
Solution double a = 10; double b = 4;
double sum = a + b;
System.out.println("The sum of " + a + " and " + b + " is " + sum +".");
42
12 | Java Operators and Operator Precedence
You can do the same if you want to subtract two numbers, except instead of using the + operator, you’d use the - operator:
double result = a - b;
System.out.println("Result is " + result);
A division expression uses /:
double divisionResult = a / b;
System.out.println("Division result " + divisionResult);
You can multiply numbers by using *:
a * b
You can also find the remainder from a division expression using the % operator, called the remainder operator or the modulo operator:
int remainder = a % b;
This should give a result of 2.
43
12 | Java Operators and Operator Precedence
You can employ, for example, multiplication expression as part of a more complicated statement:
int total = 100 + (a * 10);
You can also increment or decrement a variable by 1. To decrement a variable by 1, you add a -- suffix to the variable:
int age = 10; age--;
To increment a variable by 1, you add a ++ suffix to the variable:
int age = 10; age++;
Exercise Without testing this code in the code editor, what’s the final value of y?
int y = 10 * 4 + 5; y--;
a 45
b 44
c 98.5 44
12 | Java Operators and Operator Precedence
Solution To start, 10 * 4 + 5 is 45, and then you decrement the value of y by 1, so the correct answer is b) 44.
Look at this expression alone:
int y = 10 * 4 + 5;
Run the code and you get this:
45
This tells you that multiplication takes precedence over addition. But if you want to force addition to take precedence over multiplication, you can write it this way:
int y = 10 * (4 + 5);
Now the result is this:
90
What’s inside parentheses now takes precedence, hence the new result. 45
12 | Java Operators and Operator Precedence
Here’s another expression:
int x = 3 * 2 + 4 * 10 / 2;
The result is this:
26
That’s because this is the precedence order in this example: 1 multiplication, division 2 addition
Here’s one of the possible ways the compiler evaluates this expression: 3*2 = 6 4*10 = 40 40/2 = 20 20 + 6 = 26
Understanding how operator precedence works in Java is crucial because you could end up with the wrong result even though you’ve plugged in the correct numbers.
46
12 | Java Operators and Operator Precedence
Exercise Calculate the weight of an object on several different planets, given the gravitational constants for a few planets and the formula you’ll need to calculate the weight on the respective planets. To calculate weight on all other planets, you need the following: 1 weight on Earth 2 gravitational constant for the planet a b c d
Venus: 0.91 Mars: 0.38 Jupiter: 2.34 Saturn: 0.93
3 weight on Planet x = weight on Earth * gravitational constant
How much would a 190-pound object on Earth weigh on Mars, Jupiter, Venus, and Saturn? Here’s basically how the output should look:
"Object's weight on Earth is 190." "Object's weight on Venus is x." "Object's weight on Mars is y."
... 47
12 | Java Operators and Operator Precedence
Solution Often in programming, there are many different ways to solve a problem, so this solution may look completely different from the way you chose to solve the problem. And that’s fine—as long as you get the correct output. So here’s one way to solve this problem: 1 Create a variable that holds the Earth weight. 2 Output the base weight, which is the Earth weight. 3 Calculate the Venus weight by multiplying the Earth weight by the gravitational constant for Venus. 4 Output the result. 5 Repeat the same process for the other planets.
double weight = 190;
System.out.println("Object's weight on Earth is " + weight);
double venusWeight = weight * 0.91;
System.out.println("Object's weight on Venus is " + venusWeight);
double marsWeight = weight * 0.38;
System.out.println("Object's weight on Mars is " + marsWeight);
double jupiterWeight = weight * 2.34;
System.out.println("Object's weight on Jupiter is " + jupiterWeight);
double saturnWeight = weight * 0.93;
System.out.println("Object's weight on Saturn is " + saturnWeight);
48
12 | Java Operators and Operator Precedence
Remember, Java statements can use mathematical expressions by employing the operators +, -, *, /, and %. Keep in mind that operator precedence is very important. If your expression has all 5 of these operators employed, then the following evaluation order is used when the compiler works out the expression: 1 Incrementing and decrementing come first. 2 Multiplication, division, and modulus division occur next. 3 Addition and subtraction follow. 4 Comparison comes next. 5 The equal sign (=) is used to set or assign the variable to a value.
Resources Learn Java, https://www.learnjavaonline.org/. Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
49
TABLE OF CONTENTS
Quiz 1 What is a compiler? 2 What is bytecode? 3 True or false? The following Java statement will compile without any errors:
system.println(“Hello World”);
System.out.println(“Hello World”);
4 What is the purpose of the main() method in a Java program? 5 What is a variable? 6 What is a variable type? 7 Do the float and double primitive types have the same precision?
50
Quiz Answers 1 A compiler is a special program that translates code written in a high-level programming language, such as Java, into bytecode or machine code. 2 Bytecode is a compiled Java code format that’s ready to be executed on a computer or device running the JVM, a program that interprets Java bytecode. 3 False. The statement has two syntax errors: system should be System and is missing the out static member. The correct statement should be this:
System.out.println(“Hello World”);
4 The main() method is the Java program’s entry point. It’s where you can declare and assign variables and write Java statements. 5 A container (inside the computer’s memory) that can hold a piece of data that can be referenced. 6 A variable type is a keyword or identifier that specifies what kind or type of data the variable will hold. 7 No. A float is less precise than a double. A float is single-precision, meaning that it has less significant digits to the right of the decimal, whereas a double is double-precision.
51
13 The while Loop in Java
TABLE OF CONTENTS
52
13 | The while Loop in Java
Programs can be made more autonomous by enabling them to make decisions based on the states and conditions of variables. In essence, programs are supposed to be able to make decisions based on the flow of data—the input you give to them. In real life, you could give your friend the following instructions: To get to the mall, you’ll drive 10 miles north on Bella Street and hang a left on Martin road. If you see a big mango tree to your left, you’re getting close. Keep going until you see a big clown waving at everybody. Then the mall is going to be on your left. When these instructions are written out like this in English, they make sense. A person given these instructions would know what to do. But how do you translate these instructions, with some conditions that must be met to get to the final destination successfully? Loops and branching help programs do just that: repeat tasks, branching those tasks until the final condition is met. Let’s say you want a certain block of code (block of statements) to run until a specific condition is met. As an example, let’s simplify the mall directions for learning. To get from A to B, your friend will need to keep driving until mile 10. This means that your friend must keep driving until a specific condition is met: Get to mile 10, and at that point, they no longer need to continue driving because they’ll have arrived at the final destination. To translate these instructions for the computer, you need to express the following in code: While mile 10 has not been reached, keep driving until mile 10 is reached, then stop. 53
13 | The while Loop in Java
This is called pseudocode. It’s a mix of English and code. Essentially, it’s a notation resembling a simplified programming language that’s used in program design. To translate this pseudocode into actual Java code, you use a while loop. First, you need a few variables that will control the flow of the while loop:
int destination = 10; int counter = 0;
The destination variable is the final destination—in this case, at mile 10. The counter variable will help keep track of the progress as the friend keeps driving. Then you have the actual while loop:
while(){ }
Inside the parentheses, you need to put the conditional test, which is a conditional statement, and then whatever is inside the curly braces will keep running until the conditional test is no longer true.
while(count < destination) {
System.out.println("Keep driving"); }
54
13 | The while Loop in Java
You must keep track of the progress as you loop through. Otherwise, you’ll end up with an infinite loop—meaning that the while loop will run forever, or at least until your computer runs out of memory. To avoid this, all you need to do is update the counter by incrementing each time the loop runs by 1:
while(count < destination) {
System.out.println("Keep driving"); count++; }
Run this code and you will see this output 10 times:
Keep driving Keep driving Keep driving Keep driving Keep driving Keep driving Keep driving Keep driving Keep driving Keep driving
As soon as the while loop is executed, the conditional test will be evaluated. The first time, it will check if count (which is 0 initially) is < destination (10). If it is, then it will run what’s inside the curly braces (print out the text and increment count by 1). The counter will then be at 1, and the process continues until the test conditional is no longer true: when the counter is 10 (note that 10 is not less than 10). 55
13 | The while Loop in Java
TIP Always have a counter that’s incremented inside the while loop to avoid infinite loops! Also, in case you end up having an infinite loop, just terminate your program by clicking on the Stop button.
When the conditional test evaluates to false, then the program breaks from the while loop and continues reading what comes next. So you could add another printout to let your friend know that they have arrived!
System.out.println("You've arrived at mile " + count);
Make sure that inside the while loop you include a counter, which increments each time the while loop runs. Otherwise, you’ll have an infinite loop. Your computer will end up slowing down and eventually use up all the memory and shut down.
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
56
14 Java Branching Statements: if, if-else, and else-if
TABLE OF CONTENTS
57
14 | Java Branching Statements: if, if-else, and else-if
The fun part of programming is that it allows you to create programs that do things depending on certain conditions. For example, you can express things like this:
If your bank account has less than 1000, you shouldn’t go to Vegas.
To express that in code, you use the if statement, like this:
int bankAcct = 900;
if (bankAcct < 1000) {
System.out.println("Nope. Just stay home. Vegas is too expensive."); }
The < (“less than”) operator, along with its opposite, the > (“greater than”) operator, are called conditional operators. Notice what happens when you change from < to >:
if (bankAcct > 1000) {
System.out.println("Nope. Just stay home. Vegas is too expensive."); }
When you run the code, it looks like nothing happened. But something did happen: The conditional test evaluated to false, hence whatever you have inside the curly braces didn’t run, since 900 is not greater than 1000.
58
14 | Java Branching Statements: if, if-else, and else-if
TIP
When dealing with while loops or if statements, the conditional test (what goes inside of the parentheses) always evaluates to either false or true. In other words, while loops and if statements depend on boolean variables to run tasks. Also, whenever you are comparing, you use ==, not =. What if you wanted to test if bankAcct is equal to 1000? The obvious answer would be to just swap > for =:
if (bankAcct = 1000) {
System.out.println("Nope. Just stay home. Vegas is too expensive."); }
But that doesn’t work. The IDE even gives you the correct option to be used, which is ==:
if (bankAcct == 1000) {
System.out.println("Nope. Just stay home. Vegas is too expensive."); }
The = didn’t work because = in Java is used to assign values to a variable, not to compare. When it comes to comparing two things, you always use ==. Run this code and you still will see nothing because the conditional test resolves to false: 900 is not equal to 1000. 59
14 | Java Branching Statements: if, if-else, and else-if
In addition to if, there’s another conditional keyword called the if-else statement, which gives you branching:
if (bankAcct > 1000) {
System.out.println("Nope. Just stay home. Vegas is expensive."); }else {
System.out.println("You're doing alright. Have fun."); }
Now, by adding else, you can say that you want to display/print out a different message if the if statement evaluates to false:
You're doing alright. Have fun.
Also, change < to > so you get a false—that way, the else branch runs. Here’s the new output:
if (bankAcct > 1000) {
System.out.println("Nope. Just stay home. Vegas is expensive."); }else {
System.out.println("You're doing alright. Have fun."); }
You're doing alright. Have fun.
60
14 | Java Branching Statements: if, if-else, and else-if
In addition to ==, there’s also the opposite of this operator: not equal. To express this new conditional operator, you use !=. If you swap > with !=, the statement inside of if (the first printout) would show in the console because 900 is not equal to 1000.
!=
if (bankAcct != 1000) {
System.out.println("Nope. Just stay home. Vegas is expensive."); }else {
System.out.println("You're doing alright. Have fun."); }
Nope. Just stay home. Vegas is expensive.
So you can branch your programs using if and if-else statements along with conditional operators (==, , !=) to create fairly complex programs that can evaluate a conditional expression and decide what needs to run. As simple as it may sound, this in essence is what programming is all about: manipulating data (evaluating conditional tests, assigning values, and calculating an output or doing something). Next, write the following code: ^ Create a char variable and assign A . ^ Create an if-else statement. ^ Write the printouts.
61
14 | Java Branching Statements: if, if-else, and else-if
char grade = 'A';
if (grade == 'A') {
System.out.println("A is for Awesome!"); }else {
System.out.println("Did you get a B, a C, or an F?"); }
Run this code and it prints out the following:
A is for Awesome!
Change grade from A to B:
grade == 'B'
Run this code and now it prints this:
Did you get a B, a C, or an F?
This is exactly what you would expect. But what if you wanted to account for a B, C, or F and output a meaningful message? How would you do that?
62
14 | Java Branching Statements: if, if-else, and else-if
The else statement does not have a condition listed alongside it like the if statement does. The else statement always goes along with the if statement, like this:
if(condition){ //statements }else {
//statements }
You can use else to chain several if statements together, which gives more power for branching your code flow! By adding an else-if, you can pass a conditional test that, once evaluated to a boolean, will either print the statement inside the code block or not. So if grade is equal to B, then B is for Beautifully done!.
else if (grade == 'B') {
System.out.println("B is for Beautifully done!"); }
TIP
Avoid using long chained else-if statements when possible; it makes the code too hard to read.
63
14 | Java Branching Statements: if, if-else, and else-if
You can keep going with the chaining by adding more else-if statements to run if the conditional tests evaluate to true. The complete code looks like this:
if (grade == 'A') {
System.out.println("A is for Awesome!"); } else if (grade == 'B') {
System.out.println("B is for Beautifully done!"); } else if (grade == 'C') {
System.out.println("C is for Careless"); } else {
System.out.println("F is for Future unknown"); }
Now, anything that is not an A, B, or C is going to fall under the F category. If you change grade to D and run the code, you’ll see this:
F is for Future unknown
So whenever you want to add a condition to the else statement, since it doesn’t come with one, you should use the else-if, because then you’ll have a way to add a condition and therefore be able to branch your statements even more. If and else statements are good for situations with two possible conditions.
It’s true that you could keep chaining your if-else statements to account for several different conditions, but there’s a more flexible and cleaner way to achieve the same goal: the switch statement.
64
14 | Java Branching Statements: if, if-else, and else-if
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
65
15 Multiple Branches with the Java switch Statement
TABLE OF CONTENTS
66
15 | Multiple Branches with the Java switch Statement
The switch statement can test for a variety of different conditions and respond accordingly. A switch statement is the best candidate for cases where you have more than two possible conditions. Let’s translate the final example from the previous lesson into a switch statement. (Note that you keep the char variable intact because you still need that.)
char grade = 'A';
if (grade == 'A') {
System.out.println("A is for Awesome!"); }else {
System.out.println("Did you get a B, a C, or an F?"); }
You start by writing the keyword switch and finish the code block with curly braces:
switch(){ }
Inside of the parentheses is where you need to pass the condition—in this case, the variable that will be checked to see if a match was found. So you pass the grade variable in:
switch(grade){ }
67
15 | Multiple Branches with the Java switch Statement
Inside the code block is where you isolate all the possible cases and dictate how to respond accordingly. So you say that in cases where grade matches A, here’s what you want to happen:
switch(grade){ Case 'A' :
//do stuff break; }
The colon tells the compiler to run whatever is after the colon until it sees the next keyword, break, which indicates to get out of this particular case and go to the next one. And you continue to do the same thing for other cases:
case 'B':
System.out.println("B is for Beautifully done!"); break; case 'C':
System.out.println("C is for Careless"); break;
You can’t use the else statement as you did with if statements; instead, you use the default statement:
default:
System.out.println("F is for Future unknown");
68
15 | Multiple Branches with the Java switch Statement
TIP
If you don’t add the break keyword in a switch statement, you’ll get an undesirable result. Also, the default statement is optional in switch statements.
Run the code, and the output should be the following, assuming the grade variable is still D:
F is for Future unknown
Change grade to B and you should see this:
B is for Beautifully done!
Switch statements make your code much cleaner and easier to maintain.
If you don’t add the break keyword in a switch statement, you’ll get an undesirable result, so always make sure to include it. You can also add more than one statement inside the switch statement:
case 'A':
System.out.println("A is for Awesome!"); System.out.println("Made mom proud."); break;
69
15 | Multiple Branches with the Java switch Statement
Change grade to A and run the code and the output is this:
A is for Awesome! Made mom proud.
Both printouts show in the console. You can use as many statements as you want. Optionally, you can even add a code-block body with curly braces, like this:
case 'A': {
System.out.println("A is for Awesome!"); System.out.println("Made mom proud."); }
Run the code and you’ll see the same result:
A is for Awesome! Made mom proud.
70
15 | Multiple Branches with the Java switch Statement
Exercise Create a program that will simulate an ATM transaction. 1 Create a String variable called command that can hold Withdraw or Deposit commands. 2 Create an int variable called balance, which holds 1000. 3 Create another int variable called amount, which holds 100.
If the command value is Withdraw, then subtract amount from balance and print out this:
Your balance used to be 1000 and now is 900.
If instead the command value is Deposit, then print out this:
Your balance used to be 1000 and now is 1100.
Use the switch statement for this exercise.
71
15 | Multiple Branches with the Java switch Statement
Solution There are different ways to solve this, and the way you do it may be different from what you see here, but as long as you get the correct results, then anything is fair game. You create all the variables and then use the switch command to determine which case needs to execute:
String command = "Deposit"; int balance = 1000; int amount = 100;
switch (command) {
case "Withdraw":
balance = balance - amount; // or balance -= amount
break;
case "Deposit":
balance = balance + amount; // or balance += amount
break; }
System.out.println("Your balance used to be 1000 and now is " + balance );
Notice that there are alternative ways to decrement (subtract) and increment (add) numbers. Each alternative is noted as a comment, which follows two forward slashes (//) and is thus ignored by the compiler.
72
15 | Multiple Branches with the Java switch Statement
Although the first way that’s listed for Withdraw (balance = balance amount) works, the second is a more succinct way of expressing the same thing: balance -= amount. Which to use is your choice, but most often you’ll see the second way written. When you run this code, you should see this result for the Withdraw case:
Your balance used to be 1000 and now is 900.
And here’s the Deposit case:
Your balance used to be 1000 and now is 1100.
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
73
16 The do-while Loop and the for Loop in Java
TABLE OF CONTENTS
74
16 | The do-while Loop and the for Loop in Java
In addition to the while loop, there is a type of loop in Java called the do-while loop. To create a do-while loop in code, while () is written at the end:
do {
}while ();
Here’s an example of the whole structure:
int limit = 10;
int counter = 1; do {
System.out.println("We keep counting..."); counter++;
}while (counter < limit);
If you run the code, you get this output:
We keep counting... We keep counting... We keep counting...
…
With a do-while loop, the statements inside the loop are executed at least once, even if the loop condition is false.
75
16 | The do-while Loop and the for Loop in Java
To test this in the code, change < to >, which will make the condition false. When you run the code, the result is this:
We keep counting...
This tells you that even though the condition evaluated to false, the contents inside the loop ran once. So if you want to have statements executed once even though the conditional test is false, then use a do-while loop. In any other case, a while loop will do. Notice how pretty much anything else about the do-while is similar to a while loop: You still need to have some sort of a counter or else you end up with an infinity loop, which is bad news. The while and do-while loops are great, but the for loop is more powerful and lets you do more in Java. The for loop is Java’s most complex loop statement. It allows you to repeat a section of a program a fixed number of times, and you get to control the flow. Here’s how to construct a for loop:
for (int i = 0; i < 10 ; i++) { //more code goes here }
76
16 | The do-while Loop and the for Loop in Java
The for loop has three parts: ^ the initialization part (int i = 0;), where you are initializing the int i variable and giving it 0; ^ the conditional section (i < 10;), where you have the conditional test, which resolves to either true or false; and ^ the change section (i++), where in this case you are incrementing the variable i each time the loop runs. Let’s output the i value each time the loop runs:
for (int i = 0; i < 10 ; i++) {
System.out.println("Counter is " + i); }
Run the code and here’s the output:
Counter is 0 Counter is 1
… Counter is 0 Counter is 1
77
16 | The do-while Loop and the for Loop in Java
On the first run, i is 0, which is less than 10, and then the enclosed statement is run, so you see "Counter is 0" in the console. Next, i is incremented by 1, so now i is 1. The comparison continues: 1 is still less than 10. This time you see "Counter is 1" in the console. Then, i is incremented by 1 again, so i is now 2, and so on. This continues until the conditional test is no longer true—e.g., when i is 10, the for loop stops because 10 is not less than 10. This is why the last output you see is "Counter is 9". The great thing with for loops is you can add other conditional statements inside of them to do more complex calculations/computations, like this:
for (int i = 0; i < 100 ; i++) { if (i % 2 == 0){
System.out.println(i + " is a multiple of 2");
}
System.out.println("Counter is " + i); }
TIP
The counter variable (int i) is also called an iterator. An iteration is a single trip through a loop. You add an if statement to capture all of the numbers that are multiples of 2 and print those out. You are now leveraging the modulo, or remainder, operator you learned about in lesson 12.
78
16 | The do-while Loop and the for Loop in Java
You can increase 100 to 1000, or 100000, or an even higher number, and the code still works. The larger the number you use, the more time it may take (depending on your computer speed), but you’d get the expected results. With for loops, the sky is the limit. And they make it easy for you to quickly do some complex calculations with conditional statements and get results.
Exercise Use a for loop to count backward from 10 to 1. Here’s what the output should be:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
(Hint: Decrement, not increment.)
Solution for (int i = 10; i >= 1; i--) { System.out.println(i); }
79
16 | The do-while Loop and the for Loop in Java
You must initialize i with 10 since that’s your starting point. In the conditional section (i >= 1), you want to make sure that i is greater than or equal to 1 because 1 needs to be included in the countdown. If you remove >= and replace it with >, the countdown will omit the 1 and end with 2, which is not what you want for this exercise. The change section (i--) is where the backward counting happens, since you decrement each time you loop through and update the iterator i by 1.
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
80
17 Arrays in Java
TABLE OF CONTENTS
81
17 | Arrays in Java
Unlike variables, which can only hold one thing at a time, arrays store a collection of related variables that share the same type. So if you need to store a list of integers, for example, you would use an array. You can think of an array as a container that holds smaller containers inside it. Each smaller container is called an element. You put values inside of the element. Each element has its associated index—an ID for that element. Array indexes start at 0, not 1, so the first element is index 0, the second is index 1, etc. The great thing about arrays is that they have a length—how many elements are available in the array—so you can also specify the length of the array, which gives you a lot of flexibility. If you wanted to create an array that holds integers, you’d start by writing this:
int[] ages = new int[5];
Notice the square brackets ([]) after the keyword int. This is how you tell the computer that you want to create an array in Java. The new keyword in Java tells the computer to reserve a spot in memory for, in this case, an array. Now you have an empty array with length 5 (same as having five smaller containers).
82
17 | Arrays in Java
Next, you need to add integers inside of this array. To do that, you need to specify which smaller container—or slot—you will be adding the int into. This is when the index comes in handy. The index is the ID for each slot in your array, so you use the index to specify the slot to add the int to, like this:
ages[0] = 10;
The first slot (0) has a value of 10, and you keep adding other integers to your array following the same syntax:
ages[0] = 10; ages[1] = 9;
ages[2] = 1;
ages[3] = 8; ages[4] = 2;
Now all of your five slots are filled with integers. To print out the second slot’s content, for example, you write this:
System.out.println(ages[1]);
Run the code and it prints out this:
9 83
TIP Array indexes start at 0, not 1.
17 | Arrays in Java
What happens if you run this code?
System.out.println(ages[5]);
When you run this code, you’ll get an error like this:
Exception in thread "main" java.lang. ArrayIndexOutOfBoundsException: 5
The compiler is telling you that it can’t reach index 5 because there is no index 5. Your array only has up to index 4. If you try to reference an index that doesn’t exist, you’ll get an error. You can also create an array and initialize it with values right from the start. Here’s how you do it:
int[] ages = { 10, 9, 1, 8, 2 };
The difference here is that you didn’t explicitly set the size of the array like in the previous example. Also note that you use curly braces instead of square brackets. Each item inside of the array is separated by a comma. The way to access each element of the array is the same:
System.out.println(ages[1]);
84
17 | Arrays in Java
This should still print out this:
9
You can use a for loop and loop through an array and retrieve all of its contents:
for (int i = 0; i < 5; i++) {
System.out.println(ages[i]); }
In the for loop, you need to make sure you pass the length of the array (number of slots) for the conditional test. In this case, you pass 5 because you know that the array you’re looping through has five slots, or the length of the array is 5. The variable i, the iterator, is going to be updated each time the loop runs, and each time you pass it as the index so you can retrieve, or iterate, through your array. Run this code and you’ll see this:
10 9 1 8 2
85
17 | Arrays in Java
On the first pass, i is 0, and i is passed into the array as the index age[0], so you get 10, and so on. Notice that you had to hard-code the length of the array in order to add it to the conditional test of the for loop. In this case, it’s fine since you know the length of the array, but if you updated the array, you would need to also update the length by hand in the for loop. There’s a better, cleaner way to do this. You can access the length of an array by simply writing this:
ages.length
The period here is called the dot operator, which means that you access a property of the array that will return the length of the array. Now you can always be sure that you get the size of the array consistently without having to worry about changes or updates to the array, which would change the length of the array. Run the code and you’ll see the same results as before. But if you were to change the array, perhaps to something like the code that follows, you no longer have to update your conditional test in your loop since you are now directly accessing the length property of the array, so it will always pass the correct length.
int[] ages = { 10, 9, 1, 8, 2, 90, 67 };
86
17 | Arrays in Java
You can do all sorts of things inside of your loop. For example, you can only print multiples of 2:
if (ages[i] % 2 == 0)
System.out.println(ages[i]);
Notice the lack of braces in the if statement. If there’s only one statement inside the if statement, you can optionally remove the curly braces. Run the code and you should see only multiples of 2 showing from your array:
10 8 2
90
With the power of arrays combined with loops and branching, you can pretty much do anything in Java!
87
17 | Arrays in Java
Exercise Let’s say you have the following array of integers:
int[] ages = {20, 30, 100, 45, 10, 33};
Write a for loop that will do three things: 1 Add all of the age numbers in the array into one variable called ageSum 2 Calculate the average age by dividing ageSum by the length of the array and assign the result to a new variable called averageAge
3 Print out a message that reads “The average age is [pass the averageAge here]”
(Hint: Make sure to initialize ageSum and averageAge variables outside the for loop (int ageSum = 0; and int averageAge = 0;).)
88
17 | Arrays in Java
Solution int[] ages = {20, 30, 100, 45, 10, 33}; int ageSum = 0;
int averageAge = 0;
for (int i = 0; i < ages.length ; i++) { ageSum = ageSum + ages[i]; //calculate average
averageAge = ageSum / ages.length; }
System.out.println("The average age is: " + averageAge);
The bulk of the work happens inside the for loop when you write ageSum = ageSum + ages[i]. Initially, ageSum is 0. On the first pass through, int i is also 0, which means you get the first element of the array, 20, and add it to ageSum, which is still 0, and 0 + 20 is 20. You then assign 20 to the ageSum variable. On the second pass through, the same thing happens, except now i is 1, which also means you pass it as the index to get the corresponding element (ages[1]), 30, so 30 + 20 (the current value of ageSum) is 50. Then you update the ageSum variable with the new result, 50, and so on. This computation continues until you’ve exhausted all numbers in the array: when i < ages.length no longer holds to be true.
89
17 | Arrays in Java
Notice that there is also another calculation happening at the bottom of the loop:
averageAge = ageSum / ages.length;
That’s where you calculate the average age. Note how the averageSum is calculated each time the loop runs, and on each pass the averageSum variable is updated accordingly. Note that you can write the following statement in two different ways, and both are valid options. You will likely see the second option used more often in programs. 1 ageSum = ageSum + ages[i]; 2 ageSum += ages[i];
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
90
18 Creating Objects in Java
TABLE OF CONTENTS
91
18 | Creating Objects in Java
In programming, objects are the building blocks that can be used to create something more complex. An object encapsulates tasks, or certain functions that can be plugged in to a bigger system. If you think of a computer program as a group of objects that interact with each other, then you can design a program that’s more reliable, easier to understand, and, most importantly, reusable in other projects or programs! If two people have the same kind of car (make, model, year, etc.) and one car’s engine blows up, a qualified mechanic could remove the other car’s engine and put it into the first one and it would work. The first car would have reused the second car’s engine (object). There’s no need to make a new engine from scratch! In order to create objects, you need a plan, or a blueprint, of how the object is going to behave and what kind of properties the object will have. In Java, this blueprint is called a class—which is the representation of an object. If you want a blueprint of a car, then you need to think about what a car has (properties or attributes) and what a car does (behaviors or functions). Once you know the properties and behaviors of the object, then you can create the class (your blueprint).
TIP The concept of objects in Java can be a bit difficult to conceptualize at first. Just remember that a Java object is like any physical object in the real world: They have properties and behaviors. 92
18 | Creating Objects in Java
To create a class in Java, you use the class keyword, like this:
class Car { }
Make sure you are outside of the main class. You need to add attributes or properties of the car. A car is a very complex system, so let’s keep it simple: A car has a color, a make, and a model year. So let’s add those attributes to your Car class:
class Car {
String color; String make;
int modelYear; }
To express behavior, you use methods to express and expose what a car does. Let’s add a few methods or behaviors, such as starting, driving, and stopping:
public void start() { }
public void drive() { }
public void stop() { }
93
18 | Creating Objects in Java
There are a few new keywords here: public and void. These methods can be accessed by any other class (in other words, they’re public) and they won’t return a value, hence the void name. Let’s add printouts in each of the methods:
public void start() {
System.out.println("Starting the car..."); }
public void drive() {
System.out.println("Car moving now..."); }
public void stop() {
System.out.println("Stopping for gas..."); }
So you have a solid blueprint for your Car object. Remember, this is a class, the blueprint of an object—not the actual object yet. This is how you create, or instantiate, the actual object you can use in Java (using your class, or blueprint). You go up to main and write the following:
Car myCar = new Car();
So, just like you do with variables, you create a variable named myCar of type Car and assign it to new Car();. All you are doing here is telling the computer to create a space in memory for a Car object to live in. 94
18 | Creating Objects in Java
Now you have an actual Car type, or Car object! You can use your myCar reference to access the behaviors and the attributes of the Car object as well as set those attributes! Run the code and you’ll see this:
myCar.start();
Starting the car...
You set attributes:
myCar.color = "red";
System.out.println("My car is " + myCar.color);
Run the code and it prints out this:
My car is red
Recall that there are two main data types in Java: primitive and reference types. You’ve already worked with primitives, and now you’ve created your first reference type! The myCar object is a reference type because it references the Car object. Remember that a class is not an object. A class merely encapsulates the properties/attributes and behaviors of what the object will have once instantiated. 95
18 | Creating Objects in Java
Think of a class as the blueprint for a house. A constructor will use the house blueprint to build a house. The house blueprint is not a house.
TIP A class in Java is a blueprint.
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
96
19 Class Constructors in Java
TABLE OF CONTENTS
97
19 | Class Constructors in Java
If you print out myCar in the console, you get what looks like a long string of gibberish:
System.out.println(myCar);
....Car@6d06d69c
But it’s not actually gibberish—it’s the location of the object in memory! That’s pretty cool, but it’s not that helpful. Let’s take this one step further and try to access one of the attributes:
System.out.println(myCar.color);
Run this and you get a null, which simply means “value not set.” Since the property color hasn’t been set to anything, null is given to the reference attribute. Although you could set that attribute/property to something yourself, wouldn’t it be better if you could delegate that task to another method? That’s when constructors come into play. A constructor in Java is a method that has the same name as the class, and it constructs your object so that when you instantiate it, the object is not just an empty, useless object.
98
19 | Class Constructors in Java
Let’s take a look in code:
public Car(String color, String make, int modelYear) { this.color = color; this.make = make;
this.modelYear = modelYear; }
Notice that the name of the constructor has to be the same as the class name. You are passing parameters into your constructor (method) that are used to set up your class attributes to whatever is passed as parameters. The this keyword refers to “this class,” and you access “the current” class attributes/properties or fields. Notice also that the moment you add the constructor, your class instantiation no longer works. Why? When you instantiate an object, you say this:
....= new Car();
And what’s the name of your constructor? It’s Car! So this tells you that whenever you instantiate an object, you are actually calling the class’s constructor! Why? You’re calling it to construct the object.
99
19 | Class Constructors in Java
So why didn’t you have any issues previously with just instantiating your Car object by just writing the following?
Car myCar = new Car();
That’s because every class you create in Java implicitly has an empty constructor that looks like this:
public Car(){ }
However, the moment you explicitly create a constructor and pass parameters in, then Java will ignore the empty constructor and use the new one you created. And that’s why you have that little complaint showing now in main. To fix it, you just have to pass the arguments into the constructor:
Car myCar = new Car("Red", "Toyota", 1989);
Run the code again and you should see this:
Red
This is because the color property of the Car object is set to Red.
100
19 | Class Constructors in Java
You can extract other properties/attributes as well:
System.out.println(myCar.color + " " + myCar.make + " " + myCar.modelYear);
Run the code and this is the output:
Red Toyota 1989
Constructors are very helpful because they force your objects to be instantiated with some values, which prevents having empty objects. Although you could have classes without constructors, it’s best to have constructors when you create classes.
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
101
20 Methods: Passing Arguments, Returning Values
TABLE OF CONTENTS
102
20 | Methods: Passing Arguments, Returning Values
Essentially, a method is a code block where you can have statements and write your logic in. Methods are usually called to execute their content (statements). For instance, the main method is called by the compiler to execute what’s inside of it—hence, the main method is the entry point to a Java program.
public static void main(String[] args) { }
The main method has a few keywords: public, static, and void. The void keyword in Java means that the method returns nothing, or it doesn’t have a return type. Does this mean that methods can have types, too? Sort of. This tells you that you can have methods that return a result to you. For instance, you can create a method that calculates a sum of two numbers like this:
public void sum() {
System.out.println(10 + 10); }
There are two ways you can call this function in main. This is the first way:
new FirstJava().sum(); 103
20 | Methods: Passing Arguments, Returning Values
You instantiate an object (remember that main is actually inside of a class!). This is a simplified way of instantiating an object, especially if you don’t need a reference. And then you call the sum() method. Run the code and you’ll see this:
20
Even though this way is valid, wouldn’t it be much easier if you called sum() inside of main? Yes, it would be much easier and quicker; however, to be able to do that, you need to change a few things. First note that if you try calling sum directly in the main method, you get an error:
error: non-static method sum() cannot be referenced from a static context sum();
As the error tries to explain, main is a static method, which means it can only call other static methods inside of it. In a nutshell, the main method is static so that the compiler can call it without the creation of an object or before the creation of an object of the class. But creating objects is what makes Java an awesome object-oriented programming language! Isn’t creating objects a good thing? 104
20 | Methods: Passing Arguments, Returning Values
Yes, objects are great, but they do take up memory, and you should avoid having to create objects unnecessarily whenever possible, especially if it’s for things that don’t really need object instantiation, such as to run the main method. To be able to call sum() in main, sum must also be static.
public static void sum() {
System.out.println(10 + 10); }
Comment out the object instantiation:
public static void main(String[] args) { //new FirstJava().sum(); sum(); }
And sum() can now be called inside of static main! Run the code and it will output 20. Let’s improve sum by adding a few arguments:
public static void sum(int a, int b) { System.out.println(a + b); }
sum(10, 10);
105
20 | Methods: Passing Arguments, Returning Values
Next, since you changed sum to have arguments, those are now expected when you call sum in main. Run this and you’ll see the same 20 printed out. Even though you still get the same results, it’s important to note how flexible sum is now. It will always take in whatever is passed to it as arguments and calculate the sum and print out the result! But sum is still a void, meaning that it doesn’t return a value you could use to do other things with. For instance, if you wanted to capture the sum and put it into a variable and later multiply by another number coming from another method, it’s virtually impossible to do that the way things are now. To make sum even more flexible, you attach a return type to it—to signal the compiler that you are expecting a value of a certain type to be returned. If you want sum to return an integer, then you do the following:
public static int sum(int a, int b) { // System.out.println(a + b); return a + b; }
The return keyword must be added so that the function actually returns a value: an int type because you changed from void to int.
106
20 | Methods: Passing Arguments, Returning Values
Now you can pass the sum -returned value to a variable:
int total = sum(10, 10);
System.out.println("The total is " + total*10);
You can even do further calculations and then print out a text, like this:
The total is 200
Exercise Look at the following code:
String greet = "Hello, friend! How are you doing?";
if (greet.contains("Hello ")) { System.out.println("Yep!"); }else {
System.out.println("Nope!"); }
Without running this code, what will be printed out in the console: Yep! or Nope!? Why?
107
20 | Methods: Passing Arguments, Returning Values
Solution Nope! will be printed out in the console.
Even though greet does contain the word Hello, remember that in Java a space is also counted as a character! So when you write Hello , that’s not the same as Hello, or Hello.
Resources Schildt, Java. Sierra and Bates, Head First Java. Tutorials Point, https://www.tutorialspoint.com/java/.
108
21 Java Getters and Setters
TABLE OF CONTENTS
109
21 | Java Getters and Setters
Returning to the Car class from previous lessons, let’s add one more field/ property/attribute or instance variable:
int weight;
public Car(String color, String make, int modelYear, int weight)
this.weight = weight;
Then, let’s add this to the constructor:
Car myCar = new Car("Red", "Toyota", 1989, 100);
And then fix the Car object instantiation:
System.out.println(myCar.color + " " + myCar.make + " " + myCar.modelYear + " " + myCar.weight);
Run the code and you should see this:
Red Toyota 1989 100
Even though you are using the constructor to construct your object, you still can directly access the attributes by using the dot operator (.) to set the weight attribute to 8998:
myCar.weight = 8998; 110
21 | Java Getters and Setters
Run the code and the printout will be this:
Red Toyota 1989 8998
Let’s now set the weight to -10.
myCar.weight = -10;
Run the code and the result is still fine:
Red Toyota 1989 -10
So now you have a red 1989 Toyota that weighs −10. Sure, the code works fine, but there’s a problem. Imagine you are building out a very complex class that is part of a bigger system at a car factory. And then you ship your class off to another programmer, who also has another class that does other cool stuff for the car assembly line. And then another programmer uses your class and directly invokes the weight attribute and by mistake sets it to -10. You can see that you’d have a big problem here. How can a car weigh −10? Even though you trust that other programmers are intelligent people who would never intentionally set weight to -10, you must protect your classes from such catastrophic mistakes. 111
TIP Always protect the attributes of your classes by making them private.
21 | Java Getters and Setters
You should make your class-attribute variables private so that no one can directly access them and set them to undesired values. So let’s do that:
private String color; private String make;
private int modelYear; private int weight;
Now you have other problems: You can’t access any of these from main. While this is a problem in that your code now won’t compile, it’s actually a good thing because you’re now forced to set up your class properties in a more secure way by using getters and setters!
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
A setter method sets up a class attribute to either have an initial value or check for invalid values (such as setting weight to -10). A getter method exposes those set attributes to other classes so that those other classes can only access attributes through getters. It’s a mechanism of protecting a class’s internal state and attributes. Now the only way you can access and tamper with the attributes is through getters and setters.
112
21 | Java Getters and Setters
You set the weight and the color attributes using setters:
myCar.setWeight(8998);
myCar.setColor("Blue");
Instead of accessing the weight attribute directly, which you can no longer do because the attribute is now private, you use a getter method, getWeight(), to retrieve the weight value:
myCar.getWeight();
Run the code:
System.out.println(myCar.getColor() + " " + myCar. getMake() + " " + myCar.getModelYear() + " " + myCar.getWeight());
And the result is this:
Blue Toyota 1989 8998
113
21 | Java Getters and Setters
You really haven’t solved the problem of setting undesirable values to your attributes, but this is one step forward. Now you can easily add an if statement to check the values before you set them up. So if you detect that weight is less than or equal to 0, set the weight attributed to a default value of 1000:
public void setWeight(int weight) { int defWeight = 1000; if (weight