JAVA & Object Oriented Programming For Beginners

Farhan Tanvir
Code With Farhan
Published in
19 min readDec 28, 2022

Java is one of the most used programming languages. It is an Object Oriented Programming language (OOP). It is used to build native android apps, desktop apps, backend of web apps, microservices and more.

First Program In Java

First install Java on your system and create a file named “hello.java” and open it with any text editor. Then, write the following code snippets to hello.java file and save it.

public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

To run the program, open the terminal in the same directory on Linux & mac or power shell on windows.

To compile, run

javac hello.java

This command will create a hello.class file. To execute, run

java hello

The output :

Hello World

When you compile a java code, the java compiler converts the code into a machine readable code. Which is the generated file hello.class. This class file can be executed by JRE. Let’s dive into each part of the first program in Java.

A Closer Look at the First Java Program

The code starts with the line

public class Main {

This line uses the keyword class to declare a class in java. Class is the blueprint of an object. We will discuss more about classes later. Here we have declared the Main class. We used the keyword “public” before declaring the Main class. It means the class Main is visible everywhere. In Java, these types of keywords are known as “Access Modifier”. We will explain about different types of access modifiers in Java later.

The next line of the code is :

public static void main(String[] args) {

This line declares the main() method. All java programs begin by running the main() method. We will discuss java methods later but in short, a method takes one or more variables or values as parameters and does some tasks. A method returns a value after completing its tasks. The void keyword before the main() method says that the main() function (or method) will not return anything after completion. We use the static keyword in Java for declaring any static variable and method. The main benefit of using a static method is that it allows the main() method to be called without creating an object of the Main class. The main() method takes arrays of arguments as parameters. Any parameter passed in the command line will be received by the main() method as string.

The next line of the code :

System.out.println(“Hello World”);

Here, System.out.println() is a method which is used to print in the console. Here, System.out.println() method takes the string “Hello World” as a parameter and it prints “Hello World” in the console when executed.

The remaining two closing curly braces complete the program. This was a simple program. Now, let’s dive into the basics of Java.

Variable

Variable is used to store any data in a program. A variable must have a certain data type. Let’s see another short program in Java

public class Main {
public static void main(String[] args) {
int num;
num = 10;
System.out.println(num);
}
}

If you run this program, you will see the output :

10

In line 3, a variable named num is declared. The keyword int means, num is an integer, that means this variable will be used to store any integer value. In the next line,

num = 10;

assigns to num the value 10. In the next line we print the variable in the console and it prints 10 in the console.

If you change the line 4 to

num = 10.45;

And then try to compile the program, the compiler will give you an compilation error:

Main.java:4: error: incompatible types: possible lossy conversion from double to int
num = 10.45;
^
1 error

10.45 is not an integer. So, java cannot store a floating point number in an integer. Integer is a data type used by Java. In the next section, we will discuss every other data type used in Java.

Primitive Data Types

Java defines 8 primitive data types: int, long, byte, short, double, float, char, boolean

  1. int is a signed 32 bit integer type data. It has a range from –2,147,483,648 to 2,147,483,647
  2. long is a signed 64 bit type integer. It has range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  3. short is a signed 16 bit type integer. It has a range from -32,768 to 32,767
  4. byte is a signed 8 bit type integer. It has ha range from -128 to 127
  5. float stores real numbers. It is a 32 bit type.
  6. double stores real numbers. It is a 64 bit type.
  7. char data type is used to store characters. It is a 16 bit data type. Java char is different from C/C++. Java stores unicode characters in char type which requires 16 bits.
  8. boolean type stores true or false. It is a 1 bit data type.

Non Primitive Data Types

Non primitive data types are String, Classes, Array, List, Map etc.

Java Strings

String data type is used to store text data. Check the following code snippet:

String mystring = "Hello";
System.out.println(mystring);

This will print “Hello” to the console. Here, mystring is a String type variable. You can concat two or more string by adding them with “+” operator:

String greeting = "Hello";
String name = "Bob";
String mystring = greeting +", "+ name;
System.out.println(mystring);

Output : Hello, Bob

To find the length of a String, use the method length(). For example :

String mystring = "Hello World";
System.out.println(mystring.length());

Output : 11

Operator

Operators perform operations on variables and values. For example + is an arithmetic operator, which operates on two numeric type data like int or double and adds those two numbers.

int sum1 = 25 + 40; // 65 (25 + 40)
int sum2 = sum1 + 30; // 95 (65 + 30)
int sum3 = sum1 + sum2; // 160 (65 + 95)

Arithmetic Operators

Comparison Operators

Comparison operators compare two variables and return a boolean value true or false.

Logical Operators

Logical operators work on two boolean type data and return a boolean value true or false. Consider the following code :

public static void main(String[] args) {
int x = 13;
boolean b1 = 10 > 5; // true
boolean b2 = x == 5; // false
boolean b3 = b1 && b2; // false
System.out.println(b3); // prints “false” in console
}

The 3rd & 4th lines use comparison operators to compare two numeric values and store them in boolean variables. b1 and b2 stores true and false. The 5th line compares these two boolean variables with a logical operator && . This operator checks if both are true. If both of the boolean variables are true, then && operator returns true otherwise false. && is called the Logical AND operator. Now check another code snippet :

       int x = 13;
boolean b1 = 10 > 5; // true
boolean b2 = x == 5; // false
boolean b3 = b1 || b2; // true
System.out.println(b3); // prints “true” in console

|| is the Logical OR operator. It works on two boolean variables and returns true if any of them is true otherwise false.

The last logical operator is Logical Not operator (!). It works on a single boolean variable and reverses the value. It returns true if the variable is false.

       boolean b1 = 10 > 5; // true
boolean b2 = !b1; // false
System.out.println(b2); // prints “false” in console

If Statement

If is used for executing a block of codes when a condition is met. Usage :

 if(condition1){
// statements
}
if(condition2){
// statements
}

Check the following code :

   public static void main(String[] args) {
int x = 100;
if(x > 100){
System.out.println("x is greater than 100");
}
if(x < 100){
System.out.println("x is less than 100");
}
if(x == 100){
System.out.println("x is equal to 100");
}
}

The 3rd line checks if the variable x is greater than 100. As this condition is not true it skips the corresponding statements inside the block. Same thing happens in the 6th line, as x is not less than 100. In the 9th line, the condition is true and it executes the corresponding statement.

Output : x is equal to 100

Else If Statement

else if” statement is used with “if” statement. Then The “else if” condition is checked if the previous if condition is not met. Usage :

 if(condition_1){
// statements
}
else if(condition_2){
// statements
}
else if(condition_3){
// statements
}
...
else if(condition_n){
// statements
}

Check the following code :

   public static void main(String[] args) {
int x = 150;
if(x > 200){
System.out.println("x is greater than 200");
}
else if(x < 200){
System.out.println("x is less than 200");
}
else if(x == 200){
System.out.println("x is equal to 200");
}
}

In the 3rd line the if condition is not true. So it skips the corresponding code block. In line 6, as x is not less than 100. In the 9th line, it finds a true condition and executes the code blocks. Then it skips all remaining else if statements. Once “else if” finds a true condition, it skips all the remaining else if statements in the chain.

Output : x is less than 200

Else Statement

else” statement is used at the end of an “if” and “else if” chain. If none of the previous conditions are met, then the else statement is executed. Usage :

Check the following code :

   public static void main(String[] args) {
int marks = 25;
if(marks > 80){
System.out.println("A+");
}
else if(marks > 70){
System.out.println("A");
}
else if(marks > 60){
System.out.println("A-");
}
else{
System.out.println("Fail");
}
}

In this code, all the if and else if conditions are false. Hence, the else statement is executed.

Output : Fail

For Loop

Loop is used for executing a block of codes as long as a condition is met. Usage :

for(statement 1; statement 2; statement 3) {
// code blocks
}

First the statement 1 is executed, then it executes statement 2. Statement 2 is a boolean condition. If the condition is met, then the code blocks are executed. Then statement 3 is executed after the execution of all code blocks. Then the loop begins from statement 2. Statement 1 is executed only once, at the beginning of the for loop. The order of execution is :

statement 1 ➡ statement 2 ➡ code blocks ➡ statement 3 ➡ statement 2 . . .

The loop breaks when it finds the condition at statement 2 is false. Consider the following code :

   public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println(i);
}
}

