Nested loops in Java: Video Lecture 11

Nested looping refers to a loop inside another loop. Many applications require to loop over a repeated task. Nested looping is a solution to aid such repetitive tasks. As an example, consider printing ten lines on the terminal, where each line contains twenty asterisks, as shown below.

********************
********************
********************
********************
********************
********************
********************
********************
********************
********************

Printing one line of twenty asterisks can be performed using a loop. We can write ten lines of asterisks by running another loop over it ten times.

The Code used in the Video Lecture

In the video, we wrote a code using nested loops that prints the output of ten lines, where each line contains twenty asterisks. The java program is below. Please save the program in a file named Nested.java.


class Nested{
    public static void main(String[] args){
        int i;
        int j;
        for (i=1; i<=10;i=i+1){
            for (j=1;j<=20;j=j+1){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

The Video Lecture

The YouTube Video lecture is embedded below.

Nested loops in Java

Exercise

Write a program using nested for loop to print the following pattern of asterisks on the terminal.

**********
*********
********
*******
******
*****
****
***
**
*

Transcription of the Audio of the Video

Hi,
This is Dr. Shahriar Hossain. How are you today? I hope that you are enjoying Java programming. In this video, I am going to explain nested loops. Nested looping refers to looping over another loop. Many applications rely on multiple levels of nesting. For simplicity, today we will learn how to use one for-loop inside another.

In this video, we will go over one problem. At the end of the video, we will provide an exercise. We will solve the exercise in the next video.

The problem

The problem we are going to solve is as follows: Print 10 lines, where each line contains 20 asterisks. The sample output is provided below.

[Show the sample output.]

********************
********************
********************
********************
********************
********************
********************
********************
********************
********************

[End of — Show the sample output.]

Analyzing the problem

Let us talk about the problem. Print 10 lines, where each line contains 20 asterisks, or stars, or multiplication symbols.

Let us think about the solution. Notice that we need to draw a line of 20 asterisks.

If we can draw one line that has 20 asterisks, we can repeat the process 10 times.

[Show the hand-written code]

Whatever code we will write should have this structure [as shown on screen.] The first thing is, we will try to print one line that contains 20 asterisks. That is, at first, we will solve this subproblem – print 20 asterisks in one line.

Printing one line of asterisks

Let us write our code in the main method in a class named Nested. Obviously, the name of the file is Nested.java.

Printing 20 asterisks can be done by typing writing System.out.println(“********************”);

Hard coding the asterisks will not make your code easy to change. That is, if someone wants to print fifty asterisks in one line, then you have to change the System.out.println with fifty asterisks.

Printing one line of asterisks using a for-loop

Anyway, we are going to use a loop that iterates over a System.out.print statement 20 times.

I am writing the structure of the for loop. As you can see, this for loop is designed to iterate 20 times. The value of the variable j will vary from 1 to 20 in this loop. Inside the for loop I use a System.out.print statement, which prints just one asterisk. Notice that this is a System.out.print statement not a System.out.println statement. That is, each asterisk will be printed one after another one, without any line.

Let us save the file, compile it, and run the generated class file. Twenty asterisks are printed on the terminal. Notice that my command line, which states “My computer” starts right after the last asterisk. I actually want to print all these 20 asterisks in a line. Nothing else should be here.

A new line

What we have to do is, we have to put a new line right after the last asterisk is printed.

Let us put a newline after the for loop ends. That is, after all the asterisks are printed, this System.out.println statement will print a new line. As a result, the text, “My Computer”, which is the prefix of my command prompt will move to the next line. Please notice again, System.out.println without any content in the parentheses simply prints a new line.

Let us save the file, compile it, and run the generated class file. All the 20 asterisks are now printed in one line. We have printed one line of twenty stars. That means we are done with this part. [Show the hand-written pseudocode.] We have to now implement this part, which is repetition of what we have done so far 10 times.

Repeating the previous loop

Now that we have the code to print just one line, we can repeat this part that prints one line of 20 stars, 10 times. If we repeat this part of the code 10 times, we should have the desired output, which is 10 lines, where each line has 20 asterisks.

To repeat this part 10 times, we need another for loop. To control that other for loop, we will need a variable. Let the variable be “i”. We write a for-loop, in which the variable “i” varies between 1 and 10. The code that prints 20 asterisks in a line is inside the outer for loop that iterates 10 times.

Running the program

Now save the java file, compile it, and run the generated class file.

Notice that all the 10 lines are printed. Each line contains 20 asterisks. Therefore, we have solved the problem. [Show the original problem]

Today, we have discussed the nested loops – one loop inside another one.

Nested looping can be more complex than what we have explained so far.

Exercise

We are providing an exercise now.

Print 10 lines, where the first line, contains 10 asterisks, the 2nd line contains 9 asterisks, the 3rd line contains 8 asterisks, the 4th line contains 7 asterisks, so and so forth. The sample output is provided below.

**********
*********
********
*******
******
*****
****
***
**
*

We are giving this problem as an exercise. Please try to solve it before watching the next video.

Concluding remarks

It is fine if you cannot solve it at this point. We generally give exercises that are harder than what we have covered so far. That is what makes learners skilled. We will definitely provide the solution of the exercise and explain some relevant items in the next video.

If you have not yet subscribed to our website Computing4All.com and to this YouTube channel, please do so to confirm that you receive notifications on our new articles and videos. Wish you a wonderful day, evening, or night, whatever is upcoming. Thank you!

An exercise on for-loops and if-else: Video Lecture 10

In the previous video lecture, we learned how to repeat a segment of code using a for-loop. The segment we used for repetition was small. In the following video lecture, we incorporate an if-else structure inside the scope of a for-loop. We use a simple problem to develop this practice scenario.

The Problem used in the Video Lecture

Print all the integer numbers starting between 1 and 20 (including 1 and 20.) Mark each of them by “odd” or “even” based on whether the number is odd, or even. You must use a for-loop in your code to iterate over all the integers in the range.

Sample output is as follows.

1 odd
2 even
3 odd
4 even
5 odd
6 even
7 odd
8 even
9 odd
10 even
11 odd
12 even
13 odd
14 even
15 odd
16 even
17 odd
18 even
19 odd
20 even

The Code used in the Video Lecture

We used the following code in the video lecture. If you decide to use it, please save the code in a file named OddEven.java.

class OddEven{
  public static void main(String[] args){
    int i;
    for (i=1; i<=20; i=i+1){
      if (i%2==0){
        System.out.println(i+" even");
      }else{
        System.out.println(i+" odd");
      }
    }
  }
}

The Video Lecture

The YouTube video lecture is provided below.

Iterating over if-else using a for loop.

Exercise

Print all the numbers between 1 and 25 (including 1 and 25.) Mark the numbers that are divisible by 5 with text “Penta”. A sample output is provided below.

1
2
3
4
5 Penta
6
7
8
9
10 Penta
11
12
13
14
15 Penta
16
17
18
19
20 Penta
21
22
23
24
25 Penta

Transcription of the Audio of the Video

Hi, this is Dr. Shahriar Hossain. I hope that you are enjoying the practice of programming using Java. In the previous video lecture, we learned looping. We now know how to use Java for-loops. Today, we will see how we can put if-else statements within a for-loop.

Let us start with a problem.

The problem

Print all the integer numbers from 1 to 20, and mark each of them by “odd” or “even” based on whether the number is odd, or even.

That is, we need an output like this one, where we have an integer and against every integer we have the information whether the integer is odd of even. We have twenty lines for twenty integers between 1 and 20.

[Show the output]

1          odd
2          even
……
20        even

[End of Show the output]

Components of the program

The program has a few components.

  1. We need to go over every integer number between 1 and 20.
  2. For each of the numbers, we have to check whether the number is odd or even.
  3. Based on whether the number is odd or even, print the number and print the text “odd” or “even”.

Let us write the main method in a class named OddEven. The file name is obviously OddEven.java.

The for-loop

Let us create an integer variable named “i”. This variable “i” will be used to hold all the integer values between 1 and 20. From the previous video lecture, we know how to write a for loop and change the value of a variable. Inside the parentheses of the for loop, we do an initialization. In this case, we want the variable “i” to vary between 1 to 20. Therefore, the initialization for “i” should be 1. We want the value of “i” to become each of the numbers between 1 to 20. Therefore, the condition is that the variable “i” should never be greater than 20. Hence, we write i<=20. As said, the value of the variable “i” should be each number. That is, the value of “i” should  be incremented by 1 after each iteration of the for-loop.

Varying the value of i

Now that we have the structure of the for loop, we can do whatever we want inside the scope of the for loop. This for loop will go inside the scope 20 times. In each of these 20 iterations, the variable “i” will have a value between 1 and 20. Seeing is believing. Let us print the value of “i” inside the scope of the for loop. Let us save the file, compile it, and then run the class file.

Notice that the values of “i” are printed on the terminal. The values are 1, 2, 3, so and so forth, up to 20. Let us get back to the code.

How to find if a number is odd or even

Now, for a value of the variable i, we need to check whether the value is “odd” or “even”. How do we know if a number is odd or even? If you divide a number by 2, if there is a zero remainder, then the number is even. If the remainder is 1, then the number is odd.

For example, if you divide 5 by 2, the remainder is 1. Therefore, 5 is an odd number.

As another example, if you divide 8 by 2, the remainder is 0. Therefore, 8 is an even number.

That is, when you divide an odd number by 2, the remainder is 1. When you divide an even number by 2, the remainder is 0.

When you divide a number by 2, the remainder can be either 0 or 1, nothing else. Therefore, if you divide the value of the variable “i” by 2, and receive a remainder of 0, you can mark the value of “i” as “even”. Otherwise, the value is “odd”.

The remainder operation

In Java, the remainder operation is denoted by the percentage symbol (%). It is commonly called “mod”, which stands for modulus or remainder.

If-else

What we want to say here is the following, if (i%2 ==0) then we want to print the number and print the word “even”.

Otherwise, which is the else part, we want to print the number and the word “odd”.

Equality comparison

Notice that this double equals (“==”)  symbol refers to equality comparison, as explained in one of the earlier videos. We are comparing if the left side and the right side of the “double equals” symbol have the same values. If yes, we execute the scope, otherwise we execute the scope of the else part.

Let us save the file. Compile it and run the class file. Notice that we have printed the numbers and side by the numbers, we have reported whether the number is odd or even.

Concluding remarks

One specialty of this program is that we have incorporated if-else statements inside the for-loop. In the upcoming videos, we will write more complex codes involving looping. In the previous video, I mentioned that there are three types of looping (1) For loops, (2) Wile loops, and (3) Do-while loops. I should mention that the use of “for loop” is sufficient. Still, we will go over while and do-while loops later. For now, I want to let you know that if you know “for loops”, you can practically do whatever things are done with while and do-while loops.

I hope that the videos we are making help you in your quest to learn Java programming. Please write comments below if you have any question. Please subscribe to Computing4All.com and to this YouTube channel if you have not already done so. You will receive notifications on our new posts when you subscribe. Have a  wonderful experience in learning to program. See you soon in the next video.

An introduction to Java for loop: Video Lecture 9

Repetition of segments of codes is an essential part of programming. Repeating the execution of a code segment, a programmer can reduce the size of the code as well as solve problems that require iterations of similar computations for an arbitrary number of times. Java provides three syntaxes for repetition: for loop, while loop, and do-while loop. This article covers Java for loop.

Java for loop

Java for loop is is a powerful syntax to repeat segments of code. It provides integral mechanisms to use variables to control a looping. The “for” syntax itself has three parts: initialization, condition, and change (modification of variables.) These parts are seperated by two semicolons. The basic for-structure is provided below.

for (initialization; condition; change){
// Write the code you need to repeat.
// This is the scope of the for loop.
}

The first part, initialization, is executed only once. It executes before anything else regarding the for-loop has been executed.

The second part, condition, executes each time the execution attempts to go insde the scope of a for-loop. The execution goes inside the loop if the condition results in true, otherwise it terminates the loop.

The third part, change, executes at the end of each iteration. Generally, increment or decrement operations on variables are applied in this part.

All the three parts are optional. Java for loop is a powerful syntax because a programmer can use it quite flexibly and creatively. In fact, knowing just “for loop” from the looping control statments is good enough. A programmer can skip while loop and do-while loop pretty easily, if she/he learns the for-loop well. (If you are reading this page for a coursework, I must tell you NOT TO SKIP while loop and do-while loop.)

The video lecture on Java for loop

The following video provides great details on how to use Java for loops. It is a great introductory material. The last part of the video contains a tracing of the program to visually explain how a Java for loop works.

Java for loop: Problem, solution, and tracing

The code used in the video lecture

Here is the code we used in the video lecture. Save the code in a file named MyCode.java.

class MyCode{
   public static void main(String[] args){
     int i;
     for (i=0; i<5; i=i+1){
       System.out.println("Hello Java!!!");
       System.out.println(i);      
     }
   }
 }

Exercise on Java for loop

Use Java for loop in solving all the problems below.

  1. Write a program to print your name twenty times.
  2. Write a program that sums up all the integers between 1 and 100 (including 1 and 100.) Report the final summation on the terminal.
  3. Write a program that prints all the odd numbers between 0 and 50 on the terminal.

Comment

Please feel free to send us your code in solving the exercises above. Write your questions in the “Comments” section below. We will be happy to help you in problem-solving.

Transcription of the Audio of the Video

Hi, this is Dr. Shahriar Hossain. Have you ever thought about how can we repeat segments of our code for a certain number of times? Like most standard programming languages, Java has three different syntaxes  for repeating a segment of code. These syntaxes are called the “for loop”, the “while loop”, and the “do-while loop.”

Today, we are going to learn the “for loop.”

Sample problem

To explain a sample problem, let us write a program. The problem is to print “Hello Java!!!” five times. Based on topics we have discussed so far in this lecture series, we would write five System.out.println statements to print “Hello Java!!!” five times. If we have to write “Hello Java!!!” one hundred times, we have to write one hundred System.out.println statements. We might even have situations, where we have to repeat the same statement a thousand times. It is not quite practical to repeat statements so many times in the same program. To solve this issue, all languages provide looping.

Java for loop

Java’s “for” control statement has three parts. The first part is initialization. This part is executed once before entering the scope of the for loop. The second part is condition check. As long as this condition check is true, the execution will go inside the scope of the for loop. The third part is something that is automatically executed after each iteration of the scope.

All these three parts are separated by two semicolons, within the parentheses. Now notice that if you initialize a variable in the first part, and increase the variable in the last part, then you can put a condition in the second part to allow the execution to go inside certain number of times. For example, consider that you have a variable named “i”. You initialize the variable “i” to 0. Then you, say in the third part, i=i+1. The third part executes automatically after the execution of the segment scoped by the for loop. Therefore, at the end of each iteration i will automatically be incremented by 1.

You are starting the loop with i=0. After executing the code inside the scope of the for loop, the value of i will become 1 because i=i+1 will execute. In the next iteration, I will remain 1; then at the end of the iteration, i will become 2. This will continue for ever, unless you put a condition in the second part of the three parts of the for loop.

Terminating the loop

You can tell when to terminate the loop. In this example, you can tell “when to stop” based on the value of the variable i. Again, the second part should hold a condition; that is, it should result in a Boolean value. Before executing the scope, the program will check the second part if it is true. If it is not true, then the program will not go inside the loop.

If you type i<5, then it means as long as the value of “i” remains smaller than 5, the execution should go inside the scope of the for loop.

Summary of the three parts

Again, the first part is the initialization and executed only once. The third part is executed after every iteration. The second part is checked for “true” every time the execution attempts to go inside the scope of the for loop.

Since, we have i=0 in the first part, i<5 in the second part, and i=i+1 in the third part, this particular for loop will go inside the scope five times. We will discuss more on this soon in this video.

Let us use a Java for loop in our code

For now, let us change our code with five System.out.println statements so that our code contains only one System.out.println statement, but we repeat that statement five times using a for loop.

I am declaring an integer variable named “i”. I will use this integer variable to control the for loop.

Based on the discussion so far, all we have to do is, write a for loop, in which the first part will contain the initialization. I am putting i=0. In the second part I am putting i<5. In the third part I am writing i=i+1; Notice that, starting from 0, there are five integer numbers that are smaller than 5. Therefore, the loop will execute five times.

Let us save the file, compile, and run it. The program prints “Hello Java!!!” five times.

Values of “i” in each iteration

To check the value of the variable “i” during each of the five iterations, we can write another System.out.println statement, just to print the value of “i”. Save the file, compile, and run it.

Notice that after printing each of the “Hello Java!!!” phrases, we have a number printed in the next line which corresponds to the value of “i” in that particular iteration.

Let us trace the execution of the program.

Tracing the program

I am using a software to trace the program. You are already familiar with manual tracing from the previous video. In this video, I am doing tracing using a software named Netbeans to trace the execution of the code I have written. You do not have to use Netbeans at this point; I am using Netbeans because it gives a good visual illustration of what I am teaching today.

The light green highlight shows where the execution is right now.

I am going to track two items during this tracing. One is the value of the variable “i”  and the other is the Boolean value of “i<5”. I have the output-terminal too.

i=0

Now, the program is in a state where it has created memory space for the variable “i”. The execution is currently in the line where we have the syntax “for”. It has not yet executed the initialization i=0. The first thing the computer will do is execute, the initialization i=0. Then it will check if i<5. Because the variable “i” is zero after the initialization, 0<5 will be true. The execution will go inside the scope of the for loop. Notice that we have two System.out.println statements inside the scope of the for loop. The execution point is now on the first System.out.prinln statement.

At this point, the variable “i” is zero, as you can see here. Also notice that i<5 is true. This is the reason the “for” control statement has allowed the execution to go inside the scope of the for loop. If we execute the current line, which is System.out.println (“Hello Java !!!”), then “Hello Java !!!”  will be printed on the terminal. Our execution point has moved to the next line. Notice that “Hello Java !!!” has been printed on the terminal.

Again, the current value of the variable “i” is 0. Therefore, if we execute the current highlighted line, 0 will be printed on the terminal and here it is. 0 is printed on the terminal.

i=1

After 0 is printed on the terminal, the “for” control statement has executed the scope for the current iteration just once. Now, the third part of the for statement will execute. The third part is i=i+1. Again, the third part is executed at the end of each iteration. Once the variable “i” is incremented by 1, “i” becomes 1 because 0+1 is 1. At this point we are in the second iteration of the scope of the for loop. Notice that i<5 is a true statement because the variable “I” is 1, and 1 is smaller than 5 is a true statement. This is the reason why the execution was able to enter the scope with 1 as the value of i. We print “Hello Java!!!” for the second time on the terminal. Then we print the value of the variable “i”, which is 1 at this point.

i=2

Once the content of the variable “i” is printed on the terminal, i=i+1 will be executed and I will become 2. Since 2<5 is a true statement, the execution will go inside the scope. The first System.out.println will be executed. The execution will now go to the second System.out.println statement. Since the value of “i” is 2, the program will print 2. After printing 2, the third part of the for loop will be executed.

i=3

Therefore, the value of the variable “i” will become 3. Since 3<5 is a true statement, the execution will go inside the scope of the for loop. “Hello Java!!!” will be printed for the fourth time. The value of the variable “i”, which is 3 will be printed.

i=4

The value of the variable “i” will now become 4. Now, 4<5. Therefore, the execution will go inside the scope of the for loop. “Hello Java !!!” will be printed for the fifth time. In the next System.out.println statement 4 will be printed because the variable “i” now contains 4.

Our example loop terminates when i==5

At this point, the third part of the for syntax, which is i=i+1, will be executed. The variable “i” will become 5. Now 5<5 is a false statement. Therefore, the execution will not go inside the for loop anymore. Once the second part of the for loop becomes false, looping is terminated. The execution will jump what we have after the for loop. In our case, it is the closing curly bracket of the main method. Notice that, at this point the variable “i” is 5, and therefore the condition i<5 is false. This is the reason the for loop terminated.

By this time, we have printed “Hello Java!!!” five times on the terminal.

Now, won’t you be able to print “Hello Java!!!” ten times, on the terminal. Or say, print your name on the terminal fifty times, using a for loop? I’m sure you will.

Concluding remarks regarding Java for loops

Now that we can repeat code segments, we can write complicated codes. We can sum up all integers between 0 to 100. Or, we can find if a number is a prime number or not. Note that, you can write arbitrary number of lines inside the scope of the for loop. Those lines may contain anything including if-else if statements, or oven other for loops. More on this in the upcoming videos. If you have not already subscribed to our website Computing4All.com or to this YouTube channel, please do so to receive notifications on our new posts.

Thank you for watching the video. Hope to see you soon in in our video lecture series.

An exercise, its solution, and tracing: if-else if-else in Java: Video Lecture 8

In the previous video-lecture, we described how if-else if-else statements work. We provided an exercise with the video-lecture. In the video with this article, we provide a solution to the exercise.

Tracing a program with if-else if-else statements

In the following video, we introduce a technique called tracing that we did not cover before. Tracing is way to analyze a program. Sometimes, the variable space is so large that correctness of the code needs to be checked conceptually. Tracing by hand is a great way to analyze code for correctness.

The video: An exercise and the solution

The video does not only show how I wrote the code to solve a programming problem, but it also shows how I analyzed the problem before starting to code, and how I analyzed the code after writing the code.

Solution using if-else if-else statements in Java.

The if-else if-else exercise (from the previous video post)

Write a program that asks the user for a GPA on a scale of 0.0 to 4.0. If the user enters a number larger than 4.0 or less than 0.0, the program must output “Invalid GPA.” If the user enters a valid number, the program should display the corresponding letter grade based on the table below.

GPA rangeLetter Grade
4.0A+
3.75 to less than 4.0A
3.5 to less than 3.75A-
3.25 to less than 3.5B+
3.0 to less than 3.25B
2.75 to less than 3.0B-
2.0 to less than 2.75C
0 to less than 2.0F

The solution program using if-else if-else statements

We always say that it is better to type your own code because the practice of writing the code connects you with the solution. We are still providing the code below as a reference. If you decide to use the code, please save the code in a file named Exercise.java because the class name is Exercise.

import java.util.Scanner;
class Exercise{
    public static void main(String[] args){
      double gpa;
      Scanner scan = new Scanner (System.in);
      System.out.println("Enter the GPA, please: ");
      gpa= scan.nextDouble();
      
      if (gpa>4.0){
        System.out.println("Invalid GPA.");
      }else if (gpa==4.0){
        System.out.println("A+");
      }else if (gpa>=3.75){
        System.out.println("A");
      }else if (gpa>=3.5){
        System.out.println("A-");
      }else if (gpa>=3.25){
        System.out.println("B+");
      }else if (gpa>=3.0){
        System.out.println("B");
      }else if (gpa>=2.75){
        System.out.println("B-");
      }else if (gpa>=2.0){
        System.out.println("C");
      }else if (gpa>=0.0){
        System.out.println("F");
      }else{
        System.out.println("Invalid GPA.");
      }      
    }
}

Transcription of the Audio of the Video

Hi,

This is Dr. Shahriar Hossain. In the last video lecture, we discussed “if-else if-else” statements. On our website, we provided an exercise. Today, we are going to solve that exercise. If you have already solved the exercise that we provided with the last video lecture, I suggest, please still watch this video till end because it contains some analysis using tracing. Tracing is a technique that helps us analyze our code without running it enormous amount of time with different inputs.

Oh, one thing before we start working on the exercise, please subscribe to our website Computing4All.com and to this YouTube channel to receive notifications about our articles and video lectures.

I will not keep you waiting anymore. Let us work on the exercise.

Problem description

You can see the description of the exercise on the screen now. The exercise states the following: Write a program that asks the user for a GPA on a scale of 0.0 to 4.0. If the user enters a number larger than 4.0 or less than 0.0, the program must output “Invalid GPA.” If the user enters a valid number, the program should display the corresponding letter grade based on the table below.

Then the table provides bunch of ranges for different grades.

We will analyze the problem a bit now.

Problem analysis for if-else if-else statements

At first, I am outlining the range of GPA. Valid GPA may vary between 0 to 4.0. I am drawing the ranges that are mentioned in the description of the exercise. As described in the problem, any GPA greater than 4.0 should be “Invalid.” Also, any GPA smaller than 0 is “Invalid.”

Variable space analysis for if-else if-else statements in a Java program

Now recall, from the table that the letter grade A+ is assigned to GPA 4.0 only.

A GPA in the range from 3.75 to anything less than 4.0 should have a letter grade “A”.

From 3.5 to anything less that 3.75 should be designated as A- (minus).

GPA B+ is in the range starting from 3.25 and should be less than 3.5.

B starts from 3.0. It is less than 3.25.

The range of B- starts from 2.75. B- is less than 3.0.

The next letter grade is C. It starts from 2.0 and is less than 2.75.

Valid grades less than 2.0 result in an F.  

The idea of the solution

The idea of the solution is that we will use if-else if-else statements to display the letter grade corresponding to a given gpa.

Starting of the code

Let us write the code. I have already written the class name and the header for the main method. The file name is Exercise.java.

I will write the code to collect the GPA from the user. I will keep the GPA in a variable named gpa, which is of “double” data type.

Based on what is inside the variable, gpa, I want to display the corresponding letter grade. In our figure, we started to draw the ranges from right side. That is, from larger gpa to smaller gpa. I will write the code in the same order. That is, I will first write an “if” statement to cover the gpa greater than 4.0. Notice that all gpa’s greater than 4.0 should be marked as “Invalid GPA” because the valid gpa range starts at 0.0 and ends at 4.0.

gpa>=4.0

All I have to write is, if gpa is greater than 4.0, then print “Invalid GPA.”

GPA: A+

Now, the next item in the right side of the figure is, 4.0. At 4.0, the letter grade A+ should be printed. The idea is, I will use an “else if” statement to cover 4.0. I am writing else if, gpa is equal to 4.0, then print “A+”. Notice that the equality comparison has to be with two “equals” symbols. We discussed in an earlier video that the equality comparison is always with two equals symbol, not one. A single equals symbol is used for the assignment operations.

Anyway, if we run the program right now, then for any gpa greater than 4.0, the program will print “Invalid GPA”. For gpa equal to 4.0, the program will print “A+”. For any other gpa, the program will print nothing.

We are not going to run the program now. Rather, we will compete the code and then run the program.

GPA: A

The next grade letter is A. GPA A may start at 3.75 and must be less than 4.0. Therefore, I add another else if statement, in which I write the condition gpa>=3.75. When the condition is satisfied, we print the letter grade “A”.

At this point, if we run the program with a gpa, say 3.8, the first condition is not satisfied; the second condition gpa==4.0 is not satisfied either. The third condition gpa is greater than 3.75 is satisfied. Therefore, the program will print the letter grade “A”.

If the first condition is satisfied, which is an invalid situation in this program, the program prints “Invalid GPA” and does not check any other condition in the if-else if sequence. A condition in the if-else if -else sequence is checked only if all the preceding if or else if conditions resulted in “false”. Again, once an “if” or “else if” condition is satisfied, no other condition in the sequence will be checked.

GPA: A-

Let us get back to the code. The next letter grade is A-, which starts from gpa 3.5 and is less than 3.75. Therefore, the condition in the “else if” statement for A- is “gpa>=3.5.”

GPA: B+, B, B-

Let me quickly write the code up to B-, using concepts similar to what we have discussed so far.

GPA: C

Now, notice that the range for C is a bit large. It starts from 2.0 and is less than 2.75. In our code, we provide that condition in the “else if” statement for the letter grade C.

GPA: F

The next letter grade is “F”, which starts at gpa 0.0 and is less than 2.0.

gpa<=0.0

So far, we have all the letter grades in the code. We also have the invalid grade that is greater than 4.0. The only item that is left out is any invalid gpa that is smaller than 0.0. Notice that we do not need another “else if” for that because it is the only situation that is left out. Therefore, we can use “else” without any condition for any gpa lesser than 0.0. We write “Invalid GPA” on the terminal if the user enters any gpa that is negative.

Running the program

The code is complete. Let us save the file and compile it. I will run the program several times with different gpa values. Notice that all the grade letters are correctly printed.

Tracing

Let us manually trace the code a bit for clarity. When you run the program, the Java virtual machine will attempt to execute each line in the main method in a sequence as they appear.

A variable named GPA is created. The Scanner object named “scan” is created. Then, on the terminal “Enter the GPA, please” — this sentence is printed. Then the user enters a GPA and hits the enter button on the keyboard. The computer receives the value of the GPA in the variable named “gpa”. Now the “if-else if” statements of the code will execute, as required. Consider that the user entered a GPA of 3.3.

Tracing with GPA 3.3

Now the computer will check if the variable “gpa” is holding anything greater than 4.0. Since 3.3 is not greater than 4.0, the statement “if gpa>4.0” results in false. Therefore, the corresponding System.out.println “Invalid GPA” will not be executed. Since, “if gpa>4.0” is false, the computer now will check the next “else if” statement, which is gpa==4.0. GPA 3.3 is not equal to 4.0, therefore, the statement “else if (gpa==4.0)” is false. Since, it is false the execution will not go inside its scope. Therefore, “A+” will NOT be printed.

The next item the computer will check if gpa>=3.75. GPA 3.3 is not greater than or equal t 3.75. Therefore, this condition results in false.

The next check is if gpa is greater than or equal to 3.5, which also results in false. Therefore, the computer will check the next “else if” condition, which is if gpa is greater than or equal to 3.25. Now, GPA 3.3 is greater than 3.25. Hence, the condition “gpa>=3.25” results in true. Since it results in true, the execution will go inside the curly brackets, where it is written System.out.println “B+”. Therefore, B+ will be printed. Once one condition is satisfied, that is, once a condition results in true, after executing the corresponding scope, the computer does not check for any other condition.

The execution will jump to the end of this entire “if-else if-else” sequence. That would be the end of the program. That is, for gpa 3.3, the program has printed “B+”.

Tracing with GPA -5.0

Let us quickly trace, another execution of the program, where the user enters -5.0 (negative 5 point 0) as the gpa. Notice that negative 5 point 0 is an invalid GPA because it is less than zero. Let us check how the execution of the program will work now.

We are tracing for the variable gpa, when it is negative 5 point 0. In the first “if” statement, gpa>4.0, the condition is false because -5.0 is not greater than 4.0. Therefore, the corresponding System.out.println is not executed.

For the next “else if” condition, gpa==4.0, the resultant Boolean value is “false” too.

Notice that, for gpa negative 5 point zero, none of these conditions will result in “true”. Therefore, the execution will end up going to the “else” statement. Once, the execution goes to the “else” statement, the computer executes every instruction under the “else” scope. In our code, the only statement written here is System.out.println “Invalid GPA”. Therefore, the computer will execute it and “Invalid GPA” will be printed on the terminal.

Notice again that when, all the “if” and “else if” conditions result in false, only then the last “else” is executed.

Tracing with GPA 3.6

Let us quickly do another tracing for GPA 3.6. gpa>4.0 is false because 3.6>4.0 is false. The next, condition gpa==4.0 is false too. Even the next one, gpa>=3.75 is false. The next “else if” condition gpa>=3.5 is true because 3.6 is greater than 3.5. Therefore, the execution will go inside the scope of “gpa>=3.5”. The computer will execute System.out.println “A-”. No other condition will be checked because already a condition in this sequence of “if – else if” statements is true. The execution will jump to the end of this “if-else if-else” sequence.

Conclusion

I hope the “if-else if- else” statements are clearer with the video lecture today. Please do not hesitate to ask any question you may have via the comments section below. We will be happy to be with you in your journey to learn programming. If you haven’t already done so, please subscribe to our website Computing4All.com and our YouTube channel where you are watching this video.

if-else if-else statements in Java: Video Lecture 7

There are several control statements in Java, among which if-else if-else and switch statements are used for selection operations. The video lecture below explains if-else if-else statements. Programmers use if-else if-else statements for decision making in the code. That is, if-else if-else statements help in executing a part of the code based on certain conditions.

Prerequisites

Please make sure to go over the previous lecture on Boolean Variables and Relational Operators, if you haven’t already done so. The last lecture will give a good idea on Conditions, which is the basis for the current video.

The Video: if-else if-else statements in Java

The video explains if-else if-else statements in Java. It uses a simple example to explain the concept. Overall, the video will help beginners to start practicing if-else if-else statements.

if/else if/else statements in Java

The Program Used in the Video

The program demonstrated in the video is provided below. Please save the code in a file named ConditionTest.java if you want to use the code directly. We suggest that you type the code while you watch the video. When you type the code, you practically develope an understanding regarding the syntax you type.

import java.util.Scanner;
class ConditionTest{
    public static void main(String[] args){
        int x;
        int y;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the 1st number");
        x=scan.nextInt();
        System.out.println("Enter the 2nd number");
        y=scan.nextInt();        
        if (x>y){
            System.out.println("x is greater");
        }else if (x<y){
            System.out.println("x is smaller");
        }else{
            System.out.println("Equal numbers");
        }
    }
}

Exercise to practice if-else if-else statements

Write a program that asks the user for a GPA on a scale of 0.0 to 4.0. If the user enters a number larger than 4.0 or less than 0.0, the program must output “Invalid GPA.” If the user enters a valid number, the program should display the corresponding letter grade based on the table below.

GPA rangeLetter Grade
4.0A+
3.75 to less than 4.0A
3.5 to less than 3.75A-
3.25 to less than 3.5B+
3.0 to less than 3.25B
2.75 to less than 3.0B-
2.0 to less than 2.75C
0 to less than 2.0F

Please do not hesitate to send us your code via the comments section below. We will be happy to provide you feedback.

Comment

Please subscribe to Computing4All.com and to our YouTube channel to stay in touch.

Transcription of the Audio of the Video

From the previous video, you are familiar with comparisons and Boolean variables, we are now moving to what we can do with the comparisons. Practically, we can use comparisons for decision making in the program. That is, a part of our code will be executed if certain conditions are met; otherwise, another part of the code will be executed.

Starting of the code

I am starting my code where I will show how we can use if-else statements. The name of the class is ConditionTest; Of course the file name is ConditionTest.java. I have already written the main method, inside which I will write my code.

I am declaring two integer variables, x and y.

the variable scan is my Scanner object, using which I will get input from the user. I have written my code to get input for the first number x, and the second number y.

The first if statement

At this point, what I will do is, I will print a message if x and y have a certain relationship. The statement is written using “if” then in parentheses state the comparison. Within the parentheses, you must have a Boolean value. Notice that the comparison x>y results in a boolean value, either true or false.

Again, at first write if, then within parentheses provide the condition or comparison that results in a Boolean value. After the parentheses provide the scope of the code that should be executed if the condition in the parentheses results in “true”. You define the scope using a left curly bracket and a right curly bracket.

Anything you write inside the curly brackets will be executed, only if the condition you have provided within the “if” statement results in true. Inside the scope of the if statement I have written, I am writing a System.out.println statement. If x is greater than y, then the System.out.println will print “x is greater than y.”

Save, compile, and run

Let us save the file, compile it and run it. If the user enters a larger number for x than y, then the program should print “x is greater than y”, otherwise the program will print nothing after the user enters the numbers.

The user enters 10 for x and 5 for y. The program immediately prints “x is greater” because the first number the user provided is greater than the second number.

Let us run the code again. The user now provides 10 as the first number and 20 as the second number. Now, the program compares x>y, which results in the comparison 10>20, which in turn results in false. Since the if statement results in false, the System.out.println is not executed. The program just ends without printing anything.

Change the code to include another scope

Now, if we want the program to print something when x is not greater than y, then we can create another scope, which will be executed if the if statement results in false. What we write is, “else” and then we create another scope using left and right curly brackets.  You can print anything inside these curly brackets. Anything you print via a System.out.println statement will be printed on the terminal when x is NOT greater than y. Let us just print “x is not greater.”

Save, compile, and run the code

Let us save the file, compile it, and then run it.

Now, notice that for the first number 10, and the second number 20, the program outputs ” x is not greater.”

Earlier, the program was not printing anything for 10 and 20.

Running the program again with 20 and 10. Now the program is saying “x is greater.” That is if the first number if greater than the second number, the program says “x is greater”, otherwise the program says “x is not greater.”

What happens if you have two equal numbers

Now, what will happen if the user provides two equal numbers, say 10 and 10? Based on the code we have, the program will say that x is not greater. Notice that in the code, the if statement will result in false because x is not greater than y. Therefore, the first System.out.println will not be executed. The execution will go to the else part and execute the System.out.println of the scope of the else, which is “x is not greater.”

What if we want to say something different when x and y have the same value? Practically, we have to include a scope which will be executed when x is equal to y.

In the code, currently, we have if x is greater than y, then do something, otherwise, do another thing. The otherwise part executes only when x is smaller than or equal to y.

We will separate the smaller than part and the equal part. In the else part, we will include another if statement, with a condition x is smaller than y. When x is smaller than y, we want the program to print “x is smaller”.

Save this code, compile, and run the program. When the user puts 10 as the first number and 20 as the second number, the program outputs, “x is smaller.” It is the correct outcome.

When the user enters 20 as the first number and 10 is the second number, the program prints “x is greater.” This is a correct outcome too.

Now notice that when the user enters 10 as the first number and 10 as the second number, the program does not print anything. That is, when the user provides two equal numbers, the program does not go to any of the if scopes.

“The equal to” situation

We would like to see output for “the equal” situation too.

Notice that the first if statement handles the situation with x is greater than y. The second if statement, that is with else,handles the “x is smaller than y” situation. The only situation left is the “x is equal to y” situation. Therefore, we can simply add an “else” to handle the scope of “x is equal to y.” Inside the scope of “else”, we write “equal numbers,” within System.out.println.

We have now written a program that takes two numbers, x and y, from the user and gives an idea of which number is larger, or smaller, or if they are equal.

Let us save the file, compile the code, and run the program. Notice that for equal numbers, the program now outputs “Equal numbers.”

The general structure of if-else if-else statements

[Show the following on screen]

        if (condition 1) {
            ------------
        } else if (condition 2) {
            ------------
        } else if (condition 3) {
            ------------
        } 
            ------------
            ------------
        } else if (condition n) {
            ------------
        } else {
            ------------
        }

[End of — Show the following on screen]

Here is the general structure of “if then else” statements. The first “if” statement is straightforward. If more “if” statements are required in a sequence, they must be preceded by an “else”. You can write as many else if conditions as you need. You may end the if-then-else sequence with just an “else”. The last “else” will cover all situations that are not covered by all the if and else if statements you have in the sequence.

This overall sequence is called if-then-else statements. One thing I should mention is that, each scope under an “if” statement or an “else if” statement or an “else” statement may have many lines of code depending the problem the programmer is trying to solve. In our example, we just had a System.out.println statement within each scope.

Once a condition of the sequence is satisfied, the corresponding scope is executed. Nothing else will execute. The purpose of if-then-else sequence is to execute only one scope.

Conclusion

Please practice what we have discussed today. For exercises, please visit the link provided in the description. Subscribe to this YouTube channel and to our website Computing4All.com. We do not assume that you know anything about programming. Our video lectures, so far, are prepared for beginners regardless of background. Please start from the beginning of this lecture series if you are entirely a new learner.

Thank you very much for watching the video.

Boolean Variables and Relational Operators in Java: Video Lecture 6

A boolean variable is capable of holding either “true” or “false.” A computer program may use one bit only to store the status “true” or “false.” You might already know that the smallest memory unit of the computer is a “bit.” Therefore, a boolean variable uses as little memory as possible to store the information “true” or “false.” Generally, “true” is stored as “1.” “False” is stored as zero (“0”). Anyway, in programming, there are situations when you will want your program to remember some binary decisions (yes/no decisions.) At that time, binary variables become handy. The conclusion whether a number is greater than another number, or smaller than another number, so and so forth can be stored in a boolean variable.

Comparisons between numbers or variables are frequent in programming. That is, you will face situations where you will need to check if one number is smaller than another number, or if a number is equal to or not equal to another number, so and so forth. In mathematics, such comparisons are called logical conditions. In Java, there are six logical operators to work with logical conditions or to compare variables. The video lecture below provides further details with easy-to-follow programming examples.

The Video: Boolean Variables and Relational Operators in Java

The video explains boolean variables and logical conditions (relational operators). The examples we used in the video are suitable for beginners. Overall, the video will help a beginner to study boolean variables as well as relations operators.

Boolean variables and relational operators in Java.

The Program Used in the Video

We wrote the following program in the video. Please save the content in a file named BoolTest.java before compiling and running it. Although we are providing the code here as a reference, we suggest that you type the program yourself while watching the video. The process of programming involves typing and thinking about the problem simultaneously. This is why it is best if you write the code yourself.

import java.util.Scanner;
class BoolTest{
    public static void main(String[] args){
        boolean b;
        int x;
        int y;
        Scanner scan = new Scanner (System.in);
        System.out.println("Enter the 1st number");
        x=scan.nextInt();
        System.out.println("Enter the 2nd number");
        y=scan.nextInt();
        
        b= (x==y);
        System.out.println(b);
        
    }
}

Exercises

Please do not hesitate to send us your code via the comments section below. We will be happy to provide you feedback.

  1. Write a program that can say whether it is a hot day or not. Ask the user for the temperature (in Ferenhite) of the day. Print “true” if the temperature the user provides is higher than or equal to 90-degree Ferenhite. Print “false”, otherwise. Please do not use if-then-else for this program.
  2. Write a program that can say whether a number is odd or even. Ask for an integer from the user. Print “true” if the user enters an even number and “false” if the user enters an odd number. Please do not use if-then-else for this program. Hint: You will need to use the remainder (%) arithmetic operator.

Additional Resource

The following Java documentation covers relational and conditional operators. It uses if-then-else, which we have not covered yet in our videos. As a result, the link below might not make a whole lot of sense at this point. Still, we are providing it here as a standard reference because it is a part of Oracle Java documentation. The content of the following link will make sense after a few more video lectures.

Equality, Relational, and Conditional Operators

Comment

We will come back soon with the next topic. To stay in touch, please subscribe to Computing4All.com and subscribe to our YouTube channel. Enjoy!

Transcription of the Audio of the Video

Hi,
I am Dr. Shahriar Hossain. Today, I am going to explain the concept of Boolean variables. Boolean variables are capable of holding conditions. In a computer, a condition or a status is either “true” or false.

Logical conditions (to be used with relational operators)

A “condition” in Java refers to logical conditions of mathematics. For example, 10>5, or 6<10. Other than the “greater than” or the “smaller than” symbol, there are several other logical conditions. For example, equal to (==), not equal to (!=) greater than or equal to (>=), smaller than or equal to (<=) .

Relational operators

Here is a complete list of logical conditions
[Show on screen]
• a < b (a is Less than b)
• a <= b (a is Less than or equal to b)
• a > b (a is greater than b)
• a >= b (a is greater than or equal to b)
• a == b (a is equal to b)
• a != b (a is not equal to b)
[End of- Show on screen]

Equality comparison

Java recognizes equality comparison of two variables with two equals symbol (==). If you provide one equal symbol, it is considered as an assignment. Again, one equal symbol means assignment, that is, the right side of the assignment will be copied to the variable in the left side. Two consecutive equal symbols refer to “equality comparison” between two variables or numbers.

Each of these logical conditions results in either “true” or “false”. As a result, a Boolean variable is capable of remembering or holding the result of each of these logical conditions.

Boolean variables to store the results of relational operations

As I said earlier, a Boolean variable is a variable that can hold either true or false. In a computer, “true” refers to 1, and “false” refers to zero. In an earlier video, we explained data types and mentioned the ranges of number variables like integer, double, byte, so and so forth. The range of a Boolean variable is just zero and one, nothing else. Boolean is a data type that requires the smallest memory size, just one small bit. As a result, it can only hold either one or zero, in a small bit size.

Today we will see how we can declare a Boolean variable and what we can do with it. In this video, we are learning logical conditions as well. Logical conditions are comparisons. Comparisons will help us when we will learn conditional statements like if-then-else in a later video.

I will share my screen with you in a moment.

Starting of the code

My class name is BoolTest.java. I am writing my main methods, inside which I have declared a boolean variable named b. I also declare two more variables, x, and y, of integer type. I will ask the user to enter two numbers for x, and y. Therefore, I prepare my Scanner object named scan. I write code to get input for x. I also write code to get input for y.

At this point, I want to keep the information if x is greater than y in the boolean variable. Notice that the answer “if x is greater than y” is either yes, or now. Therefore, for the answer, you just need a Boolean variable because the Boolean variable has the capability to hold true or false, which is “yes” or “no” in this case.

If I type x>y the value is either true or false. If the content in x is greater than the content in y, then the value will be true, otherwise, the value will be false. I assign the value in the right side of the assignment operator to the variable I have on the left side. The variable I have on the left side is b, which is a Boolean variable.

Now let us print the status of the Boolean variable b, using a System.out.println statement. Save the file, compile, and run it. The program ask for the first number. The user enters 10. The program asks for the second number, the user enters 20. The program immediately answers false. Notice that the program only answers if the first number if greater than the second number the user has entered. Since 10 is less than 20, the statement “the first number is greater than the second number” is false. The program has printed false.

Running the program

Let us run the program again. The program asks for the first number. The user enters 50. The program asks for the second number. The user enters 10. Notice that the first number is greater than the second number. The program should now say true. This is because the first number is greater than the second number, and the program is checking if the first number, x, is greater than the second number, y.

Let us do another check now. Let us change the greater than symbol to smaller than. That is the program should output true if the first number is smaller than the second number. Save the file, compile it, and run it. The user enters 20 and 25 as the first and the second number. Since the first number, 20 which is x, is smaller than the second number, 25, which is y, the program outputs “true” now. That is, the program now checks if the first number is smaller than the second number.

I am quickly showing another example. Where you can see that the first number is 30 and the second number the user entered is 10. The program outputs false because the first number 30 is not smaller than the second number 10.

Changing the code with equality (==)

Now, we are going to examine another comparison operation, which is whether the content of two variables are equal or not. As I said earlier, the equality comparison between two variables is accomplished by two equal symbols. Therefore, if we write x two equals (==) y, the right side of the assignment operator should be true only when x is equal to y, otherwise, it should be false. That is, b will be true if x and y are equal. b will be false if x and y are unequal.

Sometimes, my students get confused because this particular line looks a bit weird due to three equals symbol. To reduce the confusion you can put parentheses on the right side of the assignment operator. The parentheses will not change anything. You can put them for clarity. I will skip them in my code. Let us save the file, compile it, and run it.

Running the code

10 and 20 are not equal. Therefore, the program outputs false.
20 and 10 are not equal. Thus, the program outputs false.
The user enters 10 and 10 as the first and the second number. The program outputs true now, which you expected because you used equality comparison in your code.

Let me quickly show you that putting those parentheses will not change the correctness of the program.

Notice that my program prints the same output, which is “true”, for equal inputs.

Concluding remarks regarding boolean variables and relational operators

The main idea of the video today is to familiarize you with the concept of Boolean variables and logical conditions. Over time, we will see more complex logical conditions, as well as conditional statements. Please practice what we have discussed today. For exercises, please visit the link provided in the description. Subscribe to this YouTube channel and to our website Computing4All.com. We do not assume that you know anything about programming. Our video lectures, so far, are prepared for beginners regardless of their backgrounds. Please start from the beginning of this lecture series if you are entirely a new learner.

See you in a few days in the next video lecture. Meantime, please do not hesitate to send us any question you may have, through the comments section below, or via the contact us form on our website Computing4All.com. Thank you very much for watching the video.

How to Use Arithmetic Operators in Java: Video Lecture 5

Arithmetic operators play a significant role in mathematical operations when using a programming language to solve a problem. The Java programming language has five basic arithmetic operators — addition (+), subtraction (-), multiplication (*), division, and the remainder (%). Programmers apply each of these operators on two operands (that is, on two numbers).

The Video: Arithmetic Operators in Java

In the following YouTube video, we explain the use of arithmetic operators in Java using three examples. Each of the three examples involves the implementation of a mathematical expression.

How to Use Arithmetic Operators in Java

Programs Used in the Video

In this section, we provide the codes of the three programs we wrote in the video.

Program 1: Implementing a Mathematical Expression

In the first program, we implement an arithmetic expression containing two variables. The arithmetic expression is:

{(a+b)(2a+3b)}+3a

The video explains, how curly braces and square brackets of mathematical expressions should be handled in Java. It also explains how to handle implicit operators (for example, multiplication symbols that are not present in the equation above.)

The following program codes the arithmetic expression above. Save the code in a file named Prog.java.

import java.util.Scanner;

class Prog{
  public static void main(String[] args){
    double a;
    double b;
    double res;
    Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter the 1st number:");
    a=sc.nextDouble();
    System.out.println("Enter the 2nd number:");
    b=sc.nextDouble();
    res = ((a+b)*(2*a+3*b))+3*a;
    System.out.println(res);
    
  }
}

Program 2: Compute the Area of a Circle

In geometry, computing the area of a circle given a radius, r requires evaluating the following expression: πr2.

We wrote the following program in the video to calculate the area of a circle. Please save the code in a file named CircleArea.java.

import java.util.Scanner;

class CircleArea{
  public static void main(String[] args){
    double area;
    double r;
    Scanner scan = new Scanner (System.in);
    System.out.println("What is the radious?");
    r=scan.nextDouble();
    area = 3.14159 * r * r;
    System.out.println("The area is: "+area);    
  }
}

Program 3: Compute an Arithmetic Expression

Just like the first program, we implement a mathematical expression in the third program. The expression in the third program is slightly more complex than the one in the first program.

We implemented the following arithmetic expression in the third program.

We wrote the following program in the video to code the equation above. Save the program in a file named ProgExt.java.

import java.util.Scanner;
class ProgExt{
  public static void main(String[] args){
    double x;
    double y;
    double result;
    
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter value of x: ");
    x=sc.nextDouble();
    System.out.println("Enter value of y: ");
    y=sc.nextDouble();
    result = (5*x)/(4*y)+(3*y-2)/(2*x);
    System.out.println("The result is: "+result);
  }
}

Exercise

Write a program to evaluate each of the following arithmetic expressions.

For each of the arithmetic expressions above, using paper and pencil, come up with results for some given values of x and y. For the same x and y, check if your program gives the same result. If the results are different, then you know that either you did it wrong on paper or something is wrong with your code. Please find the issues and fix them. Such fixing of problems is commonly called debugging in the practice of programming.

Additional Resource

The Arithmetic Operators section of the official Java documentation page is a useful reference for the topic we discussed in the video.

Comment

We will cover conditional statements in a future video. Conditional statements help execute different parts of a program under different conditions. To stay in touch, please subscribe to Computing4All.com. Enjoy!

Transcription of the Audio of the Video

Hi, I am Dr. Shahriar Hossain. Today, I am going to explain some items regarding numeric or arithmetic operators in Java. In the previous videos of this lecture series, that Dr. Monika Akbar and I taught, we discussed numeric data types like integers, double, and byte.

We also discussed simple arithmetic operations like addition, subtraction, multiplication, and division. We will describe more on how to use arithmetic operations using Java in this lecture.

The Arithmetic Operators in Java

Java or most standard programming languages have five numeric or arithmetic operators – addition (+), subtraction (-), multiplication (*), division (/), and the remainder (%).

We already worked on addition, subtraction, multiplication, and division in another video. They are basic arithmetic operations and I am sure everyone who is watching this video is familiar with them.

What is the Remainder Operator

What is not common is the remainder operation, which is represented by the percentage symbol (%). In Java, the percentage symbol does not have anything to do with the percentage. After you divide a number by a divisor, you get a quotient and then you have a remainder. The percent symbol or operator in Java will give you the remainder.

For example, 14 remainder 4 is 2, because 4 times three is 12 and then you will have 2 remainder to reach 14. The remainder is computed by the remainder operator.

Anyway, the remainder operations is not hugely common in day-to-day software development. You might need to use the remainder operation if you are working on projects that require implementation of mathematical equations.  

Let us talk about how to perform numeric or arithmetic operations in Java.

Evaluating an Arithmetic Expression

You may recall from middle school, how we did simplification of mathematical expressions. We used square brackets, curly braces, and parentheses in arithmetic expressions. The use of curly braces and square brackets is restricted in Java. In arithmetic statements (in Java), we can only use parenthesis.

Use Parentheses Instead of Curly or Square Braces in Java Arithmetic Expressions

For example, in an expression like this one, {(a+b)(2a+3b)}+3a, we have to replace the opening and ending curly braces with opening and ending parenthesis. Also, we cannot skip any operator when we write arithmetic statements.

Multiplication Symbol has to be Explicit in Java Arithmetic Expressions

On paper, in this expression, ((a+b)(2a+3b))+3a, we did not provide the multiplication symbols. When using Java, we must explicitly put the multiplication symbols.

Another item, I should mention is that whatever arithmetic statement you write, the result should be kept in a variable, to be able to use it later.  For example, if you have a double variable named res, then you can write:

res=((a+b)*(2*a+3*b))+3*a;

Remember from the previous video lectures that the right side of the equals symbol is executed first. The equals symbol is called the assignment operator.

Variables are Replaced by their Contents when Executed

Of course, in place of variables like “a” and “b” Java will put the values in those variables before computing the arithmetic expression you have written in the right side of the assignment operator. After the right side of the assignment is operated, the computed value goes to the variable you have placed in the left side, which is “res”. In this case.

Coding Program 1

Let me quickly code the program.

[Write the code in fast forward mode using equation res=((a+b)*(2*a+3*b))+3*a. Initialize, a to 1.0, and b to 2.0.]

Notice that, I initialized “a” to 1.0 and “b” to 2.0. For these values, I am doing the calculation on paper first. The simplified value is 27. The same way, I did it on paper, the Java Virtual Machine will do it for me using the computer’s processor.

Running the Program

That is if I run the program I have written, the computer will evaluate the arithmetic expression we have written in the right side of the assignment operator of the “res” variable. If I compile and run the program I will be able to check if the program prints 27, as expected.

After compiling and running the program, we see that 27 is printed on the terminal. This demonstrate that whatever we did on paper is actually replicated here using the program. You have written a program that can compute the expression.

Changing the Code to Get User Input

In an ideal case, we will not hard code the initial values like what we did here in our code. We know how to change the code to ask the user for the values of the variables we have.

I will now change the code. I will use a Scanner object that I will use to get the user input for “a” and “b”. After I do that, my code will ask the user for each of the two numbers. The program will take the first number and put it in a. It will take the second number and put it in b.

Let us, save the file, compile it, and run the program. The program is asking for the first number. The user enters 1. It is asking for the second number. The user enters 2. The computer states that the calculated value is 27.

We can run the program again and find the calculated value for any two numbers.

You can write a program to compute the area of a circle, or a rectangle, or a trapezoid, or practically anything as long as you have the arithmetic expression for the problem you are trying solve.

Coding Program 2: Area of a Circle

Let us go over another program. We are writing a program that is able to compute the area of a circle.

Remember from geometry that the area of a circle is πr2.

Pi (π) is constant. That means the value of pi never changes. The value is quite long, but in this program, we will keep only a few digits after the decimal point. We will use π= 3.14159.

Notice that the only variable you have here for the mathematical expression is “r”, which is the radius of the circle. Therefore, we will ask the user to provide the radius. After the user provides the radius, all we have to do is compute π times radius squared.

The radius is stored in the variable “r”. Therefore, we can write “r times r” for radius square. My arithmetic expression becomes, 3.14159*r*r.

We will put the computed value of this expression in a variable named area. Therefore we will print the area.

Let us save the file, compile it, and run the code. The user enters a radius of 2.0. The program computes the area and then prints the area of the circle on the terminal.

The user can run the program again and again to get the areas of circles of different radii.

The Third Program

I will go over one more program now. Suppose, you have this expression

[show on paper 5x/4y+(3y-2)/2x].

How can we code this.

The expression in Java code will be:

(5*x)/(4*y)+(3*y-2)/(2*x)

Notice that there are two variables x and y. Therefore we will ask the user for two numbers, x and y. These two numbers will be kept in two variables named x and y. We will make x and y double numbers. We will keep another variable named “result”, which will hold the computed result.

Coding Program 3

Let us do the coding in fast forward mode. Please pause the video if you are coding it. I will provide the code in the website Computing4All.com too. However, I recommend that you type it yourself. I feel that when you type it yourself, you build a foundational understanding of the program.

Let us save the file, compile it, and run it.

The program asks for the first number and the second number. The program computes the expression for the two given numbers, and prints the computed value.

Conclusion

We will provide exercises regarding today’s video on our website Computing4All.com. As I said before one cannot learn to ride a bike or to swim by watching videos or by reading books. Similar to that, one cannot become skilled in programming just by watching videos or just by reading books. Please practice, practice, and practice to make sure that you develop a strong programming skill over time.

More on Data Types and User Input in Java: Video Lecture 4

We have been discussing preliminaries of Java Programming language so far. If you have watched all the previous videos we made and completed the associated exercises, it is time to talk more about data types and user input in Java programming language.

The Video: Data types and user input in Java

In the previous video, we introduced how to get a double user input in Java. In the following video, we will see how we can write a code to get “input” for several different types of variables.

Variable Types and User Input in Java

The Final Program Used in the Video

We are providing the final program used in the video below. The program engages in a conversation with the user. Through the code, you will get an idea of user input in Java for several types of variables. Save the file as MyProg.java.

import java.util.Scanner;

class MyProg{
  public static void main(String[] args){
    String name;
    byte age;
    double income;
    
    Scanner sc = new Scanner(System.in);
    System.out.println("What is your name");
    name=sc.nextLine();
    System.out.println("Hi, "+name+" how old are you?");
    age=sc.nextByte();
    System.out.print("If you do not mind, "+name+", ");
    System.out.println("what is your monthly income?");
    income=sc.nextDouble();
    System.out.print("Great! "+name+", ");
    System.out.print("you are "+age+" years old, ");
    System.out.println("and you earn "+income+" each month.");
    
  }
}

Exercise

Extend the program we wrote in the video such that, in the final message, the computer provides the annual salary of the user instead of the monthly wage. That is, the user will provide the monthly salary, and the program will calculate and display what the yearly salary will be.

Comment

We will cover mathematical operations in a future video. To stay in touch, please subscribe to Computing4All.com. Enjoy!

Transcription of the Audio of the Video

Hi,
I am Dr. Monika Akbar. I am the other instructor in this video lecture series.

Dr. Hossain has already explained two types of variables — integers and “double” numbers — in the previous lectures. Integers are round numbers. We write the integer data type as “int”. Doubles are numbers that have decimal values. From the last video lecture, you already know how to get input from the user.

Today, we will discuss a few more variable types, and we will learn how to get “user input” for different kinds of variables.

The program involving user input in Java

We will write a simple program, in which we will declare a few variables of different kinds. I will explain the differences between the variable data types on the way. Let us go to my desktop computer. I will share my desktop with you now.

The program, I will write today, is quite simple. For clarity, it is better if I show you the program output right now and then I will show you how I coded the program.

The program engages in a conversation with the user. At first, the program asks for the name of the user. Then the program will ask the user for age. Afterward, the program will ask to provide the monthly salary of the user. Notice that the program asks the second and the third question addressing the user by name. The questions have a conversation style. Today, we will see how to write this program.

The file I am using is MyProg.java. Therefore, the class is MyProg. I am writing my main method.

Inside the main method, I will write my code.

The variable: name

At first, I will declare the variables we will need for the program. As I said, the program will prompt for the name of the user. After the user provides a name, the program will greet the user using the name. That means the program needs to remember the name of the user. That is, the program needs a variable to remember the name. A name may have an arbitrary number of letters in it. For natural language inputs that may contain any number of letters or symbols, Java has a particular data type. The data type is called String. A String can hold practically any text, such as a name, or an address, or an essay.

For the name, I will use a String variable. I am writing the data type, which is String, then I am typing the variable name, which is the word “name”, and then I am writing a semicolon. The variable “name”, will capture the name of the user.

For the name, I will use a String variable. I am writing the data type, which is String, then I am typing the variable name, which is the word “name”, and then I am writing a semicolon. The variable “name”, will capture the name of the user.

The variable: age

The second variable I need is for the age of the user. I can use “int” or I can use double, but I would use another data type here to store the age of the user. The other data type, which is also a number type with a round value, is called “byte”. The byte data type can hold numbers that are no larger than 127 and no lesser than negative 128. Since age is most likely to be less than 128, I will use a byte data type to remember the age of the user. Note that we could use an integer too, but I wanted to introduce this new variable type to you. This is why we are using byte for the age. I am giving the variable a name “age”. Then I type a semicolon. I should again mention that byte store round numbers. That is the age has to be a round number, without any decimal point.

The variable: income

The third variable we will use is to store the income of the user. Income can be a large number. Therefore, I will use double. I am typing double income; then I put a semicolon.

Scanner for user input in Java

We now have three variables: name, age, and income. Notice that each of these variables has a different data type. Now, we will create a Scanner just like we did in the previous video. Recall from the last video that we have to include the Scanner class with our program so that this program can use the functionality written inside the Scanner class. At the top of my code, I am adding import java.util.Scanner and then putting a semicolon.

Now, we can create a Scanner object that will help us get user input of any data type. Today, I will give the Scanner object the name sc. I am typing Scanner sc= new Scanner (System.in);

sc is an object variable of type Scanner. sc would help us get user input. In the last video, we provided some explanation on this line.

Asking the user for her/his name

Now, I am going to write a question using System.out.println. That is, the program will ask this question to the user. Within System.out.println, I am writing, “What is your name?” At this point, if we compile and run the program we will just see that the program is printing “What is your name?” Then the program will end immediately, given that we haven’t told the computer to do anything yet.

After “What is your name?” is printed on the terminal, we want the program to get input from the user. That is the user will Type her or his name using a keyboard and the program should save the name in the variable we have to store name. We know that we have to use our Scanner object sc here.

Getting a String user input in Java using a Scanner object

We need to write the variable name in the left side, and then on the right side, we need to write whatever scanner functionality we want to write to get the input from the user. The right side of the assignment operator is always executed first. In the left side, you only keep one variable, in this particular case, the variable “name”. In the right side, I am typing sc dot nextLine(). That is “sc”, the Scanner object, has the capability to read a line of text. The capability is summoned by the nextLine() method. Now the right side of the assignment operator will be executed first, which practically will keep waiting until the user types and enters her or his name. Once the user types some text, the sc.nextLine() method captures it and creates a string. The assignment operator sends the string captured by the sc.nextLine() method to the “name” variable in the left side.

Asking for the age of the user

Now that the program remembers the name string the user provided in the name variable, the program can address the user by her or his name. I am going to write the next question that the program will ask, using a System.out.println method. The next question is, How old are you? This is great but I would like to include the name of the user in this question. For example, Hi John, How old are you? To do that, we will somehow include the name of the user in this System.out.println method.

Remember from the last video that, whatever we want to print “as it is” goes inside the quotations. To print the variable content, we directly provide it outside the quotations. We concatenate quotations parts with the variables using a plus symbol.

Since I want to say, “Hi”, I put Hi inside the quotation. Then I want my program to say, the name of the person who is running the program. The name of the person is saved in the String variable name. Therefore, I type the plus symbol concatenate the name with Hi. Then I write another plus symbol to concatenate the last part where the program will say, “How old are you?”

Partial program

Let us compile the program and run it to see what happens.

The program asks the user for her name. The user types her name, Jane Doe, and presses the enter button. Then the program addresses the user by name, saying “Hi, Jane Doe, how old are you?” Then the program ended its execution. That is because we did not write anything in the code to get user input for age. Let us go back to the code and work on the rest of the code.

Getting the age of the user using a Scanner object

Remember that the variable age is a byte data because we declared it as a byte. I am typing age equals, then on the right side, I will write something using the Scanner object to get a byte size number from the user. The command is nextByte. I type sc.nextByte();

The age variable will contain the age provided by the user.

Asking for income information of the user

Now, the next line, within System.out.print I am writing “If you do not mind,” in quotations and then I append the name of the person, and then I append a comma only. Notice that I have use System.out.print not System.out.println here. After this line is executed, there will be no new line. Whatever I will print next will be printed in the same line in the output.

Now I am writing a System.out.println, inside which, within the quotations, I am writing “what is your monthly income?” After this is printed, the prompt will go to the next line because we have used System.out.println, not System.out.print.

Getting the income of the user using a Scanner object

Anyway, at this point, the program should prompt for income. To get user input for income, we write income=sc dot . Now notice that we declared the income variable as a double. Therefore, we will write sc.nextDouble(); to get a double input from the user. This line will get the double input from the user and put it inside the income variable.

Displaying everything

Now that the program has everything, name, age, and, the income of the user. The program can display any message using these information pieces.

I will write two System.out.print methods and one System.out.println method to display what we want to tell the user.

We will say, “Great! “, then we want the program to state the name of the user, so we append the name varaible.

In the next System.out.print method we want our program to say, you are this many years old. In the “this many” part, we want the program to write the age that the user provided.

Finally, in a System.out.println we will write “and you earn this much each month.” In place of this much, we want the program to print the income that the user provided, which is stored in the income variable.

I use a System.out.println to make sure that after the last thing printed on the terminal, the command prompt goes to a new line.

Output of the program

Let us save the file MyProg.java. Compile it and then run it.

Notice, how it is working. The program asks the user for her name. The user provides the name, Jane Doe. Then, in the next question, the program uses the name of the user and asks for her age. The user provides her age. Then the program uses the name again for the third question. This time, it asks the user for her monthly income. The user provides a monthly income of, say 20000.
After the user enters the income, the program prints this nice message. Great! Jane Doe, you are 20 years old and you earn 20000 each month.

A limitation of the program

While this is a nice program, it has some flaws. It is always good to know the limitations of your programs. The more you know the limitations, the better you can make it foolproof. We will not make it foolproof today because we have not yet covered all the necessary topics to be able to make a program foolproof. Over time, we will learn more items, such as how to apply conditions and looping, that will help us make a program bug-free.

As I said earlier, the data type, byte, cannot hold any number greater than 127. If there is a lucky person in the world who is using the program and has age greater than 127, then the program will behave abnormally. Let us see.

Sample output to demonstrate the limitation

Let us say, the name of the person is John Doe. John types his age, which is 128. As soon as John hits the enter button after typing his age, the program shows an error and terminates. Notice that the error states “Value out of range. Value:”128″”

Every variable has a limit. On the screen, we have provided a list of data types and the range of numbers each data type supports.

Notice that byte supports numbers between negative 128 to positive 127. A short data type supports numbers between negative 32,768 to positive 32,767. Data types int, long, float, and double support larger and larger ranges of numbers. float and double have an extra power; they can handle decimal numbers, while byte, short, int, and long are only for round numbers.

Please visit the supporting page on Computing4All.com for today’s lecture for additional resources.

Final remarks

We always tell our students at the bachelor’s level, many of whom are just starting to learn a programming language, to have patience and keep practicing. Practice makes everyone perfect.

The learning principle is the same for everyone, whether the person is self-learning a programming language, or the person is learning it in a course. If you are learning all by yourself and watching this video as additional material, please know that we are making these videos, especially for you, because we know that you have little to no help. My suggestion is, please please please practice while you are watching our programming videos. After practicing what we cover in the videos, please go beyond and above to write another program of your choice, using the knowledge you gained so far.

If you find our videos informative, please give us a thumbs up, subscribe to Computing4All.com, and our YouTube channel. If you have any question, please send us a message via Computing4All.com or by simply writing a comment in the Comments section below. Thank you for watching the video.

Getting User Input and Making a Calculator Using Java: Video Lecture 3

I am writing this article in support of the video we made on the topic — Getting User Input in Java. The video helps new learners by providing explanations on how to develop a simple calculator program. The user of the program types on the keyboard to enter two numbers. The program captures the two numbers the user provides and then it applies addition, subtraction, multiplication, and division operations on the numbers.

Why a Programmer Needs to Know About User Input

A programmer needs to know about user input due to the tremendous need for user input in many modern day software pieces. Consider the calculator program you have on your phone or laptop. It requires your input to apply mathematical operations. Consider editor software like MS Word. We type on the keyboard, and MS Word saves what we type. MS Word helps us format what we want to print.
Consider the Google Maps App on your smartphone. You write a destination address, and the software provides you directions to the destination. That is, the program reads the address you provide.

Therefore, getting input from the user is quite common in computer programs.

The Video: Getting Input from the User, for a Calculator Program, Using Java

Getting input from the user is an essential part of programming. It can be intimidating for beginners. With some practice, writing Java code to get input from user becomes quite mundane over time.

Getting User Input from a Calculator Program Written in Java

The Final Program Used in the Video

In the video, we only covered how to get user input of double data type using a Java Scanner object. The programmer can use nextInt() instead of the nextDouble() method to get an integer from the user. The program that we came up with, for double numbers, in the video is provided below. Save the program in a file named MyProg.java.

import java.util.Scanner;

class MyProg{
    public static void main(String[] args){
        double num1;
        double num2;
        double res;
        
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the first number:");
        num1= scan.nextDouble();
        System.out.println("Enter the second number:");
        num2= scan.nextDouble();

        res=num1+num2;
        System.out.println("Summation: "+res);
        res=num1-num2;
        System.out.println("Subtraction: "+res);
        res=num1*num2;
        System.out.println("Multiplication: "+res);
        res=num1/num2;
        System.out.println("Division: "+res);
    }
}

Exercise

Write a program that does the following items.

The program asks the user for three double numbers and displays (a) the result of the summation of the three numbers the user provided and (b) the result of multiplication of the three numbers.

Comment

You will see more of user input in our future videos. To stay in touch, please subscribe to Computing4All.com. Enjoy!

Transcription of the Audio of the Video

Hi,
I am Dr. Shahriar Hossain. I am here today to help you practice more on variables. We will build a Calculator program today using Java.

From the last video lecture, you know how to add two numbers and how to subtract one number from another. In the exercise, which I provided on Computing4All.com, I asked for multiplication and division as well. I will extend the concept that I described in the previous class. I will write the code of the last lesson and also do the exercise, which is the inclusion of multiplication and division. That should be good enough for a quite primitive calculator.

One item is that in our code, we are hard-coding the numbers so far. That is, every time we change the numerical values of the variables, we need to compile the code to generate the class file because of the change. In an ideal program, the program should ask the user for two numbers, and then the program should do whatever mathematical operations it is supposed to do.

I will now share my screen with you so that you can see how I write the program. I will keep explaining on the way.

The starting of the code

Suppose, the name of the Java file I am working on is MyProg.java. Therefore, the class name has to be MyProg. The scope of the class is within a set of curly braces. I will now write the Main Method. I am writing the Main Method public static void main and the parameters. The Main Method has a scope too, within a set of curly braces. We will write the instructions inside the curly braces.

Please note that we are building a calculator program. Therefore, we need two numbers held in two variables. These two variables will be the operands of addition, subtraction, multiplication, and division. We are not working on any sophisticated calculator program today. The calculator we will build will only have the ability to add, subtract, multiply, and divide.

Declaring the variables

Let us declare two Double variables. We already know how to declare two Double variables from the last lecture. The names of the two variables that will become our operands are num1 and num2. I declare the first one by stating “double num1;”, and the second one by “double num2;”. I should mention again that we have to put a semicolon at the end of each instruction. The line public static void main is not an instruction. It is defining where is the starting of the program is. Therefore, public static void main does not have a semicolon at the end. Over time, we will see that there are statements in Java for which we do not put semicolons.

An Instruction is a unit task. In general, each instruction inside the main method must have a semicolon at the end.

Anyway, I declare another double variable named res, in which I will put results of the mathematical operations addition, subtraction, multiplication, and division.

Now we will put some values inside num1 and num2. Let us write instructions to put 25 inside num1 and 12 inside num2.

So far, we declared all the variables and initiated num1 and num2 with operands. I will first add the two numbers in num1 and num2 and put them in the “res” variable.

The assignment operator

Note from the previous lecture that, in a line, with the assignment operator, the computer executes the right side of the assignment operator first. Whatever the value of the right side is, the computer copies the value to the variable in the left side. The left side cannot have anything other than one variable.

Summation

When executed, res should contain the summation result. Let us print the summation result on the terminal, as we did in the previous video lecture. If we run and compile the program, we should see the value of res, which is the addition of num1 and num2, on the terminal.

To be exact, the output will be “Summation: 37”

Subtraction

Now, we would like to do the subtraction. Notice that after printing the summation result, we can reuse the “res” variable for any other operation. We will subtract. So, we write “res=num1-num2;”

We write a System.out.println instruction to print the subtraction result.

Multiplication and division

Similar to addition and subtraction, let us write the code for multiplication and division. Each of the mathematical tasks includes one line of instruction to do the mathematical operation and one line to display the result.

After you have written the code for all four operations, compile and run the program. We can see that results of all the operations — addition, subtraction, multiplication, and division — are correctly printed on the terminal.

Hard-coding is not a good idea, in this case

While I like the code so far, notice that for a pair of new numbers in num1 and num2, we have to recompile the code and run again, which is not a good idea for software development. The user does now know how to compile or change the code. Therefore, we need to modify the program in such a way that the program asks the user for two numbers, and then the program outputs the results of the mathematical operations carried over the two numbers that the user provided.

Assigning values directly in the code like the ones we have done here, is called hard-coding. Instead of hard-coding the numbers we will change the code so that the program asks for input to the person who will run the program.

Getting user input in Java may not look straightforward

Getting input from the user is not entirely straightforward. I will introduce a few new items regarding getting information from the user. The items might not make much sense at this point because we are still not familiar with methods, classes, and objects. We will be using the new items to get input from the user. Much later, when we learn advanced topics, we will understand the inner functionality.

Java Scanner

Anyway, to enable your code to get inputs from the user, you need to use the Scanner class, which we are not familiar with at all. At the beginning of the code, even before the first line, now we have to write “import java.util.Scanner;”. For now, the explanation that might make sense is the following — this particular class “Scanner” has the functionality written in it that allows a program to get user inputs. Through this line, your program is telling the Java Virtual Machine to import that functionality of scanning numbers from users.

Now, instead of hard-coding the numbers to num1 and num2, we will ask the user to enter two numbers by typing on the keyboard. Our program will assign the two numbers that the user provided to num1 and num2.

Before the assignments, we will have to create a scanner object. To create a scanner object named “scan”, I am writing this line. We have not discussed objects yet. Therefore, it will be hard for you to understand this line at this point. For now, you will have to trust the following explanation: this line creates a scanner object named “scan” that is capable of capturing the input the user will type on the keyboard.

Getting user input in Java: The nextDouble() method

Previously we assigned 25 to num1 and 12 to num2. These two lines must change because we are not hardcoding anymore. Instead, we will tell the computer to copy the number that the object “scan” captures to the variable num1. In the right side of the assignment operator of num1, we write scan.nextDouble();

That is, the object “scan” will wait for the next double number entered by the user. Once the user types a double number and hits the enter button, the “scan” object will send it to the num1 variable. If the user does not type a number and does not hit the enter button on the keyboard, then the program will remain waited at that point.

Now let us do the same for num2. In the right side of the assignment of num2, we will write scan.nextDouble();

In this line, the program will wait for the second number to be entered by the user.

Now, the program is ready. Save the MyProg.java, and compile it.

User input on terminal

Now let us run the program. Notice that the program is not displaying anything. Instead, it is waiting, which looks like the program is stuck. Actually, it is waiting in the line “num1=scan.nextDouble();” It is waiting for the user to type a number and hit enter. Now, as the user, I am typing 22.4, and then I press the enter button.

Notice that the program is again waiting. It is because now the execution is in the line “num2=scan.nextDouble();” The computer is waiting at “scan.nextDouble()” for the user to enter another number, which the computer will put in variable num2.

Therefore, as the user, I am typing 2.0 and then I will hit the enter button. As soon as I will hit the enter button the scan.nextDouble() will capture the value 2.0. Then the assignment operator will send 2.0 to num2.

Once num1 and num2 are ready, the computer will execute the rest of the lines in a jiffy. That is, the summation, subtraction, multiplication, and division results will be printed as soon as the num2 variable receives a value from the user. Now, I will hit enter, and the program will print all the results.

The user can run the program again and again. Each time the program will wait twice for two variables, num1 and num2.

Prompting for user input

One thing that I would like to include in the program is a message on the terminal before the program starts waiting for num1. I would like to add System.out.println and then write “Enter the first number: ” inside the parentheses inside quotations.

Similarly, before the scanner waits for the second input from the user, I would like to print on the terminal “Enter the second number: ” using a System.out.println method.

Save MyProg.java and compile it. Run the program. Now notice that the program prints “Enter the first number: ” before it starts to wait for the first input. Now I enter 20.2. The program now received the first input. Before it started to wait for the second input, it printed “Enter the second number: “. Now I enter 2.0. The program prints all the results.

Notice that this version of the program is more user-friendly since the program is communicating with the user by providing guidelines like, Enter the First number, or Enter the second number.

Conclusion

If you have any question, or if you are struggling to compile and run any of the programs we discussed so far, please do not hesitate to contact us via Computing4All.com or by leaving a comment in the comments section.

Thank you for watching the video. We will be coming back soon with another video in this video lecture series. To stay in touch, please subscribe to Computing4All.com and to our YouTube channel.

An Introduction to Variables in Java: Video Lecture 2

I am writing this article today in support of the video I made on Variables in Java. The video describes a little bit of theory and then demonstrates how you can use multiple variables in your program. I used simple applications — addition and subtraction of two numbers — to describe how to use variables in Java. The target was to make the video suitable for learners who have just started to gather study materials to learn the Java programming language.

Watch the video and practice at the same time. Pause and repeat as required. Learning will remain incomplete without practicing the content of the video. Please note that learning a programming language requires practicing. It is like learning to swim. Reading a book on how to swim helps in understanding the principles, but no one can become a swimmer without really attempting to swim.

The Video: Variables in Java

Variables are in the core of any programming language. Learning to handle variables in Java will aid in learning any programming language later.

Video lecture on how to use variables in Java.

Additional Resources

The following two pages provide further details on variables in Java, especially regarding the naming convention of variables and basic data types.

  • Variable naming convention: Please read the “Naming” section of the link.
  • Primitive data types: The link will give you an idea on what general variables are there in Java, other than int and double that we covered in the video.

Exercise

If you want to practice more on the use of variables in Java, here is an exercise for you.

Write a Java program that has at least two double variables named num1 and num2. Assign any decimal values to num1 and num2. Then on the terminal, display the addition (num1+num2), subtraction (num1-num2), multiplication (num1*num2), and division (num1/num2) results. When showing a result, put a text first and then put the result. For example, for the summation, if the summation is 35.8, then display the following sentence: The Summation is 35.8. That is, do not just print the results; put some context with each result.

COMMENT

We will come back with the next video in this video lecture series in a few days. We will cover more on variables in Java. To stay in touch, please subscribe to Computing4All.com. Enjoy!

TRANSCRIPTION (OF THE AUDIO OF THE VIDEO)

Hi,
I am Dr. Shahriar Hossain. I am here today to explain and help you practice the concept of variables in Java programming language. In our previous video, I explained how to write, compile, and run your first Java program. We are advancing toward more and more rigorous programming concepts. Although I am teaching programming language Java in this video lecture series, the concepts will help you learn other programming languages. Overall concepts are similar between core programming languages.

My target is to cover the theories as well as to help you practice some applications. In each video, I will try to cover the theory and then share the view of my desktop with you so that you can see how I write a program to practice the theory.

What you will learn today

Today, you will learn the concept of variables. The concept of variables is in the core of any programming language. You handle data through the use of variables in your programs. Today, we will see how you can add two numbers stored in two variables. I teach very slow so that everyone can cope with any new concept I cover. There is no point of making these videos if I cannot explain the concepts well to you in a meaningful way.

Thank you for your feedback

After publishing the previous video, I received a message from one of the viewers stating that she/he was not able to hear what I was saying because the sound-level was not adequate. I really appreciate any feedback. I checked my microphone. I figured that the problem was not with the microphone. The problem was and still is me. I do not and probably cannot speak loudly. As a solution to the problem of low-level audio, I will amplify my voice using a synthesizer before publishing the video. Thanks to the person who provided the feedback.

Please keep sending us feedback regarding any of the videos we make. You can provide feedback through Computing4All.com or directly from YouTube comments section below the video.

Let us talk business now. Let us talk about what variables are in a Java program?

What is a variable?

A variable in a Java program or in any program written using any standard programing language refers to a content kept in memory space. When I said “Content” I meant “data”. For example, a number is a data content. A person’s name can be considered a data content. You want your program to remember some data content throughout the runtime of the program. Anything that you want your program to remember has to be stored in variables.

Now, where are these variables kept? In a computer, when you run your program, the variables are kept in the main memory of the computer. The main memory of the computer is commonly called RAM, which is short for Random Access Memory. Therefore, whenever you run a program the program uses some space of the RAM to store things it has to remember. When you write the program, you provide instructions on how to use the variables.

There can be many types of data and hence variables

Now, think about how many types of data you may have. Actually, there can be many types of data. For example, some data can be numeric, like age, salary, price, or any countable amounts. Some data types may not be numeric. For example, names of people, address, book title, these are non-numeric data. Such non-numeric information pieces, which require natural language are generally called strings.

So far, we have discussed numeric data and strings. There is another type of data, which is just one letter, for example, sometimes on calendars, you see the days of the week stated as S for Saturday, S for Sunday, M for Monday, that is the first letter of the day of the week is used to represent the day. Such one letter symbols are called characters. Therefore, ‘a’ is a character. ‘b’ is another character, so and so forth.

We have talked about three types of data. (1) Numeric, (2) Non-numeric String, which has more than one letter, and (3) characters containing just one letter.

The concept of a container

In this particular video, we will only practice two of the numeric data types. Now let us think about numeric data types. Some number are small; some are big. For example, the age of a person. How large this number can be in reality? Probably, age can be 100 years or at most 120 years. Now, consider the yearly income of people in the United States. It can be as small as zero. It can be as large as a few million. Therefore, a variable that stores age of people can have a way lower capacity than a variable that stores the income of people.

You can consider a variable as a container. If you need to carry one liter of water from here to there, you do not use a barrel that can hold fifty gallons of water. You will probably prefer to use a bottle instead of a barrel. On the other hand, if you need to move 40 gallons of water, you will probably use a large barrel instead of using a small bottle because to move 40 gallons using a small bottle you will have to back and forth several hundred times.

Memory space in a computer is limited. Therefore, we use variables wisely. I mean, we do not have to be wise at this point because our programs are quite small, but at some point, we will have to make sure that we are using the correct type of variable for the right kind of data.

What types of variables do we discuss in this video?

Today, I am going to cover two types of numeric variables. The first one is called Integers, and the second one is called real numbers or double numbers.

An integer variable can hold numbers that do not have any decimal point. For example, 5, or, 10, or, the number 20. You cannot keep the number 3.6 in an integer variable. To hold numbers that have decimal points, you need a double or float variable. I will demonstrate how we can use integer and double variables in Java.

Now, let us go to the computer and take a look.

Writing MyProg.java

At first, I will write the structure of the program. As I said in the previous video, I use a simple text editor to write my programs. I am using XCode now on a Mac. You can use notepad on a Windows machine. The name of the file I will work on is MyProg.java. As you know from the previous video, the name of the class has to be MyProg if the finename is MyProg.java.

Inside the scope of my MyProg class, I am writing the main method. The main method has the combination of syntax “public static void main” and String start and end square brackets within the parentheses. Then write args.

Then mention the scope of the method by providing a set of start and end curly braces.

Everything we will write today will be inside the scope of the main method.

Suppose, the problem we are going to solve today is the following. How can we add two numbers and display the result?

Declaring variables

The first thing to do is — declare two variables for the two numbers. That is we will store each number is a variable.

We are going to use an integer variable for each of these two numbers.

This is how we declare integer variables.

The first thing to say is the data type then we have to give a name to the variable. The data type Integer is expressed by just “int” in Java.

I type int then I provide a variable name. The name of my variable is “a”.

We could name my variable “aa”, or anything we want, within certain restrictions. One convention is a variable name should start with a letter. A restriction is, you cannot use a reserved word as your variable name. For example, you cannot use the word “class”, or “public” as your variable name because these words are already reserved by Java to be used in the code.

Anyway, I type int then I put the variable name “a” then I put a semicolon. When I put a semicolon, the Java virtual machine detects it as an end of one instruction. Therefore, int a semicolon is a complete instruction. When running the program and running this specific line, the Java Virtual Machine will create a variable, which has the data type of  Integer and the name a.

Now, let us create a second variable. We will keep the second variable of the same type as a. We will give the second variable the name “b”.

Therefore, we write int b and then put a semicolon. Now we have two variables. That is, Java has created two variables where we can put numbers.

The assignment operator

Let us put numbers in each of these containers a and b. This is how we are going to do it.

We just write a equals 10 and put a semicolon.

The equal symbol is called an assignment. The right side of the assignment is executed first and then the value is dropped inside the variable in the left side. I should mention to clarify that the left side of an assignment operator can have only one variable.

Instead of writing, a equals 10, we could write a equals 8 plus 2. In that case, the virtual machine will execute the right side of the assignment operator first, which would result in 10 and then copy the value 10 in variable a. That means, the container a will contain 10 after the execution of this line. By container a, I meant variable a.

Now, let us put another numerical value in the variable b. We write b equals 20 to put 20 inside variable b.

When we will run the program Java will come to the first non-empty line inside the main method. It will create the integer variable a. Then, it will create the integer variable b. Then it will put 10 inside variable a. It will put 20 inside variable b. Notice that we have not displayed anything yet. Suppose, we want to display the summation of variable a and variable b on the screen.

Displaying the summation: The wrong way

We might remember from the last video lecture that we use System.out.prinln to print whatever we want to print on the terminal. So I am writing the System dot out dot println instruction here. A note from the last video – we write whatever we want to write inside quotes. So, I am writing inside quote “a plus b”. Soon, we will see that it is not the right way to print the summation of a and b. Let us compile and run the code. You will see what I am saying.

I use Javac to generate the class file. The command is javac MyProg.java. MyProg dot class is generated. Now, I will run the class. The command is java MyProg. After I run it, I should see the summation of a and b on the screen. Oops. Wrong. I see the text “a+b” is written. I wanted to see the summation of a and b. Therefore, I have written something wrong in my code. Let us go back to the code.

Displaying the summation: The correct way

Notice that I write a plus b inside double quotations. Whatever is written inside quotations, will be printed on the terminal and that is what happened in the output of the program. The text “a+b” was printed. This is what we do to really print the summation of the variables. We just remove the quotations. When we remove the quotations, Java will execute whatever you have within the parentheses. You have a plus b within the parentheses. a is 10 and b is 20. The summation of 10 and 20 is 30. Therefore, System.out.println will print 30 on the screen. Let us compile the java file again. Let us run the code now. You can see that the result 30 is printed on the terminal now.

Congratulations

If you are practicing with me right now and if you have come this far of this video, many many congratulations on the successful use of two variables using a Java code. You will be surprised to find what you can do with this knowledge. You can practically write a calculator program with the knowledge you have gained so far. Let us go with a small example today. Let us go to the code.

Copying the result to a variable

We will modify the code a little bit. Let us introduce another variable named result. This variable result will contain the summation of the two variables. I am writing int result and then I am putting a semicolon. Therefore, when this line will be executed, there will be a variable named result, which may contain any number. Now, I am writing result equal a plus b. Then put a semicolon.

When this line is executed, the right side is executed first and whatever is the outcome of the right side is copied to the variable in the left side.

In the right side, the virtual machine will find a, which is a variable then plus, then another variable b. Java will take the content of “a”, which is 10. Then it will take the content of “b”, which is 20. Then Java will sum up the contents, which will be 30. Now, Java will take 30 and put it in the variable at the left side. Therefore, the variable named “result” will contain 30 after this line is executed.

Now, in the System.out.println part instead of writing a plus b, I will just write result. Therefore, System.out.println will print whatever content I have in the variable named “result”. Hence, 30 will be printed.

If we compile the code and run it again, we will see that the result is 30, as expected.

Subtraction

Now, we will try to do a subtraction, but I will use the same variable “result” to store the subtracted value.

One thing to notice here is that after we print the summation using System.out.println method, we can reuse the result variable to hold the subtracted value. The computer executes the program line by line in a sequence. After executing the summation, we want to print a subtraction result. Therefore, after the summation result is printed we, write result equals a minus b. Then put a semicolon. Remember that a is 10; b is 20. Therefore, the subtraction result will be negative 10. Now, we will print the result using another System.out.println instruction.

Let us compile our MyProg.java file. Then run the program. Now notice that the first line contains 30 and the second line contains negative 10. The output displays addition and subtraction of two variables a and b, where a is 10 and b is 20.

Printing numbers without context is boring

Now, notice one thing that the numbers are directly printed, without any context. I want to at least say, “The summation is 30” instead of just printing 30. And, “The subtraction result is -10” instead of just printing negative 10 on the terminal.

To accomplish this, we have to work on our System.out.prinln instructions. We already know that, when we want to print plain text, we write the plain text inside double quotes and put it in the parentheses of System.out.println statement. We will do that right now.

How to include context text in the terminal output

With the System.out.println method, for the summation result, I am writing “The summation is ” then I want Java to put my result. I cannot write the variable name “result”  inside the quotations because in that case output will be “The summation is result”. What we will do is we will keep the variable name “result” out of the quotations. We will tell java to include the content, 30, of the variable after this text.

To concatenate two texts or one text and one number, we just use the plus symbol. In this case, we tell the computer that we want to include the number in the variable “result” after the text “The summation is ”. Notice that I have written, in quotation “The summation is ” then I typed a plus symbol and then I write the variable result. When printing, the System.out.prinln method will replace any variable name with the content of the variable. As a result, the printed item will be “The Summation is 30.”

I am making a similar modification for the subtraction by adding “The subtraction result is ” before the variable result. I have used the plus symbol between the text and the variable name, like the previous line.

Now, compile the file and run it. We have the desired output. The first line contains “The summation is 30” and the second line contains “The subtraction result is -10.”

An introduction to “double” numbers

Now that you have learned about variables, you can do a few tests. For example, can your code handle decimal numbers?

Let us check. Let us change the value of the variable a to 22.5. Now let us see what happens if we compile the code. We receive an error. The error states that the variable a and the number 22.5 have something to  do with “incompatible types.” The reason of the error is, data type “int” can only handle integers, that are numbers that do not have any decimal points. A type that can handle real numbers or, numbers with decimal points is called double. Let us change the integer type to double. Now, let us change the type of b as well to double. Therefore, a and b are both now capable of holding real number, that is, numbers with values after the decimal point.

We need another modification. The variable “result” should be “double” just like a and b because the summation or subtraction it will hold now is also a real number with a decimal point.

Let us compile and run the program now. Notice that the first line now contains “The summation is 42.5” because a was 22.5 and b was 20. The second line contains “The subtraction result is 2.5”, which is correct for “a” equal to 22.5 and “b” equal to 20.

You can now change the values of a and b, then compile and run the program to get a feeling about how your program with multiple variables work. The website computing4all contains exercise associated with today’s video lecture. The more you will play with your code the more you will become skilled.

Conclusion of the video

As I said in the previous video, practice makes women and men great in programming. Therefore, keep practicing. Too keep in touch, subscribe to our website computing4all.com and also subscribe to our YouTube channel. I will see you in the next video. Happy programming!