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!

How to Write Your First Program Using Java: Video Lecture 1

Writing the first program using Java can be intimidating, especially if someone is learning a programming language for the first time. Please do not be afraid or discouraged. If you saw someone write programs in the speed of light — especially in movies when there are only ten seconds left to a terrible happening, which only a nerdy programmer can stop — you have to understand that it is just a freaking movie.

In the following video, you will watch how you can write a program to display a sentence or two on the computer screen. Trust me, if you and I cannot write and generate the program to display a sentence in two minutes, the nerds in the movies will never be able to write a program to stop a terrible happening — for sure not in ten seconds. A big BOO to all those movies that create misconceptions regarding programming, computing, Artificial Intelligence, and Data Science.

The Video: How to Write, Compile, and Run Your First Java Program

We created the video keeping new learners in mind. As a result, the video contains many details. We have plans to publish more videos on programming using Java in a sequence that we use to teach in a bachelors-level programming course. All the videos will explain topics keeping new learners in focus.

How to write, compile, and run your first Java program.

Exercises

If you want to practice more after watching the video, here are some follow-up exercises for you.

Write a Java program that displays the following texts on the terminal/command prompt.

Hello, world!!!
Java is cool!
I love mocha too.
I do not know why a programming language is named after coffee.

Write a Java program to display the following sentences on the terminal/command prompt.

I have 2 pencils on my desk and 3 in my drawer.
I have a total of 5 pencils.

Comment

I am pretty sure you will be able to modify the code we discussed in the video to solve the exercise above. We are planning to come up with the next video in this lecture series in a few days. 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 with your first Java program.

The video is intended for people who have planned to start or have started recently to learn the Java programming language.

What you need for the exercise in the video

You will need a laptop or a desktop computer to practice the items I cover today. You will need three items, on your laptop or desktop, to practice the content I will cover today. First, you will need a simple Editor. I will explain more about simple editors soon in this video. Second, you will need the Java Development Kit SE installed on your computer. On Google, please search with the phrase Java Development Kit SE and you will get the link for a download. Install the Java Development Kit on your machine, if it is not already installed. Third, you will need to use the terminal, which is already installed on your computer. On a Windows computer, it is called a Windows terminal, and on Mac, it is a Mac terminal.

Please keep watching the video, I will explain more when time comes.

I will try to explain everything slowly with details. Many times, we think about the coverage of materials and teach too fast in a university classroom. As a result, students sometimes struggle with the topics we cover. The struggle is not because the students do not have the background but many times it is because we, the professors, do not give students enough time to follow through.

This particular video is not from my classroom. A great thing about a video is that you can pause it and repeat as many times as you want. I am hoping that today’s material will give you a clear idea of how to write and run your first Java program.

In a few seconds, I will go to my computer and share the screen with you and demonstrate how to write a Java program, compile it, and execute the program YOU have written. I hope you will enjoy it.

Editor

I am going to write my first program. The name of the program is Welcome. This is why I named the program file that I am writing Welcome.java. I am writing Welcome.java using a plain text editor. A plain text editor is something like notepad on Windows. You cannot draw anything as you do on MS Word using a simple text editor. On a mac, you can use Xcode just like I am using it to write my program. Please note that you cannot use sophisticated document editors like MS Word to write your programs. Your program has to be written using a text editor. If you are using Windows, notepad is an excellent editor to start with. For Mac, Xcode is a good start.

Again, the name of the file on which I am writing now is Welcome.java.

Starting of a Java code

A Java code starts with the syntax class. Later, we will learn that there can be some other items even before writing the syntax “class”. For now, let us say that a java file starts with the word/syntax class. Then you have to write the class name. The class name is exactly the same as the name of the file but without the extension .java. Therefore, the name of the class is Welcome. Just welcome.

Scope of a Java class

After writing “class Welcome”, we have to tell the scope of the program. In Java, mentioning the scope of something is done using curly braces. I am typing an opening curly bracket here and a closing curly bracket here. Everything I will write for the program will be inside these curly braces. These curly braces are defining the scope of the program I am writing.

The Main method in a Java program

A java program starts with the main method. Later in another video in this sequence, I will explain what methods are. For now, we just need to know that a Java program starts from the main method. Inside the class, I am going to writing the main method. The syntax for the main method is “public static void main”. I will explain the meaning of each of these words in a future video.

Then in starting and closing parentheses write String start and close brackets args. This line is something that has a lot of unknowns at this point. The topics associated with each of the words in this line are covered a little later in a programming course. So, bare with me regarding this line. Just know that this line is a marker for the computer from where your program will start. We need a set of curly starting and ending curly braces to state the scope of the main method we are going to write. Whatever instructions we will write inside this scope of the main method, the computer will execute it.

Writing an instruction

Now, we will write our first instruction. A common standard in Java or in most of the programming languages is that one instruction should be written in one line. Later, we will see that one line may have multiple instructions too.

One question you may ask is, what instruction do we want to write. At this point assume that the purpose of the program we are writing is to display several sentences on the screen. Therefore, the instructions we will write are relevant to writing something on the screen.