statement 1 : int i = 0

statement 2 : i < 5

statement 3 : i++

Code block : System.out.println(i);

First, an integer variable is declared and 0 is assigned to it. Then in statement 2, it checks if the value of i is less than 5. As this condition is true, the code block is executed. In this case it prints the value of the variable i in the console. Then statement 3 is executed. In this case, it increments the value by 1. Then it continues from statement 2. It checks if the condition is met and then prints the new value of i in the console. At each cycle, the value of i is incremented by 1. When i is not less than 5, the loop breaks.

Output :

0
1
2
3
4

While Loop

While loop is another type of loop used by JAVA. Syntax :

while(condition) {
// code blocks
}

As long as the condition is true, the code blocks are executed. Example :

 int i = 0
while(i < 5) {
System.out.println(i);
i++
}

At each cycle, it checks if the value of i is less than 5. If true, then it prints the value of i to the console and then increments its value by 1. The output of the while loop is the same as the previous for loop. That means, it will print from 0 to 5 in the console.

Break Statement

Break statement is used in a for/while loop. When a break statement is executed, it immediately breaks the loop. Example :

int i = 0
while(true) {
System.out.println(i);
i++;
if(i == 5){
break;
}
}

When the value of i is equal to 5, it breaks the loop.

Methods

Methods are used to perform a task and return a value or nothing. They may take values or variables as parameters. Syntax of a method is :

