The Creating Coder

Live by the code

Category Introduction to Java

Coding Challenge 8

For the 8th Coding Challenge, we will make a program that has 2 methods. The first method will be a user-made method: static void makeCoffee. This method will also have a parameter: boolean wantsCoffee.

Within the user-made method, we will have an if statement that only executes when wantsCoffee is true. The if statement (when true) should print the following: Your coffee is brewing

Inside of our main method, we will call the user made method and pass the value true to our method with an argument.

After compiling and running our code, the output should be:

Good luck and if you get stuck, scroll down to the bottom of the screen for help!

methods, parameters, arguments

methods, parameters, arguments

methods, parameters, arguments

methods, parameters, arguments

methods, parameters, arguments

methods, parameters, arguments

methods, parameters, arguments

methods, parameters, arguments

methods, parameters, arguments

Great job and see you next Chapter!

GitHub link.

Lessons 28 – 31 Review

Which escape sequence starts a newline?
\t
\\
\n
Which logical operator is known as OR?
&&
||
!
Classes are typically nouns, whereas methods are typically…
Verbs
Adjectives
Conjunctions
_________ are the variables that are declared within the parenthesis of a method and only visible within that method
Parameters
Arguments
_________ are the input given when the method is called upon
Arguments
Parameters

Lesson 31: Method Parameters and Arguments

When working with methods, there will be times that we want to keep variables only within our method.  Java has a way of doing this through the usage of parameters.  Parameters are declared within the parenthesis of our method.  Let’s go over an example of a method with parameters.

In the example above, we have the user made method and Java’s main method.  Within the printingMethod’s parentheses, we have the parameter String str.  This is the variable that we want to create and use solely within the printingMethod() method.    

By adding the parameter String str, we now have a String variable that will only exist within the confines of the method.  For example, if we were to try and print out String str in the main method, we would get an error message stating that it cannot find the symbol.

Also, by adding a parameter into our method, we make it necessary to put a String value into the method when it is called within the main method.  Otherwise, our code will fail to compile.  

In the code above, we have the String coffee within the method when it is called.  This can be referred to as an argument

Also, it is important to note that you can pass as many parameters and arguments as you want.  Just be sure to separate each separate value by a comma.  Look at the example given below:

After compiling and running the code above, we get the following output:

To summarize, parameters are the variables that are declared within the parenthesis of a method and only visible within that method.  Arguments are the input given when the method is called upon.  Also, there is no limit to the amount of parameters/arguments you can add to your method.

Interviewers can often ask questions about the difference between parameters and arguments, as well as what they accomplish. If you are aspiring to make coding a career choice, it would behoove you to be able to know and explain both concepts.

GitHub link.

Lesson 30: Methods

Methods are one of the fundamentals of programming.  As you might recall from our object-oriented programming lesson, we talked about how classes are typically nouns and methods are verbs.  They help reduce redundancy by being able to use them an unlimited amount of times throughout our code for different instances.

Thus far, we have been putting most of our action-taking code within a class and main method.  However, as our programs start to become more complex, it will be important to split our code into different methods, classes, and objects to make troubleshooting easier.  Now let’s look at a method in action.

In the example above, we have two separate methods.  The first one listed is a user created method, and the second one is our main method.  

In future lessons, we will cover the keywords static and void.  For now,  just know that static means that the data is associated only within its class, but not any created instances of it.