The instruction, which is practically a Java method, is System dot out dot print. Then within parentheses write whatever you want to print. In this case, I am telling the computer to print “Welcome to the world of Java ” Whatever I want to print must be inside quotations. These are double quotations. At the end of each instruction, we must write a semicolon. The semicolon indicates the end of the instruction. Without the semicolon the computer will be lost regarding the end of the instruction.

Please make sure that you have this piece of code written before we go to the next step. The next step is to compile this code and generate the program. Then we will run the generated program to check if our program prints the sentence “Welcome to the world of Java ” on the screen.

Compiling a Java code

Again, I have written the code in a file named Welcome.java. The computer cannot directly execute a high-level program written by humans. We will use the Java compiler to generate a program, which is a file with .class extension. The computer can execute the class file.

When I said the computer can execute the class file, I meant that the Java virtual machine can execute the class file. Java virtual machine, which can execute our programs, is also called in its short name JVM.

Let me show you the entire process.

Using the Terminal or a Command Prompt

You have your code written in a file Welcome.java. You need to open the terminal now where you will be able to compile and execute the program you have written. The terminal on a Mac is called TERMINAL. On a Windows system, the Windows terminal is a program called CMD.exe. I am showing this example using my Mac terminal. The java commands are the same for all types of desktop and laptop computers.

A terminal is a program from which we can execute other programs. We will execute the Java Virtual Machine, as well as the Java Compiler from the terminal.

Notice that I am first typing the word java and pressing the enter button to check is java command is present on my computer. The command is showing me java-related parameters indicating that java is present on my computer. Then I am typing javac and pressing the enter button, which shows me some massages  printed by the javac program. This is an indication that javac is already present in my computer. Therefore, I am ready to compile and run my program Welcome.java.

If your terminal displays a message saying “Command not found” when you type java or javac and hit the enter or return button,  then your computer does not have java or the terminal is not recognizing the path that contains java virtual machine. Please make sure that you have installed java and your terminal recognizes the path of the Java Virtual Machine.

Some commands like ls or dir, and clear or cls

Then, I clear the terminal with the command clear. Now, I have to make sure that my terminal’s command prompt goes to the directory where I have Welcome.java. I use the command cd to reach to the folder where I have the file Welcome.java. To make sure that my command prompt is currently located in the directory where I have welcome.java, I just type ls, which shows me the content of the current folder. I see that the file Welcome.java is in the current directory. Therefore, I can execute the java compiler to generate the class file.

Sequence: Write Code → Compile → Run

I should mention at this point that the sequence of creating the program is the following: At first, write your code in a java file. Then compile the java file using javac, which is the java compiler. After compilation, a class file is generated. The class file is the program that Java virtual machine recognizes. Run the class file using the program java.

The javac command

So, I am now going to use javac to compile my Welcome program.

I typed javac Welcome and then hit the enter button. It gives me an error because I missed the .java extension. Then, I typed the javac command with Welcome.java, the full file name. Notice that a class file is generated in the folder immediately. The name of the class file is Welcome.class. Welcome.class is the actual program that java recognizes. Now, we will run the class Welcome.

The java command

To run the generated Welcome.class, we have to run the command java Welcome. The java does not require the .class extension in the command. Therefore, running the program is plain and simply java Welcome.

Notice that we wanted to print Welcome to the world of Java. The program has printed it on the terminal screen. If you have come up to this point of the video and practiced it on your computer, Many many congratulations on the execution of your first Java program.

Can we make the output esthetically better

Now, although the line is printed on the terminal, the command prompt appears right after the sentence ends, which is practically an eyesore. I would like to see the command prompt in a new line. The way how we solve the problem is, use System.out.println instead of System.out.print. Let us change the code and see if we can make the output esthetically better.

Now, that I have changed System.out.print to System.out.println, there should be a new line at the end of the displayed output on the terminal. We will have to compile the program using javac again because we have changed the code. To run the newly generated class file we again use the command java Welcome.

Notice that the output now contains “Welcome to the world of java …”, and the command prompt has been moved to the next line.

How can we print a second sentence

Now, suppose we want our program to display a second line containing “I love to code using Java.”

All we have to do is write another System.out.println instruction in our code. The parentheses of the System.out.println method will now contain “I love to code using Java.” After including the line, save the file Welcome.java.

Compile the code using javac because Welcome.java has been modified. Now run the class file using the java command. You have two lines as the output of the program. The first line contains “Welcome to the world of Java” and the second line contains “I love to code using Java.”

These two lines are printed on the terminal because using your code you told the computer to print them on the screen.

Now, you can print as many lines as you want on the terminal by writing as many System.out.println instructions as you need. In the future, we will learn more basic items of programming and move forward to solve complex problems.

Conclusion of the video

I hope that you enjoyed the video. I always tell my early stage classes in Computer Science that learning to program is not the hard part. The hardest part is to develop the skill through which you will solve problems. Practice makes women and men great in programming and problem-solving. Hope to see you soon with another video.