return_type method_name (parameter_1, parameter_2, . . . parameter_n){
// code blocks
}

return_type is the type of value which will be returned by the method after execution. If it is void, then the method will not return anything.

method_name is the name of the method.

parameter_1 is a parameter accepted by the method. A method can take multiple parameters.

Check the following example :

public class Main {

static int add(int num1, int num2){
int result = num1 + num2;
return result;
}
public static void main(String[] args) {
int x;
x = add(10,20);
System.out.println(x);
}
}

Output : 30

We have declared a method at the 2nd line. The static keyword means, the method is a static method. In this method, the return_type is int. It takes two integers num1 and num2 as parameters. It then adds these two numbers and puts the result in an integer variable result. It then returns the value of the variable result.This method is called at line no 8 :

x = add(10,20);

This line calls the add() method with two parameters 10 & 20. The add() method then adds these two numbers and returns the result. When the method returns, at line 8, the value returned by the add() method is stored in the variable x. Then it prints the value of x to the console.

A method may have a return type void. In that case, it will not return anything. See the following code :

public class Main {

static void sayHi(){
System.out.println("Hi");
}
public static void main(String[] args) {
sayHi();
}
}

Output :

Hi

We declared a method sayHi() with return type void. The sayHi() method doesn’t return anything after completion. When called, this method prints “Hi” to the console.

From the beginning we used System.out.println(“Hi”) to print anything on the console. This is a Java method which takes a String or other data type as a parameter and prints it in the console. It has a void return type. That means it returns nothing.

Now we have learned about all the basics of java. We will dive into the Object Oriented Programming (OOP) part.

Object Oriented Programming (OOP)

In procedural programming we use methods or procedures that operate on data. In object oriented programming we create objects that contain both data and method. Object oriented programming (OOP) languages have a number of advantages over procedural programming languages. It creates well structured clean codes which is essential for large and complex projects.

Java Classes & Objects

Class is a blueprint of objects. Consider class as an abstract architecture and objects are instances of class. Consider the following figure :

In this figure, Car is a class. A car has a model name, price, color and build year.This are called the properties of a class. Then we introduced three objects of the Car. The first one has an orange color, 10K price, build year 2015 and a model name : AAA. Each of the three car objects has the same 4 properties but with different values. So, objects are real physical things and classes are their blueprint. Class defines which properties its objects will have.

Consider another example. We have a class named Human. Each human has some common properties. They have height, weight, age, color etc. These are the properties of a “Human” class. Then each person : Adam, Eve, Seth, Bob and you are an object of the “Human” class.

Now let’s see how we declare classes in Java. Syntax of a class is :

   class ClassName{
public property_1;
public property_2;
. . .
public property_n;

public method_1(){
// code blocks
}
public method_2(){
// code blocks
}
. . .
public method_n(){
// code blocks
}
}

Consider the following code :

class Human{
public double height;
public double age;
public double weight;
public String name;

public void showHuman(){
System.out.println("height: " + height);
System.out.println("age: " + age);
System.out.println("weight: " + weight);
System.out.println("name: " + name);
}
}

public class Main {

public static void main(String[] args) {
Human bob = new Human();
Human alice = new Human();
}
}

First, we declare a class Human. Then from line 2 to 5, we declare four properties of our Human class. The public keyword means these properties will be accessible outside the class. Each property is a variable with a data type. In this case height, weight and age are double type variables and name is String type. Then There is a method named showHuman(). This method describes all properties of a human. Now consider the main() method. We created two objects for our Human class.

Human bob = new Human();

This line creates a new Human object named bob. By the same way it declares another object named alice. Each of these objects has 4 properties : height, age, weight & name. Now write the following code blocks in the main method :

       Human bob = new Human();
