Notes 2 - Introduction to Java(User Input, Data Types, Conditions, Loops)
Objectives:
Introduction
Welcome back to Lecture 2! In Lecture 1, we were able to get to know what Java is, how to write notes within our code via Comments and we also learned that we can store some values in the memory of our computer which is called Variables. In this lesson, we are going to get to know variables even more, learn how to read user's input and use it. We are also going to get to know about conditions and loops and learn their different syntax and functionalities and most importantly their importance in programming.
User Input
To begin with, we are going to learn about how to read user's input from the terminal window. In the previous lecture, we were able to write code that looks like this:
public class Hello {
public static void main(String[] args) {
String name = "Andrew";
System.out.println("Hello, " + name);
}
}
This code works fine and will print "Hello, Andrew" to the screen since the value of the variable name is "Andrew", however it would be inconvenient for our users who does not know how to edit code to make it correct for the user. Let's say the user's name is not Andrew, it could be Sam or David and though the program seems to run just fine however, it is not correct since the program will say "Hello, Andrew" instead of "Hello, " + what ever the user's name is. A solution for this is that we will allow users to input something on the terminal window. That's where User Input comes in. User Input is a special feature for probably each programming language that allows users or developers to test the program they're working on before sending it to their client. In Java, taking user's input could be a little bit challenge than other languages because its syntax looks like this.
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name? ");
String name = scan.nextLine();
System.out.println("Hello, " + name);
}
}
At glance, there are a lot of new in this code however, there are some that are pretty familiar to us from the previous lessons. So let's go ahead let get to know these lines of code.
import java.util.Scanner;
For us to be able to read user's input for the first time, first we need to import some class that has the functionality to do it and that class is Scanner. Scanner is imported from java.util. We will learn more about packages in the later chapters and lessons in this blog but for now we'll focus in reading the user's input for the first time. So we named this class Hello and we also declared main() in it.
Scanner scan = new Scanner(System.in);
We also need to understand that Scanner is a class which means that it contains methods with different functionalities. Methods are actually functions within a class and we'll going to discuss more about methods and classes sooner. For now, we have to understand that in order for us to have access to the methods that's in the Scanner, we first need create object for it. In our example above, we treat Scanner as variable type then followed by scan which is the variableName. You can name the object anything you want just like declaring a variable. Scanner is the data type then the name of the variable. If you don't understand what's the meaning everything to right after the equal sign, that's okay. You just need to do it every time you need to read user's input for your program.
println() vs print()
In the previous lesson, we learned that println() let's us print something on the terminal window. print() also has the same functionality. Their only difference is that, println() creates a new line after it printed everyting on the terminal window while print() not. In this code, we noticed that we used print() instead of println() to ask for the user's name.
scan.nextLine();
In the fifth line, we created an object for the class Scanner named scan which means we can now access some of the methods in Scanner which we can use to read user's input. That one that we used in the example is nextLine(). nextLine() is a method inside the class Scanner that can read String value from user's input. To access the method, we need to call the object, a dot, and then the name of the method. In this case, we used scan.nextLine(); There are also few methods that can read different type of user's input and store it in our variable named name. Here are some:
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Then finally, we can now print the user's input to the terminal window. Just as
C:\Users\admin\Desktop\Java Files>java Hello.java
What is your name? Andrew
Hello, Andrew
Data Types
In programming, data types refer to what type of data are we storing or working on. And it is very important that we learn data types. There are different types of data that we can store in our computer. And as we have learned from the previous lesson, variables are like storage box or drinking bottle that has its name and its content which is water or anything you can drink. Same goes in programming. We need to know and understand what type of data are we working on. Here are some of different type of data exists in Java programming, The primitive and the non-primitive data types. Here are the some primitive data types: byte, short, int, long, float, char, and boolean. Non-primitive data types are String, Arrays, and Classes (you will learn more about these in later chapters). Each primitive data types can store certain amount of memory while non-primitive data types memory size are unknown because they're constantly changing.
Numbers
There are different data types used to store numerical values and it is divided into floating and non-floating numbers. Non-floating numbers do not store decimal values while floating numbers do. Non-floating values are also called Integers. There are four primitive data type that can store integer values and these are byte, short, int, and long where byte has the least size that is only 1 byte and longs is the greatest with that it can store up to 8 bytes. In floating numbers, there only 2 data types used in Java programming and these are floats and double. These two data types are related to each other only is that float only has 4 bytes of memory while double has 8. int and double are often used in Java programming.
Boolean
Boolean can only take one of the following values, true or
false.
Characters
The char is used to store a single character. The character
must be surrounded by single quotes, 'e', 'a'. Each character has its own
ASCII value. This means that you can also store the ASCII value that instead
of coding like char = 'A', you can also do this char = 65 or char =
64.
Non-primitive
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
- Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer is not defined by Java (except for String).
- Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot
- A primitive type has always a value, while non-primitive types can be null.
- A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
- The size of a primitive depends on the data type, while non-primitive types have all the same.
Conditions
Now, we have learned how to read user's input and use it in
our program and a little bit about data types. And we are now in one of the
most important feature of every programming languages, and it is Conditions.
Conditions are use to make the computer choose from true or false. There are
different syntax and keywords we can use to implement conditions. The most
popular one is "if" and "if-else"
if
if keyword literally means to do something under a certain condition. It is just saying that if something is true, then do some tasks. Here is its syntax:
if (condition) {
// block of code to be executed if the condition is true
}
This syntax means that if the condition surrounded by parentheses is true, then execute the block of code inside of it which is also within two curly braces or {}. Let's take this next example.
String name = "David";
if(name.equals("David")) {
System.out.println("Great choice!");
}
In this example, we initiated a variable called name and assigned the value "David" to it. Then in the next line, we stated a condition that if the value of our variable name is equal to "David", then execute the block of code that's in it, otherwise ignore it. In this example, the output will be "Great choice!" since the value of the variable name is indeed "Andrew". If not then nothing will be printed on the terminal window. Note: The block of code inside will be executed if and only if the condition is true, otherwise it will be ignored.
if-else
Java also has special feature for condition if which is if-else. if-else basically means that if the condition is not true, then proceed. Just take a look at this example below:
String name = "Panfilo";
if(name.equals("Andrew")) {
System.out.println("Great choice!");
}
else {
System.out.println("Better luck next time!");
}
Let's say we set the value of our variable name to "Panfilo" and the condition inside our if is, is name equals "Andrew", but since it is not true that the value of our variable name is "Andrew", then the block of code in it will be ignored, instead it will execute the block of code that's in else. However, if the condition inside if is true, then its block of code will be executed and the block of code of else will not be executed. But in this example, since name is not equal to "Andrew", we will expect an output saying "Better luck next time.". Note: the equals() method is exclusively used for String data types, if we are going to state conditions using other data types, then we must use comparison operators. Comparison operators are symbols that we used to compare two different values. Take this example below:
//A program that determines if the integer is odd or even number.
int x = 5;
if(x % 2 == 0) {
System.out.println("Even");
}
else {
System.out.println("Odd");
}
There are unfamiliar symbols in this example which are '%' and '=='. The symbol '%' is an arithmetic operator that takes the value of the remainder of two values divided and the symbol '==' is a comparison operator that determines if two values are equal. The statement x % 2 == 0 means take the remainder from x divided by 2 equals 0. This statement will return the value true or false depending on the value of x. In this example, the value of x is 5 and if you divide it by 2, it will give you a remainder of 1 which returns the value false it is not equal to 0 and since the condition is false, then execute the block of code in else. One more feature of if condition is if-else-if. This basically means that you can create a series of if else. See this example below:
//A program that determines if the integer is positive, negative or zero.
int x = 5;
if(x > 0) {
System.out.println("Positive");
}
else if (x < 0){
System.out.println("Negative");
}
else {
System.out.println("Zero");
}
This example determines if the value of x is positive, negative or zero. Inside the conditions statement, we can see some familiar symbols which are '>' and '<'. The whole statement means that if x is greater than 0, then print "x is positive", else if x is lesser than 0 then print "x is negative", else if none of the conditions are true, then print "x is zero" which is in else.
Loop
In programming, loops are very useful and helpful to prevent any repetition of the codes and to simplify any problems. Let's say you want to print "Hello, world!" 10 times. What you might do is:
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
System.out.println("Hello, world!");
but we can do better than this.
while
So instead of rewriting the same code 10 times, we can
do:
int i = 0;
while(i<10) {
System.out.println("Hello, world!");
i++;
}
A while loop can be helpful for this kind of problems. So instead of rewriting the same code for a number of times and use multiple lines of code. So a while loop works the same as if condition the only difference is that while loop will repeatedly execute its block of code until the condition became false. In this example, we initialized a variable called i and set it to 0. Then we used while(i<10), which means while the value of i is lesser than 10. Inside of it is first, it will print Hello, world! and then increment the value of i. So every time the block of code is executed it will print Hello, world to the terminal window and increment the value of i until the value of i is lesser 10 became false.
do-while
Aside from while loop, there is also do-while loop, it is a variation of while loop and its syntax looks like this:
int i = 0;
do {
System.out.println("Hello, world!");
i++;
}
while(i<10);
In this example, we initiated a variable and set its value
to zero, inside the do, we have a block of code that prints "Hello,
world!" on the terminal window and increments the value of i. then there
is while with its condition inside. Basically, do-while loop
executes the block of code inside do at least once whether the
condition is true or false. If the condition is true, the block of code
will repeatedly executed until the condition will became false. In our
example, it will print "Hello, world" 10 since we are incrementing the
value of i for each loop until its value reaches 10 then stop the loop.
for
You may also find for loop helpful. for loop is quite different from while and do-while loops in terms of its syntax. Here is how a syntax looks like:
for (int i=0; i<10; i++) {
System.out.println("Hello, world!");
}
Comments
Post a Comment