Java for beginners
Java is a programming language that helps us to write commands (code) to a computer to perform a specific task.
Like many programming languages, Java is also a programming language, it is also used as a guideline and instruct to computers.
Other languages include C, C++, Python and many more!
You know what? A computer is a dumb machine. A computer is a dumb machine. The saying is that no one is more intelligent than a computer, no one is as foolish as a computer
It should be instructed how to perform a particular task and to achieve this we use a programming language.
Java is one such language the computer understands.
That’s what java is…a mediator between you and your computer.
So if you know Java, you will be able to teach your computer to execute tasks!
Where is Java used?
Let’s see some specific scenarios where Java is being used, the list is endless…
Java is used to command and instruct robots to perform a particular task. In this case the robot has an operating system (eg Windows, Android, Ubuntu), as does a computer and mobile, which allows it to instruct.
Java is used to create Android apps which you use on daily basis.
You may not know it, but almost every application for smartphones running on Android use Java.
Java is also used to create and build many desktop applications that are used on a daily basis.
How java works
Now, you must be wondering how the commands which we write in english are understood by the computer and how is it able to act accordingly?
Let me try to explain this in four simple steps.
- First, we write a list of commands in the English language, creating a Java program.
- Then, the program is converted into an intermediate version, called bytecode. This version is not readable by humans anymore.
- The bytecode is then read by special software called a Java Interpreter, which translates it to a machine-friendly language.
- The computer reads the translated code and performs the tasks requested.
So far you have learned
- What is Java? A programming language, used to give instructions to a computer.
- Where is Java used? Many different fields, like mobile apps, desktop applications, even robotics!
- How does java work ? Yes! The four steps: write, convert, feed and perform š
What does computer programming mean?
A computer program serves to tell the computer when, where, and how to do it, for which the computer program uses a list of guidelines & instructions.
Everything a computer does is done by using a computer program.
A computer program is written in a programming language like C, C++, Java, etc.
Writing your first program
Letās start with the first program that students create. Itās called Hello World. It tells the computer to print āHello Worldā on screen.
But before doing that, let’s see if you know some of the commonly used special characters in programming.
We need a way to display something on the screen right?
The command used to print some text on the screen is:
System.out.print
Note that Java is a case sensitive language, meaning that uppercase letters and lowercase letters are different for it
So S should be in capital and rest of the command in small case is mandatory.
Now, you must be wondering, how do we tell the computer to print some specific text on the screen?
So, to achieve this, you need open-close curved brackets just after the command, and put your text inside them
Something like this:
System.out.print(Hello World)
The text you write inside the open-close curved brackets is the one that is printed on the screen.
This is the way to differentiate between the command and the text to print.
So, if you are a computer, you will read the previous line as:
Ok, the command is āSystem.out.printā.
I need to print something on the screen.
But what should i print?
Oh wait! There is some text inside the curved brackets.
Yes! I must print this text! Bingo!
Oops! We forgot one thing here.
In order to print any text, the text needs to be enclosed in double quotes.
That’s the actual way to print words on the screen.
Letās continue!
Oh! There is one last thing remaining.
In Java, we put the semicolon after every command.
Just like we use the full stop after every statement in English, we use the semicolon to end every command in Java.
So the final command will look something like this:
System.out.print(“Hello World”);
Storing a value
Imagine a kitchen shelf full of food items. Each food item is stored in a beautifully well-organized and well labeled container.
That would be great for mom to get what she wants quickly for preparing delicious food, whenever you yell āMom, I am hungry!!!ā š
Now, letās say you need to store something in your computer shelf. This shelf is also called as memory. With this method, you can always return to the shelf when you need things quickly.
For this, you will need a container, just like the one you had in the kitchen shelf.
In programming, this storage container is called variable. Hope you remember the name āVariableā, because we will use this name a lot.
We have to provide variable with an unique name, so that it comes to our service whenever we are looking for it.
Along with that, we also need to mention the type of value it will contain, eg: words, numbers, etc.
In this way Java will know how much space to reserve for your variable, as some types require more space than others.
In order to put values into a variable, we use the equal (=) sign, like we do in maths. And everything that starts has an end. In programming, semicolon(;) is used to end a command.
For example:
int score = 100;
In this case our variable is called score, which has a value of 100 and has an int type, short for integer. The int type tells the computer that the variable can only contain whole numbers.
Storing words
Let’s see how to create a variable to store words, like your name.
For this, we need to tell the computer that we would like to store text in the variable.
To do that, we use the keyword String before the variable name.
Something like this:
String name = “James”;
Again, note that the text is written in quotes to tell Java that it has to be considered as a string.
Storing true or false
Sometimes we require a special kind of value to be stored, mostly for decision making.
The values are true and false, also called boolean values.
To store such values we use the keyword boolean.
Something like this:
boolean isCorrect = true;
Storing numbers
Let’s see how to create a variable to store whole numbers.
For this, we need to tell computer that the value we would like to store is an integer (whole number).
We do this by using the keyword int before the variable name.
Something like this:
int score = 100; //creation and assigning the value.
Basic math operation
Now that you know how to create a variable which stores numbers, let’s start doing some basic math with it.
First let’s create a variable:
int a ;
Let’s assign a value to it:
a = 25;
Similarly, let’s create one more variable and assign a value to it:
int b = 70;
Now, lets create a third variable c to store the result of our calculation:
int c;
Finally, store the sum of variable a and variable b in the new variable c.
c = a+b;
above code will save value of a+b in the variable c.
So in this topic you have learned many things, but the most important ones are:
- Storing data in a computer program.
- Printing the stored values using the print command.
- Different types of variables: int, string, boolean.
- Doing basic maths operations on numbers and printing them.
What is decision making?
In your life, you have taken numerous decisions, like :
To select a subject between maths and biology.
To go play football with friends or not,
and of course, to continue and finish this Java course š
All of these decisions are based on numerous criteria, which lead to a big YES or NO.
Have you ever wondered, how does a computer take decisions?
Say, based on the value stored in a variable, you want the computer to do task 1 or task 2.
How would you do that with Java…? or is it really possible with Java?
Let’s check it out…
Of course! It is possible with Java!
If you couldnāt make the computer to take decisions, it wouldnāt be a very useful programming language š
There is a statement, called conditional statement, which help serve this purpose.
Let’s see…
if…else statement
The conditional statement is known as if…else statement.
There is a condition we supply to this statement, which has to be either true or false.
Based on this condition, our program divides into two branches:
- if block – do tasks when condition is true.
- else block – do tasks when condition is false.
Let’s divide the statement into 3 main chunks:
- condition
- if block
- else block
and see how can we write the if else statement.
let’s see how can we write a condition in the if…else statement
if(condition)
The āifā keyword tells the computer that whatās going to come is an if…else statement. Condition part indicates the condition that needs to be evaluated, surrounded with in curve brackets
Example
if(7>5)
if(4<=8)
Now, let’s check how do we write the if block:
Right after the if statement, we add the code we want to run when the condition is true, between curly brackets.
{
System.out.print(“The condition is true”);
}
The last remaining part of the if else statement is the else block.
else block is written starting with the else keyword, soon after the if block’s curly brackets have ended.
else {
System.out.print(“The condition is false”);
}
So, if we look at our code as a whole, it will look like this:
if(condition){
System.out.print(“The condition is true”);
} else{
System.out.print(“The condition is false”);
}
That’s cool and easy!!!
So, let’s just quickly summarize what we have learnt in this topic:
For condition based tasks, the computer uses the if else statement.
The if else statement consists of three parts:
- The condition block written inside the curved brackets, which will result in either true or false value.
- The if block, written inside the curly brackets, having statements to perform when the condition is true.
- The else block, written just after the if block, starting with the else keyword and the curly brackets, having statements to perform when the condition is false.
What is Repeating a task?
So, now you know how to make a computer take decisions based on instructions.
Now, let’s see another important aspect of programming, something for which the computers are known for…
You know what? At ntaugc.net, we have many tasks to do on a daily basis.
One such task is to test the app before releasing it to our users…This is most important!
Every time we do some similar set of tests before releasing the app and it’s monotonous.
Wish we could do this repeated task from some machine. Is this even possible?
Yes, it’s possible!!!
Yup, any task which needs to be repeated can be done by computers pretty fast and easily using programming.
So, if we need to perform A, B, C and D tasks for say 10 times, what are the possible ways to tell this to a computer?
Write down A,B,C,D 10 times and instruct the computer to perform it 10 times. We hate it this way!
Like we used to learn new words when we were kids, writing it down several times.
But neither are we kids now nor is the computer.
Let’s see if we have a better option.
This is a much better way…
In programming, we have something called a loop, which helps us to carry out tasks repeatedly, without the need of writing the same instructions several times.
Similar to the if else statement, a loop is composed of a loop keyword, a condition to be checked and a block of code that is executed a number of times
Something just like this..
loop(when_to_stop){
test A;
test B;
test C;
test D;
}
Loops in programming
Letās now see how to create a loop in detail
loop(when_to_stop)
{
test A;
test B;
test C;
test D;
}
In the above set of instructions, there are three main things to notice:
- loop: this is the keyword which will tells the computer that we want to do a repeated task.
- when_to_stop: this is the condition which will decide when to stop the loop.
- loop block: written inside open-close curly brackets, the tasks that we want to repeat.
Types of Loops
In Java, we have three main types of loops:
- while loop
- do while loop
- for loop
Let’s check these one by one.
While loop
Sometimes, we don’t know when to stop our loop, like in the above gif.
But we know the condition, where we need to stop.
So, for such kind of repeated tasks, we use the while loop.
Let’s see how it looks:
while(contition_to_stop){
instructions…
}
let’s break it down…
while loop has 3 main components
- while: a loop keyword to tell computer it’s a while loop command.
- condition: written inside open-close curved brackets, decides when to stop the loop.
- instruction block: written inside open-close curly brackets, it contains the instructions to be repeated.
did you notice the two lines of code, which we never discussed before?
int i = 1;
i = i+1;
The first line tells the starting point of our loop, in our case an integer with value of 1.
The second line helps us to proceed with the loop, incrementing the value of i by 1 each time.
Both these instructions are important for a loop to work properly.
Some scenarios of looping requires a task to be done at least once.
Thatās when you use a do while loop.
To read a file you know that you have to always read the first line in it, but then you will have to loop until you finish it
This is how a do while loop looks:
do{
instructions…
} while(condition_to_stop);
Let’s see in detail.
ādoā is a keyword for the computer to recognize. It tells it that the next block of code is going to be a do while loop.
This is followed by open-close curly brackets for writing instructions to repeat…
Then a while keyword is usedfollowed by a condition to stop the loop, same as in while loop; written inside curved brackets…
Finally a semicolon to end things up.
For Loop
Sometimes, you need to repeat a task several times,and you know the number of times it should be repeated.
For example, you know that in a week you need to set up an alarm to wake you up at 6 AM daily.
So you know that the alarm task has to be repeated 7 times…
Such type of repetitive tasks are done in Java using the for loop.
This is how a for loop looks:
for(start_value;condition_stop;proceed_code){
instructions to repeat in the loop
}
Example :
for(int i = 1;i<=10;i++){
System.out.println(“Hello World”);
}
The above code will print Hello World 10 times.
Let’s break down the whole command:
for is the command telling the computer about the type of loop.
start_value will tell from where to start the loop, usually a number. Usually a variable is created in this section.
condition_stop will tell you when to stop the loop.
proceed_code will help in increasing/decreasing the start_value, so that we come close to the condition to stop the loop.
We write the above three things inside curved brackets, just after the for keyword, separated by a semicolon.
Then we write the instructions to execute after that, inside open-close curly brackets like the other loops.
To sum it up:
- Whenever we need to run the same set of instructions continuously, we use loops.
- A while loop is mainly used when we don’t know how many times the loop needs to be run.
- A do while loop is used when we want to run the loop at least once, irrespective of the condition.
- A for loop is used when we know how many times the loop needs to be executed.
The conditional statements and The loops.
You are almost there, few more steps to master the basic concepts.
Have you seen an egg storage tray, the one shown in the picture above?
The only purpose of the tray is to store eggs systematically without breaking them.
It has compartments to store multiple eggs at the same time.
So, one tray for multiple eggs, instead of having one for each, which sounds weird…right?
Similarly, what we have is a class full of students, almost 40 of them.
And we need to store their names in the computer using Java.
You definitely know how to do that…
create 40 String variables with name1, name2…till name40 and start storing values in them.
The above technique seems to be an obvious solution for this problem…but is there a better alternative?
Wish we had a tray like an egg tray, one tray to store multiple things of the same type.
Like one storage place which can store multiple values, of the same type, in a sequence, like a queue.
You know what, we have one such feature in programming!!!
Yes, you heard that right, it’s called an Array.
It seems interesting, let’s explore it…
An Array is a special form of storage, which stores multiple values of the same type.
The values are stored one after the other, like a queue, or a stack.
And we can access these values by using an index, starting with 0.
So the first value entered goes to the 0th position, next to the 1st position and so on.
Creating arrays
So, let’s see how do we create one:
For creating an array we need the following things:
- Type of values it will store.
- Name of the array.
- Maximum number of values it will store(a range).
Say, you need to create an array for storing numbers, and it can store up to 10 values.
The command will be as follows:
int numberArray[] = new int[10];
The first element, as with variables, is the type used
Followed by the name of the array,
Followed by a pair of square brackets. This is important because it distinguishes arrays from simple variables
an equal sign,
new, a java command
again the type of data,
and finally, the max size enclosed in open-close square brackets.
The semicolon at the end, as always.
You know what we can even break the previous code into two statements.
Something like this:
int numberArray[];
numberArray = new int[10];
This is to separate the creation(also called declaration) and setting the limit(initialisation), which is used in some cases.
The declaration step tells the machine that we will use a variable, but not at that moment. Initialization takes a declared variable and associates some value to it.
Now, that you know how to declare and initialise an array, let’s check how to store values in it.
As we have already discussed, array values are stored starting from index 0.
So, if you want to store a value at the first place in the array, the command will look something like this:
numberArray[0] = 100;
We are taking the array called numberArray, and putted the value 100 at position 0. Indexing is done inside square brackets.
Similarly, if you want to add another value at a different index:
numberArray[1] = 101;
So, you can keep on adding values to the various positions in the array, but you need to remember not to exit the maximum elements number
And if you exceed that, the computer has no place for your extra member, and it will refuse to follow instructions which you gave.
In programming, we call this as an error, which happens whenever we do something wrong.
Accessing the values
Now that you have created an array and started storing values into it, next thing that you need to learn is how to access those values.
Here you will face two scenarios:
- Accessing single member.
- Accessing multiple members.
Let’s see how to do that individually…
Accessing single member is quite straight forward.
Similarly to when you store values, for accessing you use the index of the element you want to access, enclosed in square brackets.
int num = numberArray[4];
the above command will give us the value stored in the 5th place of the array and store it in a new variable num, keep in mind that indexes start from 0!
So to get the count of total values stored in the above array, you will write:
int count = numberArray.length;
here numberArray is the name of the array, and the length is the command to get the length and dot is used to separate them both.
You must be wondering why have we discussed the length command, when we were about to see how to access multiple values of the array.
Two reasons:
- A good to know
- Because you canāt really access multiple values in a array, but you can use a loop and get each one individually!
Want to know how? let’s check…
We make use of for loop to access multiple values of an array.
Let’s say you need to print all the values in the array.
For that, we start with the first element in the array and go on till the last element in the array.
And we use a for loop to go from 0 to the last element.
Let’s check the code:
for(int i = 0;i< numberArray.length;i++){
System.out.println(numberArray[i]);
}
0 1 2 3 4 5 6 7 8 9
So we have learned how to work with arrays in this chapter
- An array stores multiple values of same type.
- This is how we create it:: int numberArray[] = new int[10];
- This is how we add values to it: numberArray[0] = 100;
- Accessing single element: int num = numberArray[4];
- Accessing multiple elements: for(int i = 0;i<numberArray.length;i++){ System.out.println(numberArray[i]); }
What is an input?
So here we are, the final chapter of Basic Java…
From variables, to if else, to loops, to arrays…
Learned a lot…
One last topic before we end things up…
Let’s do it then!
Imagine you are writing a program to find if the number is odd or even.
You wrote a program for that.
You would create a variable, assign some value to it(odd or even).
Then check if the number you have entered is odd or even using the āif elseā statement and print back the result.
Now say, you want to enter a number to check in the program while the program is running on your computer…
In real time…
So, it means you need to give input to the computer, which will then be stored in a variable and then that variable will be checked.
So how do we do this in Java?
Taking an input
So to achieve this, we need use Scanner command of Java.
Let’s see how this works:
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
In the 1st line, the command creates an object(sc) of the Scanner class.
Now, what the heck are classes and objects?
Easy, for now just think that it is something Java has created for us to use, and this is the way to use it…
Classes and Object will be covered in the coming chapters.
So using āscā we can get the input which is passed to the program.
But how?
Now, when we run a Java program, a window pops up, which has a black screen.
It’s called the ‘Console Window‘.
When the program is running, a cursor(_) will be blinking…
That is where we need to pass the input.
So the input passed is then stored into an āintā variable using a command of the Scanner class.
i.e sc.nextInt()
Post that it’s the same old process…which we follow to work on the variable and check if it’s an odd or even number.
Your code will look something like this:
int x;
System.out.println(“Enter an integer to check if it is odd or even “);
Scanner in = new Scanner(System.in);
x = in.nextInt();
if ( x % 2 == 0 )
System.out.println(“You entered an even number.”);
else
System.out.println(“You entered an odd number.”);
and once it is run, the output will look like this:
Enter an integer to check if it is odd or even 22 You entered an even number.
Similarly, you can take words as input using the Scanner class like this:
Scanner sc=new Scanner(System.in);
String name=sc.next();
So this was how we can take input from the user while the program is running and store it in a variable for further processing.
That was one of the easiest process, there are few other ways…
but the other ways are tricky, and we will learn them in our advanced courses…
But have you ever wondered how do we write the complete code required to print any text?
Let’s see how an actual program is built.
Rebuilding our first program
To build our first complete program, we need to know three basic building blocks:
- The class
- The main method
- The print statement
The class
The class is like our home, a place for anything and everything in its place.
In our case, the members who will perform the instructions will be inside the class.
A class looks somewhat like this:
class HelloWorld{
//hey computer, these are the members
Member1 – i do xyz task
Member2 – i do abc task
}
Inside the curly braces is where all the action happens.
The main method
Like all the tasks in our home is controlled by a head(mom or dad), here, in our case we have a main method where we will write all the instructions that we need to perform.
So, the main method(mom or dad) will run all the instructions(daily activities) which all are done within the class(home).
Sounds great! Doesnāt it?
main_method(){
//hey computer, do everything that the main command says
//…u better do it!!!
}
Again, inside the curly braces is where all the action happens.
The print statement
As we have learned, to print something using java, we need the below command(code):
System.out.print(“Hello World”);
The complete program
As we have a head in our home and the head is the one who runs the activities of the home with the help of other members.
Similarly, we too have created a program for the computer to understand and do our tasks, by using java.
So let’s check how the complete program looks like.
So let’s check how the complete program looks like.
class HelloWorld{
main_method(){
System.out.print(“Hello World”);
}
}
Hello World
As you already know by now, a class is a container which contains all the members that are used to write a program.
These members include variables and methods(we shall learn about methods later).
But the big question is: Why use a class?
Object Oriented Programming
Everything here is in the form of classes and objects.
OOP is a methodology in programming created to simplify things and Java follows this methodology.
What is an object?
In Object oriented programming, a class acts as a blueprint from which objects are created.
Consider the blueprint of a car. The blueprint consists of two tires and the car body.
From this blueprint, we can design any type of car(object) which has two tires and a body. The properties of each object can be different. Such as the color, shape, etc. but will keep the original properties of the blueprint (class).
In other words, a class defines all the aspects that will have to be kept the same (two tires, a car body), while objects are a real example of that class.
Thus, we can create infinite objects from a blueprint(i.e. class). But an object can have only one blueprint(class).
An interesting and simple concept. Isnāt it?
So, we have understood the need for classes and objects in java.
Now, let’s see how to use them in our program.
public class Car {
String color = “White”;
}
public class Test {
public static void main(String args[]) {
Car objectMercedes = new Car();
System.out.print(objectMercedes.color);
}
}
White
In the above program, Car is the class and objectMercedes is its object.
We also have a data member in the class called ācolorā which defines the color of the car.
The real āmainā
class Car
{
public static void main(String args[]){
…
}
}
Before you get scared of what you just saw, the main method is actually written that way, didn’t tell you this since before you get scared.
For now, just know that it’s done this way, you will understand more about each word used here as we move ahead in the course.
Explanation
public static void main(String args[])
{
Car objectMercedes = new Car();
System.out.print(objectMercedes.color);
}
Inside the main method, the first line shows how we create an object, it looks like the same way we declare an array, but in this case we are using the Car class as a type, not too bad!
Then we use the name of an object, along with the dot(.) which is called as an access operator.
The dot is used to access any of the members of that class.
This is how we use classes and objects in a program š
Great in this chapter, we have learned:
- What exactly is Object Oriented Programming
- What is a Class and its purpose
- What is an Object and its purpose
Tip
Letās learn about a few good practices in programming.
Although these are not mandatory, they keep your code neat and consistent:
- A class name should start with a capital case, eg: Car, GoodFamily, MyClass
- An object name should start with a small case and every first letter of the next word should be in the capital case, like objectMercedes, myObject, myFamily