bob.height = 5.5;
bob.weight = 65;
bob.age = 33;
bob.name = "Bob";
System.out.print(bob.name);
System.out.print(bob.age);

In the first line we create an object named bob. In the 2nd line :

bob.height = 5.5;

we set the height property of the object bob to 5.5, science it is a double type variable. We can access any property of an object with the dot(.) operator. By the same way we set the other three properties of the bob object. In ling 6 & 7, we printed the name and height of bob to the console. Output :

Bob
33

Now, let’s remove the last two line and replace it with :

bob.showHuman();

We call the showHuman() method of the object bob and it will execute the code blocks inside the showHuman() declared in the Human class.

Output :

height: 5.5
age: 33.0
weight: 65.0
name: Bob

Now, consider another example :

class Car{
private String model;
private String color;
}

public class Main {

public static void main(String[] args) {
Car car = new Car();
car.model = "Toyota";
car.color = "red";
System.out.println(car.model);

}
}

In this example we created a class named car which has two properties: model & color. Instead of the public keyword, we introduced a new keyword called private. If you try to compile the program, you will get a compilation error :

Main.java:10: error: model has private access in Car
car.model = "Toyota";
^

The error says that the property model is declared with the private keyword. So, you cannot access the property like this :

car.model = “Toyota”;

When a property has the private keyword, it cannot access outside the class with a dot(.) operator. It is only accessible inside the class. So, this gave you the compilation error. To solve this issue, we will write 2 methods for each property inside the class : getter and setter method.

class Car{
private String model;
private String color;

public String getModel(){
return model;
}
public void setModel(String modelName){
model = modelName;
}
public String getColor(){
return color;
}
public void setColor(String colorName){
color = colorName;
}
}

We declared four new methods : getModel(), setModel(), getColor() & setColor(). The getModel() method returns the current value of the model property and the setModel() takes a String parameter and sets it to the model property. Science private keywords are accessible inside the class, these methods can set and get the values of the properties. Now rewrite the main method :

public static void main(String[] args) {
Car car = new Car();
car.setModel("Toyota");
System.out.println(car.getModel());

}

We call the setModel() method of the car object with and pass a String “Toyota” as a parameter. This method will set “Toyota” to the model property. In the next line we get the current value of the model by calling getModel() property of the car object. This will print the value of the model to the console. Output :

Toyota

There is another (and conventional) way of writing a setter method. We can rewrite the setModel() method as :

public void setModel(String model){
this.model = model;
}

We changed the method’s parameter name to “model” which is the same name we used for the property. To avoid confusion for the compiler we used the “this” keyword. The “this” keyword in Java always refers to the current object. So, “this.model” refers to the property “model” of the current object. So, the statement “this.model = model” sets the parameter of the setModel() method “model” to the property “model” of the object. By the same way we can rewrite the setColor method :

public void setColor(String color){
this.color = color;
}

Constructor

Constructor is a method which is called when an object is created. When we create an object like :

Car car = new Car();

The Car() method is the constructor which creates the car object. It is the default constructor of any class. We can create our own constructor :

class Car{
private String model;
private String color;

public Car(String model, String color){
this.model = model;
this.color = color;
}
public String getModel(){
return model;
}
// . . . other methods
}

We defined a new constructor Car(String model, String color). A constructor method always has the same name as the class and it doesn’t have a return type. Now, let’s use our new constructor in the main() method :

public static void main(String[] args) {
Car car = new Car("Toyota", "Red");
System.out.println(car.getModel()); // prints "Toyota" in the console

}

We called our custom constructor instead of the default one. This constructor takes two String data as parameters and sets these parameters to the properties : model & color. This way we can instantiate the properties when the object is created. We can create multiple object with the new constructor :

Car car1 = new Car("Toyota", "Red");
Car car2 = new Car("Ford", "Black");
System.out.println(car1.getModel()); // prints "Toyota" in the console
System.out.println(car2.getModel()); // prints "Ford" in the console

Inheritance In Java

In Java, inheritance is obtaining properties and methods from a parent class. One class can acquire properties and methods from another class. It is like a child-parent relationship. Let’s see an example. Consider the following class :

class Shape{
public double area;
public double perimeter;
}

class Triangle extends Shape{
// area, perimeter
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3){
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
this.perimeter = side1 + side2 + side3;
this.area = side1 * side2 * side3;
}

public double getPerimeter(){
return this.perimeter;
}
}