The keyword void means that we do not want a return value.  For example, if we wanted a String returned, then the method would look like static String methodName(){

After the first two keywords(static and void), we see printingMethod(){ }.  The method name is assigned by the programmer.  It is then followed by parentheses and a set of brackets.

What we put in the brackets, is what will be executed whenever we call the method.  In the example above, we have a print statement.  

To call the method in this example, all we must do is type our method’s name and parentheses in our main method.

If we do not call printingMethod() in the main method, it will not print.  Also, if we call the method twice, it will perform its function twice by printing the sentence twice. 

Also, you can add the method before or after the main method and it will work regardless.  

Methods are an essential component to object-oriented programming and we will continue to see and use them in future lessons.

GitHub link.

Lesson 29: Logical Operators

Thus far, we have gone over various operators that we have been using to create our Boolean expressions.  However, we have been limited by only using one Boolean expression at time.  In this lesson, we will take a look at logical operators.

In Java, there are 3 logical operators:

Symbol MeaningCode
AND&&
OR||
NOT!

The logical operator && is used when we want to have two or more conditions evaluated.  Let’s look at an example.

In the if statement above, we can see that we have two separate conditions that are joined by the && symbol.  First, the boolean variable likesCoffee is true.  Next, since the first condition is met, the && operator moves to the 2nd condition to see if it evaluates to true.  Because both of the conditions are met, the if statement prints out: Want some more coffee?.

&& is sometimes referred to as a short circuit operator. This is due to the fact that if the first condition does not evaluate to true, then it does not bother with evaluating the 2nd.  Now let’s look at an example of the OR operator ||.

In the example above we have an OR logical operator represented as || in between two separate conditions.  When we use an OR operator, it means that conditions do not have to be met.  Instead, only one of them must be met in order for the if statement to execute its code.  In this case, although hotTemp does not evaluate to true, the if statement will still execute.  This is because the likesCoffee evaluates to true and forces the if statement to print: An iced coffee sounds good.

The NOT logical operator ! is used to reverse values.  Let’s look at an example.

In the code above, we can see that we have the NOT operator ! in front of the boolean value hatesCoffee.  This if statement translates roughly into “if the bool value hatesCoffee does not equal true, then execute code within brackets.”  

As you can see, the Boolean value hatesCoffee does indeed equal false.  Therefore, the program above executes the if statement and prints I like coffee.

In future lessons, we will start to experiment more and see examples of how these logical operators can be paired together and used with parentheses to further specify the execution criteria to suit the programmer’s specific needs.

GitHub link.

Lesson 28: Escape Sequences

In past lessons, we have gone over a couple of different ways we can manipulate Strings.  We have learned about various print methods and adding spaces with quotation marks to get our desired output.  In this lesson, we are going to go over escape sequences that can help simplify some of our string manipulation, as well as fix certain issues we run into when printing special symbols.

The term “escape sequences” is derived from the need to “escape” from its normal usage.  For example, say we want to print a String that has quotation marks “”.  However, we know that Java uses quotation marks to begin and end a String.  Let’s look at what happens when we try to make and print a String with quotation marks.

(The code above does not compile or run)

Instead of Java knowing that we want to print quotation marks inside of our String, it does what it is supposed to do – it treats the two sets of quotation marks as two separate Strings.  To escape Java’s standard usage of quotation marks, we use the escape sequence.  In this instance, the escape sequence for quotation marks is \” .  Let’s now try using the escape sequence for quotation marks to fix our code:

By just adding a backslash in front of the quotation marks, we now get the desired outcome:

As we know that there are quite a few different special characters used in Java.  Look at the list below to see some other important escape sequences.

Escape SequenceAction
\tInserts a tab indentation
\nStarts a new line
\rInserts a carriage return (similar to new line)
\bInserts a backspace
\\Allows for the usage of a backslash \ in text
\’Allows for the usage of ‘ in text
\”Allows for the usage of ” in text

Go over the table above to familiarize yourself with the escape sequences listed.  Also know that although carriage return is still used in some cases, we will typically be using \n or using the println() method to start a new line.  In fact, carriage return refers to typewriters and when the carriage had to be manually returned by hand!  Great job and see you next lesson!

GitHub link.

Coding Challenge 7

For the 7th coding challenge, we will make a program that contains a for loop and 2 int variables.  The program’s purpose will be to act as a countdown timer for NASA.  We want the countdown to start at 10 and finish at 1.  Feel free to name the variables on your own.  However, be aware that for loops generally use int i as its variable type and name.  When you are done, your program should print something out like the following:

Also, know that the first and last statements in the output do not have to be within the for loop.  In fact, it is best if you leave it out of the loop.  As always, if you can’t figure it out, feel free to scroll down.  Good luck!

for loops

for loops

for loops wordpress won’t leave spaces

for loops

for loops

See how we used the decrement operator to take 1 away from int i every loop?  Awesome job and see you next chapter!

GitHub link.

Lesson 27: The Modulus Operator

In some of the earlier lessons, we went over the 4 most used math operators used in Java.  Those four included:

Addition+
Subtraction
Multiplication*
Division/

Now that we have a little practice underneath our belt in Java, we are going to introduce a new math operator that you’ve probably never seen.  This new operator is called: the modulus operator %.  

The modulus operator uses division and outputs a result.  However, the result is not the dividend.  Instead, it is the remainder.  In other words, it is the number left over if a number does not divide evenly.  Let’s look at an example to better understand.

In Example 1, we can see the equation 9 % 4.  As we well know, 9 is not evenly divisible by 4.  Therefore, because we are using a modulus operator, we know that 4 goes into 9 twice and leaves us with 1 leftover.  Hence, the result for example 1 should be 1.

In Example 2, we have 9 % 3.  Knowing that 9 is evenly divisible by 3, we can determine that there will not be a remainder.  Therefore, we know that the result for example 2 should be 0.

Let’s take a look at the output below:

Sure enough, we had a remainder of 1 for the first example, and no remainder for the second example.  

Although we haven’t seen any opportunities for a modulus operator yet, in future lessons we will see it used with more complex math problems.

GitHub link.

Lesson 26: println() vs print()

In the previous lesson, we went over a program that counted to the number 10 using a for loop. Using the System.out.println() method, every loop printed the number on a new line.

However, what if we wanted to print our numbers out on one line?  So far, we have only used the print method System.out.println() .  Today, I’m going to introduce a new printing method that does not start a new line every time it prints something new. This new print method is System.out.print()

When using this new System.out.print() method, is important to know that it leaves no spaces. Let’s take the code from the previous lesson and replace the println() with print().

As you can probably guess, the output from the program above is not a pretty sight to behold:

All the numbers have been mashed together. This is because the print() method is doing its job. Remember, the job of the print() method is only to print, and not to create a new line.

In order to make it more readable for people, we can adjust the grammar inside of the print method and add an if else statement for commas to be added between numbers until it reaches the number 10.

Be sure to notice that we used a println() method first, and then used a print() method for the loop. The code above gives us the following output:

If nothing else, just remember that println() prints whatever is in its parentheses and then moves to a new line, whereas print() does not create a new line or space after it prints.

Great job and see you next lesson!

GitHub link.

Lesson 25: For Loops

In earlier lessons we went over while and do while loops and learned in what cases we would use them.  In this lesson, we will be going over a new loop called a for loop. For loops typically serve a much more specific role, than other loops.  Let’s look over the outline of one:

There are 3 different sections within the parenthesis of a for loop that are each separated by a semicolon.

Section 1 is executed first and assigns a numerical value (typically to an int.)

Section 2 is the condition that must be met to have the loop continue to run.

Section 3 has an increment or decrement operator associated with the value in section 1. 

Then, just like other loops we learned about, we put whatever code we want repeated every loop inside of the curly brackets.

Now that we have a rough idea of what a for loop should look like, let’s look at an actual for loop in action.

In the code above, we have a program that is designed to count to the number 10.  Within the first section of our for loop, we assign the int value i to start at the number 1.  

In the 2nd section, we have the condition that while i is less than or equal to the count number, the loop will continue to run.

In the third section, we have the increment operator that will add 1 to i for every loop.

Finally, within our brackets we tell the computer to print out i every time it loops.  After compiling and running the program, we get the following output:

Just like we hoped, the program tells us what number it is counting to and stops after reaching it. Great job and see you next lesson!

GitHub link.