class Circle extends Shape{
// area, perimeter
private double radius;

public Circle(double radius){
this.radius = radius;
this.perimeter = 2 * Math.PI * radius;
this.area = 2 * Math.PI * radius * radius;
}
}

We first declared a class named Shape. It has two properties : area & perimeter. The second class Triangle “extends” the Shape class. When a child class “extends” a parent class, the child class gets all properties and methods of the parent class. In this case, the Triangle class has two properties : area & perimeter though these two properties are not declared in the Triangle class. In the constructor of Triangle class, we assign these two properties :

this.perimeter = side1 + side2 + side3;

this.area = side1 * side2 * side3;

We can access these two properties with the “this” keyword from the triangle class. I know the formula used here to calculate the area of a triangle is wrong. But for the sake of simplicity let’s assume, it is real. We did the same thing in the Circle class. Its constructor takes the radius as parameter and calculates the perimeter & area :

this.perimeter = 2 * Math.PI * radius;

this.area = 2 * Math.PI * radius * radius;

We can access these two properties with getter methods. Add the following two methods in both Triangle & Circle classes :

   public double getPerimeter(){
return this.perimeter;
}
public double getArea(){
return this.area;
}

Then rewrite the main method like this :

   public static void main(String[] args) {
Triangle triangle = new Triangle(2, 3, 4.5);
System.out.println(triangle.getPerimeter());
Circle circle = new Circle(10);
System.out.println(circle.getPerimeter());
}

Output :

9.5
62.83185307179586

In the Shape class both area & perimeter is declared as public properties. That means, they are accessible from everywhere outside the class. If we change them into private properties & try to run the program again, we will get an error. First change the Shape class :

class Shape{
private double area;
private double perimeter;
}

Then run the code again. Output :

Main.java:15: error: perimeter has private access in Shape
this.perimeter = side1 + side2 + side3;
^
Main.java:16: error: area has private access in Shape
this.area = side1 * side2 * side3;
^
. . .

The output says that “perimeter” is a private property. So, you cannot access this property from a child class. Now, let’s use another keyword “protected” :

class Shape{
protected double area;
protected double perimeter;
}

Now the program can be compiled & run without an error. But what does this new keyword do? When a property is “protected” its value can be accessed everywhere in the same package. In Java a package is used to group a set of similar classes. Packages are used in large & complex programs to organize the codes better.

Function Overloading

Let’s consider the following example :

class A{
public void greet(){
System.out.println("Good Morning");
}
public void greet(String message){
System.out.println(message);
}
public void greet(String message, String person){
System.out.println(message + ", "+person);
}
}
public class Main {

public static void main(String[] args) {
A obj = new A();
obj.greet();
obj.greet("Hello");
obj.greet("Hello", "Bob");

}
}

Class A has three methods with the same name “greet”. The first method takes no parameter, the second one takes a single String parameter and the last one takes two String parameters. This way of declaring multiple methods with the same name is called function overloading in Java. When we call the greet() method, Java will call the method depending on the parameters we passed. For example, in the main() method, first we called the greet() method with no parameter :

obj.greet();

Java will call the first definition of greet() method with no parameter. When we call great() with two string parameters, Java will call the third definition of greet() method with two parameters. The output of the program will be :

Good Morning
Hello
Hello, Bob

We cannot overload a method with the same types of parameters. For example:

   public void greet(String message, String person){
System.out.println(message + ", "+person);
}
public void greet(String message2, String person2){
System.out.println("Hello, "+ person2 + ". "+message2);
}

This will result in a compilation error. Because if we try to call like this :

obj.greet(“Hello”, “Bob”);

Java will not understand which definition of greet() tp call.

Function Overriding

When a child class declares a method with the same name and parameter as the parent class , then it is called function overriding. For example :

class Chef{
public void cook(){
System.out.println("Cooks vegetable");
}
}

class ItalianChef extends Chef{
public void cook(){
System.out.println("Cooks pasta");
}
}
public class Main {

public static void main(String[] args) {
ItalianChef italianChef = new ItalianChef();
italianChef.cook();
}
}

In this example, ItalianChef class extends Chef class. So, it acquires the cook() method from its parent class. But it overrides the method with a new definition. Output :

Cooks pasta

If we remove the overridden method from ItalianChef class and run the code again, the output will be:

Cooks vegetable

That means, it will use its parent class definition of the method. So, when a child class overrides a method from the parent class, then the objects from the child class will always call the overridden method.

Now, we have completed all the basics and OOP parts of the Java language.

--

--