Java OOP Interview Questions – Part 02

Hello guys,

I’m back with another article in our Java OOP Interview Questions article series. Today I’ll be discussing another 10 questions regarding the deadly diamond of death, UML relationship types, sorting, serialization, static blocks and many more. Without further ado, let’s get into the fun stuff.


11. Why doesn’t Java support multiple inheritance?

As you may already know, Java does not support a class to inherit from multiple superclasses. But languages like C++ and Python do support multiple inheritance.

The reason behind Java’s restriction is to avoid ambiguity or as some people like to say to avoid the deadly diamond of death. Let me explain the deadly diamond concept using this image.

Deadly Diamond of Death

Think of the following idea with the assumption that Java supports multiple inheritance.

Here we have classes B and C that inherits from class A and then we have class D inherits both B and C. If A has a method called run(), and both B and C have overridden it, what method is D going to inherit from? Class B’s run() method or class C’s method?

This is the reason why Java does not provide the ability to inherit from multiple classes.

12. Explain UML Relationships: Directed Association, Aggregation, Composition, Generalization

  1. Directed Association

Directed Association helps to depict the elements that are associated. These are weak relationships

A Car uses A Garage

  1. Aggregation

This is also a type of association. The difference here is that the associated part is crucial for the other element. But still, this also is considered as a weak relationship

A Car needs Tires. But a Tire doesn’t need a Car

  1. Composition

Composition is a strong relationship.

A House is composed of Stones

These two are tightly bonded together because if we remove stones, there won’t be a structure called a house as well.

  1. Generalization

These are the relationships that depict inheritance.

13. What is the difference between Comparable and Comparator in Java?

These are two interfaces that Java provides to sort objects.

When we are using the Comparable interface (from java.lang package), we can go on the following process.

We need to implement Comparable interface for the Entity class. Then we need to implement the compareTo() method in the way we want to get the objects sorted. After that, we just need to call Collections.sort() and pass object list we want to get sorted.

The process that we need to do when using the Comparator (from java.util package) interface is a bit different.

Here we need to create a separate class that implements the Comparator interface. Then inside that class, we need to implement the compare() method to sort out data. And then when we are calling Collections.sort(), we need to pass the comparator class as the second parameter and Java will handle the rest.

The main difference is that when using Comparable interface, we can only create a single sorting sequence. But with Comparator interface, we can sort as much sorting sequences as we need.

In addition, we have to modify the entity class if we are going to implement the Comparable interface.

14. What is Serialization in Java?

This guy can’t read your data directly now 😪

Serialization in Java is the process of writing data of an object to a byte stream.

We can use the Serializable interface in Java to achieve this feat. Serializable is a marker interface which means that it doesn’t have any methods or variables. It is only used to mark the entity classes so that the compiler knows that he needs to get ready to serialize that particular entity class.

Here is a simple code snippet on how to serialize an object in Java.

Student Class

package serialization;

import java.io.Serializable;

public class Student implements Serializable {

    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Main Class

package serialization;

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {

        Student student = new Student("Thisura", 22);

        FileOutputStream fileOutputStream = new FileOutputStream("thisura.txt");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(student);
        outputStream.flush();
        outputStream.close();
    }
}

When we run the code, a text file called thisura.txt gets created in directory and the object gets stored in the file as a byte stream.

We can deserialize using the ObjectInputStream  and FileInputStream.

15. When should we use static methods and variables in Java?

We should declare a variable as static when we are sharing data

We should declare methods as static when we are using them as utility methods

16. Does a constructor return a value?

Yes, it returns the current class instance

17. What are the restrictions we have to face when using static methods?

Static methods can’t use non-static variables or methods

this and super keywords can’t be used in static methods

There is no need to create an object of the class to invoke a static method

static methods can’t be overridden in subclasses

18. Why is the main method in Java static?

The main method in Java needs to be declared as a static method so that the compiler does not have to create an object before calling it.

Since it is from the main method that the program start, the main method should always be static so that the compiler can call it right away.

19. When do we use static blocks?

We use static blocks to initialize static variables.

This block of code gets executed once the class is loaded into the memory. A class can have multiple static blocks. Here is a code snippet to explain it quickly.

    private String name;
    private int age;
    static String school;

    static {
        school = "Westminster";
    }

Before Java 7, it was possible to even execute a program without a main method. That is by using static blocks. Since the static block is executed once the class is loaded to the memory, we can write whatever we want inside the static method and run.

If we try to run the main method without the static keyword, the following error occurs.

Error: Main method is not static in class abstraction.Main, please define the main method as:
   public static void main(String[] args)

20. When should we use this and super keywords in Java?

this keyword is used to access a certain method or variable of the current object. This is commonly used to get rid of the confusion between class variables and parameters inside constructors.

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

We can just create the constructor like the below code and could get rid of this keyword.

    public Student(String myName, int myAge) {
        name = myName;
        age = myAge;
    }

We use super keyword when we want to access variables or methods of the superclass. In addition, we can call superclass constructor by writing super().

Another fun fact about these two keywords is that, we can’t call super() and this() in the same constructor since both methods must be the first line of code in the constructor.


That is it for this article. Hope you guys learned something valuable. If you have any doubts, please drop a comment down below, I’ll try to answer it. See you soon 😎

Java OOP Interview Questions – Part 01

Hello coders,

I am back with a new article series. In this series, I am going to focus on the interview questions you might have to face as a Java developer. These questions go over the basic concepts in Java and explain how exactly everything works so you could nail your interview.

I am going to try and explain each answer fully and attach a piece of code to help to grasp the concept easily. Let’s get into it.


1. What is an object in Java?

An object in Java is an instance of a class. It is something tangible that we can apprehend intellectually.

Java classes are like blueprints for creating objects. For example, Dog is a class where Oscar is an object created from that class.

every object inherits the methods and attributes of their classes. A constructor is used to create objects.

Dog oscar = new Dog();
Photo by Jamie Street on Unsplash

2. Why was OOP (Object Oriented Programming) introduced?

As the name suggests, this concept is built around objects.

In Object-Oriented Programming, we create objects that hold methods and attributes. The main reason to introduce OOP was that OOP helps us to implement solutions for everyday coding needs. Hiding data from the user, the ability to reuse the code, the ability to implement inheritance are some examples.

With the reusability of the code, OOP makes the code easier to maintain. OOP helps to make the design of the code simpler and structured. This paves the way for easier troubleshooting.

3. What is the difference between Array and ArrayList?

The main difference is that Array’s have a fixed size, while ArrayLists can shrink or expand accordingly. The length of the array needs to be defined once it is being initialized. If we try to store more elements than the length of an Array, the compiler throws an ArrayIndexOutOfBoundsException.

Primitive data types like int, double can’t be stored in ArrayLists. ArrayLists store the Wrapper classes or Objects. Arrays can be multidimensional, where ArrayLists can only be single-dimensional.

Arrays should be used when we know how many elements are there. If the number of elements is not known, the better option would be using ArrayLists since it can adjust automatically.

4. What is Polymorphism in Java?

Polymorphism is one of the core concepts that are there in object-oriented programming. Polymorphism is the ability of an object to have many forms. In UML terms, this is the number of IS-A relationships an object has. There are two types of Polymorphism.

All objects in Java are considered to be polymorphic since all objects are derived from the Object class and the class itself. For example, let’s say there is a laptop object. This object is created from the Laptop class (laptop IS-A Laptop). In addition, it is an object of the Object class (laptop IS-A Object).

There are two main ways

  1. Dynamic Polymorphism (Run time Polymorphism)

The reason why this is called run time polymorphism is that this concept talks about method overriding which happens at run time.

The simple idea can be explained like this. Let’s say there is a Java class called A and it has a subclass called B and both A and B classes have a method called run(). In this case, when we run the of B class, A’s run() method gets overridden.

Here is a small code snippet for the above example.

package polymorphism;
class A {
    public void run(){
        System.out.println("Running in A");
    }
}
class B extends A {
    public void run (){
        System.out.println("Running in B");
    }
}
class Main {
    public static void main(String[] args) {
        A obj = new B();
        obj.run();
    }
}

Basically why this is happening is that Java determines which method needs to be called in run time. Java does this by looking at the type of the object. In this case, since the object is type B, Java calls the run() method in the B class.

  1. Static Polymorphism (Compile time Polymorphism)

This is the concept of overloading the methods by changing the method signature. Java can determine which method needs to be called in compile-time, hence the name Compile time Polymorphism.

Method signature includes only the method name and the parameters. It does not include the return type of the method.

Let me explain this with an example as well.

package polymorphism;
public class Runtime {
    public static void main(String[] args) {
        MyClass.run();
        MyClass.run(10);
        MyClass.run(10, 12.5);
    }
}
class MyClass{
    public static void run(){
        System.out.println("Empty Method");
    }
    public static void run(int a){
        System.out.println("One Integer Parameter : " + a);
    }
    public static void run(int a, double b){
        System.out.println("With int and double parameters : " + a + " " + b);
    }
}

If you observe properly, each method signature is different from each other. This concept is called method overloading.

5. What is Abstraction in Java?

Abstraction in Java is the concept of hiding certain details from the user and only showing the essential information. This can be achieved using interfaces or abstract classes. Let’s talk about abstract classes first.

  1. Abstract Classes

Java abstract classes hold regular java methods and abstract methods. An abstract class is different from regular classes because we can’t create objects from abstract java classes. Even though we can have regular and abstract methods inside abstract classes, abstract methods can only be defined inside an abstract class.

The closest example I could think of explaining abstract classes is the class Animal. Abstract classes are like blueprints. There are no “animal” in the world, there are only classes like Cat, Dog, Lion that fall into the Animal superclass.

Let me create a simple Animal class and tell you how we can use abstract classes to our advantage.

Animal Class

package abstraction;
abstract class Animal {
    abstract void eat();
    abstract void sleep();
    
    public static void normalMethod(){
        System.out.println("Hey, I am a normal method");
    }
}

Cat Class

package abstraction;
public class Cat extends Animal{
    @Override
    void eat() {
        System.out.println("The cat is eating");
    }
    @Override
    void sleep() {
        System.out.println("The cat is sleeping");
    }
}

Main Class

package abstraction;
public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.eat();
        cat.sleep();
        Animal.normalMethod();
    }
}

Here what I did was that I created our Animal class which is abstract. Then I created a class called Cat which extends the Animal class. When a certain class extends an abstract class, that class has to override and implement all the abstract methods that have been defined in the abstract class. So, in this case, eat() and sleep() methods were implemented.

In addition, I added a regular method inside the Animal class just to show you the difference. Here is the console output of the above code.

The cat is eating
The cat is sleeping
Hey, I am a normal method
  1. Interfaces

Interfaces in Java are just like Abstract classes. They can hold regular methods and also abstract methods.

The methods in interfaces are generally public and abstract. All the variables in interfaces are public, static and final.

The main difference between interfaces and abstract classes is that a class can only extend one abstract class (since multiple inheritance concept is not allowed in Java). But if we use interfaces, we could implement multiple interfaces.

6. What is Encapsulation in Java?

Encapsulation is another core OOP concept that we use to achieve data hiding. Here what we do is that we declare variables as private variables and create getters and setters to modify the variables.

Here is a sample class where encapsulation has been implemented.

package encapsulation;
public class Encapsulation {
    
    private String name;
    private String address;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
You Can’t See Me 😎

7. What is Inheritance in Java?

Inheritance in Java is a vital concept that helps us to reuse the code again and again. Inheritance basically means that java classes can inherit data from some other classes. All the methods and attributes in the superclass can be accessed by all the subclasses.

We use extends keyword in Java in order to implement inheritance.

8. Why are there two ways to implement threads?

There ways of implementing threads in Java. They are, by implementing the runnable interface and by extending the Thread class.

When we extend the Thread class, we are creating threads where each thread is associated with a unique object. But when we implement the Runnable interface, we are using the object instance.

Just because we implement the runnable interface in a class, it does not become a thread. We need to pass the runnable instance to an instance of Thread class in order to make it a thread

The runnable interface should be used if we are going to only modify the run() method. In addition, if we want to extend a superclass, we should utilize the runnable interface.

9. What is Multithreading in Java?

Multi-threading, as the name suggests, involves executing two or more threads simultaneously. Each thread runs parallel to each other. All these threads use a shared memory space, hence saves memory. Context-switching between the threads takes less time as well.

Java Multithreading is mostly used in games, animations and stuff.

10. How do we use threads synchronously?

The need to use threads synchronously arises in situations where we are trying to interact with the same resource. For example, if multiple threads try to save data to the same file, there is a possibility of some data getting overridden.

So, to solve this, we need to make these threads work synchronously so that they know when the other thread is using the resource. The core concept used here is that every object in Java has a something called monitor associated with it. Only one thread can hold a lock on a monitor at a given time. The other threads have to wait until the lock is unlocked.

The way we can achieve this is by using synchronized blocks. Here is a simple code snippet to explain the concept. Here is an example of what would happen if we do not use synchronized blocks.

Thread1 class

package multithreading;
import static multithreading.Main.myClass;
public class Thread1 implements Runnable{
    @Override
    public void run() {
        myClass.deposit(100);
    }
}

Thread2 class

package multithreading;
import static multithreading.Main.myClass;
public class Thread2 implements Runnable{
    @Override
    public void run() {
        myClass.deposit(500);
    }
}

Main Class

package multithreading;
public class Main {
    static final MyClass myClass = new MyClass();
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Thread1());
        Thread thread2 = new Thread(new Thread2());
        thread1.start();
        thread2.start();
    }
}

MyClass class (This includes the main method)

package multithreading;
import java.util.Date;
public class MyClass{
    double balance = 0;
    public void deposit(double amount){
        balance += amount;
        System.out.println("The balance at " + new Date() + " is : " + balance);
    }
}

Here what we are expecting is 100 and 600 respectively. But since we are using unsynchronized threads, the expected result does not come up. Here is the output of the given code.

The balance at Sat Jan 23 11:57:11 IST 2021 is : 600.0
The balance at Sat Jan 23 11:57:11 IST 2021 is : 600.0

So, to correct this code, we need to make the deposit() method synchronized. Let’s see the code and the output after adding the synchronized keyword.

    public synchronized void deposit(double amount){
        balance += amount;
        System.out.println("The balance at " + new Date() + " is : " + balance);
    }
The balance at Sat Jan 23 12:02:26 IST 2021 is : 100.0
The balance at Sat Jan 23 12:02:26 IST 2021 is : 600.0

This is how using synchronization can save us from a malfunctioning program.


I’ve discussed 10 questions so far. Hope you enjoyed it. I’ll come up with another set of questions in the next article. If you have anything to say where I could improve, please drop a comment below. See you soon 👌😎


5 Reasons Why You Should Read Everyday

Reading is an empowering habit that you could adapt to your life and it will pay off every single day. Being a well-read person should be a goal in everyone’s bucket list. We can easily see a disparity between the thought process of a normal person and a person who reads regularly. Let me explain why I started reading a book a week and why you should too.

1. Reading books will help you learn constantly

Photo by Christin Hume on Unsplash

Warren Buffett, an American investor who is among World’s Top 10 Billionaires, reads 500 pages every single day and he suggests anyone who wants to be successful to do so too. He believes that reading is like compound interest.

To achieve better results in life, you need to learn regularly. The more you learn, the more you will get better in handling life’s challenges and thus becoming successful.

2. Reading improves your communication skills

Image by Free-Photos from Pixabay

Reading helps you look at life incidents in other people’s point of view. You get to learn from the stories and experiences of people you don’t even know. This is one of the reasons why I am using Quora frequently as well. We should always try to learn from other people. We should learn from other people’s mistakes.

Besides, reading updates your vocabulary and your thought process. When you read more and more, you will get exposed to more words. And eventually, they will slide into your everyday vocabulary without you even knowing. This is why we can usually spot how smart a person is when they talk about something.

3. Reading upgrades your brain

Photo by Frank Vessia on Unsplash

A team of neuroscientists at Emory University in Atlanta have discovered that just reading a novel initiates changes in the way the brain connects with different circuits, and most importantly, those changes last for at least five days. Although five days are not that long, this proves that reading changes us even after reading. It is like taking a steroid for the brain with no side effects at all.

When you read more and more about various topics, your brain creates connections between every one of them. This will eventually help you understand things deeply. Over time you will feel like you have the answers to everything.

4. Reading improves your concentration

Image by S. Hermann & F. Richter from Pixabay

Not being able to focus on something for a longer period is a problem most of the people have. This is mainly because of our electric devices and social media have been created. This is an immense difficulty I faced in the past because I have a cluttered mind.

But once I started reading every day and working to a schedule, I get things done in a focused manner. This has made me more productive and organized.

5. Reading helps you see through author’s eyes

When we read books, especially autobiographies, we get to experience and see how that person saw the challenges. We can learn from the way he conquered his failures. We can learn from the way he worked his ass off to get to the place where he is now. We get to see how he was depressed and looked like a fool.

These stories help you realize that none of the “special” people is special. They are just ordinary people like me and you. They have developed a healthy mindset in their lives that have helped them achieve their goals. If they can do it, we can do it too.

Watch this video to get motivated 😍🤘

Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.

Have a nice day ✌

Variable Arguments (Varargs) in Java

Hello coders, I am back with a new article series called Exploring Java. Here I am basically going to take java concepts and explain them one at a time and show you how and when to you them. I’ll try to keep the articles short and simple for you to grasp the core easily. Well, I hope you guys will like this article series. Let’s get to work.

What are Varargs?

Varargs aka Variable Arguments is a feature in Java that simplifies the methods that need to take in many arguments of the same type. Let me simplify. Instead of taking in arguments like this,

    public static int myMethod (int a, int b, int c, int d){
        return a + b + c + d;
    }

you can take in arguments like coded below.

    public static int myMethod (int ... args){
        System.out.println("Number of arguments : " + args.length);
        int sum = 0;
        for(int a: args){
            sum += a;
        }
        return sum;
    }

This code snippet will give the following result.

Number of arguments : 4
14

This is exactly like using an array as the argument. This is a more cleaner way to do it. I can pass any number of arguments of the same type. Here is how it works when there is a variable of another type.

    public static void main(String[] args) {
        System.out.println(myMethod("First One",1,3,4,6));
        System.out.println();
        System.out.println(myMethod("Second one"));
    }

    public static int myMethod (String text, int ... args){
        System.out.println("Number of arguments : " + args.length);
        System.out.println(text);
        int sum = 0;
        for(int a: args){
            sum += a;
        }
        return sum;
    }

This code snippets outputs the following result

Number of arguments : 4
First One
14

Number of arguments : 0
Second one
0

As you can see we can even stay without passing any parameters at all. This is a really cool feature for Java

Now you don’t have to create a new method every time an argument is added. You could just use varargs and not worry at all.


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.

Have a nice day ✌

6 Surprising Benefits of Journaling Everyday

Journaling is a habit that most of us have tried at least once in our lives. But a small percentage of people continues with it. Even though the thought of sitting down and writing things down in a book feels boring, it can have a surprising impact on your life.

So, let’s learn about the six surprising benefits you could experience from journaling every day.

1. You will learn from your old experiences

The more you expose yourself, the more you will learn about yourself

Image Source

When you get into the habit of writing down things that happened in your life each day, you can go back to any day you like and feel what you felt that day.

This can be really crucial, especially when you have bad days. For example, let’s say you had a fight with your partner and you wrote down everything. Once your anger is gone, you could just go back and read that journal entry. You will then realize how silly you were and the best way you should have reacted. So, when you get into the same kind of fight with your partner in the future, you could just act maturely with the experiences you have.

2. It sharpens your memory

Every one of us changes over time. The way we talk, the way we look, the way we think and etc. will change as you age. When you are 40 years old, you will never be able to guess how 20 years old you thought about yourself. Yeah, well that will happen only if you don’t maintain a journal.

Our beliefs will change over time. We won’t even realize it. Journal entries can remind you how you once thought. You will realize how much you have changed. Once you read these journal entries of old you and relive the memories, your memory will sharpen.

Relive the moments

Image Source

3. Keep it as proof for your progress

You can write anything you want in your journal. If you are trying to achieve some kind of a goal, write down what you did and what you want to do to achieve that goal.

After some time you could rollback and read the things you did when you were at the beginning. Reading those journal entries will make you feel really good.

These journal entries will be really helpful when you are having a bad day. Just read some of your good memories and relive them. You will realize how much progress you have made and how close you are to achieving your goal.

4. It will motivate you

This point is related to the last benefit we talked about. When you read one of your good memories on a bad day and realize how much work you have put in, you will be motivated to go for it.

In addition, since you know your day is going to be recorded in the journal at the end of the day, you will be motivated to do at least one good thing so that you could write it down on your journal.

Journaling will motivate you for good

Image Source

5. It improves your writing

Once you write and write every day for some time, your writing style will improve without you even realizing.

Especially if you are hoping to become a writer or a blogger or whatever, you should start from journaling. That is the easiest place where you could start writing because you are your favourite topic to write about. You will have no barriers. You can write just whatever you want.

Start your writing journey with journaling

Image Source

6. It relieves your stress

Having a journal is just like having a best friend with you every day. You can share anything with your journal.

If you are in a stressful situation, start writing and explaining your situation in the diary, just like you would explain it to your best friend. Once you finish writing down, you will feel so relieved and calm. The technical term for this is brain dumping.


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

Java OOP Concepts : Abstraction

Hello coders, I am back with another new article in my Java OOP Concepts article series. The concept that I’m going to elaborate today is called Abstraction.

What is Abstraction?

In Java, Abstraction is the process of hiding certain details from the end-user and showing only the essential information.

How can we achieve Abstraction?

This concept can be implemented in two ways in Java.

1. Using Abstract Classes

When we make a class Abstract in Java, we can’t create objects from those classes.

We can only access the data inside it once some other class inherits it (using extends keyword).

Abstract classes can contain abstract methods. Abstract methods do not have a body. The subclass that inherits this has to provide the body for the class.

Abstract methods can only be declared inside an Abstract class. But abstract classes can hold normal methods as well.

Take a look at these code snippets to get a better idea.

Animal class (Abstract)

abstract class Animal {

    public abstract void speak();

    public void sleep() {
        System.out.println("Sleeping Like an Animal");
    }
}

Cat class

public class Cat extends Animal{

    @Override
    public void speak() {
        System.out.println("Cat says Meow");
    }

}

Abstraction class (Main class)

public class Abstraction {

    public static void main(String[] args) {

        Cat cat = new Cat();
        cat.speak();
    }
}

Here is the console output of this.

2. Using Interfaces

Interfaces are just like abstract classes. Interfaces also hold methods with empty bodies.

A class needs to implement an interface to access the methods inside it (using implements keyword).

The cool thing about interfaces is that a class can implement multiple interfaces at once. But a class can’t extend multiple classes.

You will understand the concept better once you read the following code snippet.

Animal Interface

interface Animal {

    public void speak();

}

Mammal Interface

interface Mammal {

    public void A();

}

Cat class

public class Cat implements Animal, Mammal{

    @Override
    public void speak() {
        System.out.println("Cat says Meow");
    }

    @Override
    public void A() {
        System.out.println("I am a Mammal");
    }
}

Abstraction class (Main class)

public class Abstraction {

    public static void main(String[] args) {

        Cat cat = new Cat();
        cat.speak();
        cat.A();
    }
}

Here is the console output for the above code


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

Java OOP Concepts – Polymorphism

Hello fellow coders, I am back with another article in our Java OOP concepts article series. We learned about Inheritance in the earlier article. Today, we are going to learn about a concept called polymorphism that is also associated with Inheritance.

What is Polymorphism?

The word Polymorphism means many different forms.

Polymorphism can be implemented in Java in two ways.

1. Method Overriding (Runtime / Dynamic Polymorphism)

When there is a child class and a parent class, the child class can override the methods that are there in the parent class.

Here is a code snippet that shows how the concept can be implemented in Java code.

Animal Class (Parent Class)

public class Animal {

    public void speak(){
        System.out.println("Animals speak");
    }
}

Dog Class

public class Dog extends Animal{

    @Override
    public void speak() {
        System.out.println("Dog barks");
    }
}

Cat Class

public class Cat extends Animal{

    @Override
    public void speak() {
        System.out.println("Cat says Meow");
    }
}

Polymorphism Class (Main Class)

public class Polymorphism {

    public static void main(String[] args) {

        //Creating an Animal object of Animal type
        Animal animal1 = new Animal();
        animal1.speak();

        //Creating a Cat object of Animal type
        Animal animal2 = new Cat();
        animal2.speak();

        //Creating a Dog object of Animal type
        Animal animal3 = new Dog();
        animal3.speak();
    }
}

Here is the console output of the above code

2. Method Overloading (Static/ Compile-time Polymorphism)

We can overload a method by changing the method signature without changing the name of the method.

Take a look at the following code snippet to understand the concept simply

Animal class

public class Animal {

    public void speak(){
        System.out.println("Animals speak");
    }

    public void A(){
        System.out.println("No parameters - void");
    }

    public void A(int a, int b){
        System.out.println("Two int parameters (" + a + ", " + b + ") - void");
    }

    public double A(double a){
        System.out.println("One double parameter (" + a + ") - return a value");
        return a;
    }

}

Polymorphism class (Main class)

public class Polymorphism {

    public static void main(String[] args) {

        //Creating an Animal object of Animal type
        Animal animal1 = new Animal();

        animal1.A();
        animal1.A(10, 20);
        animal1.A(54.3);
    }
}

Here is the console output of the above code


I think I gave you guys a clear simple explanation about Java Polymorphism concept.

Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

Java OOP Concepts : Inheritance

Hello coders, I am back with another article about Java OOP concepts. Today, I am going to be explaining about Inheritance concept.

Inheritance in Java is not much different from its real meaning. Just like you have inherited the house you live in from your parents, Java classes can do the same thing.

Let me explain the concept with some code snippets so that you would be able to grasp the concept better programmatically.

Take a look at these two simple Java classes, Animal and Dog.

Animal Class
public class Animal{

    private String color;
    private String name;

    public String getColor() {
        return color;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void run(){
        System.out.println("Running");
    }
    
    public void sleep(){
        System.out.println("Sleeping");
    }
}
Dog Class
public class Dog {

    public void bark(){
        System.out.println("Barking");
    }
}

As you can see Dog class does not have any attributes and just has a method. Since Dog is an Animal, we should be using the attributes from Animal class, right? How can we do that in code?

Here we make use of the extends keyword in Java. This extends keyword helps us to create a connection between Animal and Dog classes.

public class Dog extends Animal {

    public void bark(){
        System.out.println("Barking");
    }
}

This makes sure that all the properties and methods that are there in the Animal class are accessible to Dog class. Let me show you real quick.

As you can see all the methods and properties in Animal class can be used from any Dog object now.

This concept is really powerful since it helps us to write simpler and faster code and reduce code duplication.

If we didn’t have Inheritance concept, we would have had to write everything all over again in Dog class too.

Super Class and Sub Class

When we implement Inheritance in our code base, the associated classes get their special names.

The class that inherits all methods and behaviours (Dog class) is called the Subclass.

The class that gets inherited (Animal class) is called the Superclass.


Well, I don’t think I have to explain this concept that further since this is a simple concept that is already there in the real world.

Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.

Have a nice day ✌

Java OOP Concepts – Encapsulation

Hello guys, I am finally back after a long break. Sorry for not being able to publish articles regularly.

Today, I am going to start a new article series regarding Java OOP Concepts. To start this off, I would like to discuss Encapsulation in this article.

Encapsulation is one of the core concepts when it comes to Java OOP (Object Oriented Programming) concepts.

What is Encapsulation?

Encapsulation is a mechanism we use to achieve data hiding and security. When we implement encapsulation in a certain class, the data related to that class only becomes accessible through methods. We can’t directly access or update the data once encapsulation is implemented.

Why should we implement Encapsulation in our code?

  • It makes our code more flexible and easy to change.
  • It helps us to make our code secure
  • We can make the class read-only if we don’t implement setter methods
  • We can make the class write-only if we don’t implement getter methods

How can I implement Encapsulation?

Let me write and explain the code as I write it.

public class Circle{
    
    //Defining Variables
    private double radius = 5.0;
    private String color = "Blue";

}

Here I created a Circle class with two attribures, radius and color. Nothing complicated. You may have recognized that I’ve used the private keyword to limit the access to the variables.

Why do we use private keyword?

Let me update the above code quickly to explain the difference

public class Circle{
    
    //Defining Variables
    String notPrivate = "I am visible"; 
    private double radius = 5.0;
    private String color = "Blue";

}

And I’ve created Test class and I am trying to access these variables from there.

public class Test{

    public static void main(String [] args){

        Circle circle = new Circle();
        //Prints I am visible
        System.out.println("Here is the normal variable : " + circle.notPrivate); 
        //Compile Error
        System.out.println("Here is the private variable : " + circle.color );  
    }
}

When we try to access a private variable, JVM throws an error like this

Compile Error

The same error occurs if you try to update the variable directly like this.

circle.color = "Red";

Adding Getters

So, let me revert this to the earlier code. Now we know that we can’t directly access these private variables. What can we do now?

Yes. We can add getter methods to achieve this. Here is the updated Circle class.

public class Circle{
    
    //Defining Variables
    private double radius = 5.0;
    private String color = "Blue";

    //Defining Getters
    public double getRadius(){
        return radius;
    }

    public String getColor(){
        return color;
    }

}

We need to make these methods public so that they are accessible from other classes. Now we can use these getter methods to access our private variables.

public class Test{

    public static void main(String [] args){

        Circle circle = new Circle();
        System.out.println("Radius of the circle : " + circle.getRadius());
        System.out.println("Color of the circle : " + circle.getColor());
    }
}

This prints out the following values to the console.

Adding Setters

So, now we have created a read-only class. We can read the data in the class, but we still can’t update the data. We need to add setters to update the data.

public class Circle{
    
    //Defining Variables
    private double radius = 5.0;
    private String color = "Blue";

    //Defining Getters
    public double getRadius(){
        return radius;
    }

    public String getColor(){
        return color;
    }

    //Defining Setters
    public void setRadius(double radius){
        this.radius = radius;
    }

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

}

Let’s try to update the values using these methods

public class Test{

    public static void main(String [] args){

        Circle circle = new Circle();

        //Testing Getters
        System.out.println("Radius of the circle : " + circle.getRadius());
        System.out.println("Color of the circle : " + circle.getColor());

        //Testing Setters
        circle.setRadius(10.0);
        circle.setColor("Red");

        System.out.println("Radius of the circle : " + circle.getRadius());
        System.out.println("Color of the circle : " + circle.getColor());

    }
}

This code prints out the following output to the console.

Alright, now we have fully implemented encapsulation in our code.

We can increase the security further if we implement abstraction concept. I will discuss abstraction in a later article.


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

IPL 2020 Team Review : KXIP

Hey guys, I am back with another article in my IPL Team Review article series. Today, we are going to talk about the KXIP team and my initial thoughts on the squad.

Squad Members

  • KL Rahul (wk, Captain)
  • Arshdeep Singh
  • Darshan Nalkande
  • Chris Gayle (✈)
  • Hardus Viljoen (✈)
  • Nicholas Pooran (✈)
  • Krishnappa Gowtham
  • Harpreet Brar
  • Jagadeesha Suchith
  • Mujeeb Ur Rahman(✈)
  • Karun Nair
  • Mandeep Singh
  • Mayank Agarwal
  • Mohammad Shami
  • Sheldon Cottrell (✈)
  • Glenn Maxwell (✈)
  • Murugan Ashwin
  • Jimmy Neesham(✈)
  • Sarfaraz Khan
  • Deepak Hooda
  • Ishan Porel
  • Ravi Bishnoi
  • Chris Jordan (✈)
  • Tajinder Singh
  • Simran Singh
Home Ground – IS Bindra Stadium
Head Coach – Anil Kumble
Winners – Never
Runners-Up – 1 time (2014)

Well, I’ve to say that this team has the potential to win the trophy this year. This is a stronger squad than last year’s squad.

My Ideal XI

Top Order

I would want Chris Gayle and KL Rahul to open the inning for me. Both of them are well-established openers and always have given KXIP a good start. Especially, Rahul’s form is going to be crucial for KXIP to have a good season. If he can lead from the front, it would take the pressure off Gayle which would help him to get back into his normal form.

I would Karun Nair as my number 3. He has played for many teams over the year and is an exciting talent. I would want him to take the responsibility to build an inning because I’ve seen his potential.

Middle Order

I would send Glenn Maxwell at number 4. The only reason I am going to pick Maxwell over Pooran is that he could roll his arm around to get me some crucial wickets. Glenn hasn’t been in his best form recently when it comes to T20Is. But I am going to back him for few matches to see if he could find his form back.

I would want Sarfaraz Khan to walk to the crease as my number 5 batsman. He is a young lad with good potential. He is not a textbook type player, but he would get you runs with his cheeky scoops.

Deepak Hooda would be my number 6 batsman. He also has been playing in the IPL for many years now. He has the experience that a number 6 batsman needs to control and get used to the conditions quickly.

I would send Krishnappa Gowtham at number 7. He is the perfect bowling all-rounder that you would like to have in your side. He has impressed me with his bowling over the recent IPL editions. I would want to hang around and finish the innings for me.

Bottom Order

I would want Chris Jordan to be my number 8. He would add more depth to the batting order and his off-cutters and slow bouncers could prove to be useful in pressure situations.

Murugan Ashwin would be my number 9. He also has been there with KXIP for some time and has the ability to take the crucial wicket.

I would want Mohammad Shami as my number 10. He is the only genuine pace bowler in the KXIP side. This is a big concern in my opinion. This is going to be a spin-heavy bowling attack. Since we are playing in UAE, the pitches are going to be dry and more friendly for the pacers. Even then, I would like to have another genuine fast bowler to go to if Shami gets injured.

I would add the Afghan all-rounder, Mujeeb Ur Rahman as my number 11. He can turn a match of its head with his spin. He is going to be crucial for KXIP in the first six overs. I would bowl him in the first 6 and save Shami for the death overs.

Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

IPL 2020 Team Review : MI

Hey cricket fans, I know IPL already has started. The plan was to finish the article series before IPL kicks off. But I couldn’t do it due to an unavoidable reason. I would like to finish off this series anyway.

Today, I am going to talk about the MI squad and my thoughts on my ideal playing XI. Let’s get going.

Squad Members

  • Rohit Sharma (Captain)
  • Digvijay Deshmukh
  • Quinton de Kock (wk)
  • Aditya Tare
  • James Pattinson (✈)
  • Nathon Coulter-Nile (✈)
  • Trent Boult (✈)
  • Saurabh Tiwary
  • Jasprit Bumrah
  • Dhawal Kulkarni
  • Chris Lynn(✈)
  • Prince Balwant Rai Singh
  • Jayanth Yadav
  • Suryakumar Yadav
  • Krunal Pandya
  • Kieron Pollard (✈)
  • Sherfane Rutherford (✈)
  • Rahul Chahar
  • Mitchell McClenaghan (✈)
  • Hardik Pandya
  • Mohsin Khan
  • Anmolpreet Singh
  • Anukul Roy
  • Ishan Kishan
Home Ground – Wankhede Stadium
Head Coach – Mahela Jaywardene
Winners – 4 times (2013, 2015, 2017, 2019)
Runners-Up – 1 time (2010)

My Ideal XI

Top Order

I would have Quinton de Kock and Rohit Sharma opening the batting for me. They are familiar with each others’ strengths and weaknesses. Both has the ability to take MI to a great start and can take the responsibility to play a long inning.

I want Suryakumar Yadav to come in at Number 3. He’s capable of hitting the long ball as well. I want my top order to take the score to something close to 60. I would take 60/1 after 6 overs any day of the week.

Middle Order

At number 4, I want Saurabh Tiwary to take responsibility. He has been there playing IPL for a long time now. He has the experience under his belt to handle any situation. He’s capable of hitting the long ball. I would want him to be more responsible and try to build the innings without throwing the wicket away without getting used to the pitch.

I’d send Kieron Pollard at number 5. He has proven that he can absorb pressure and build an inning throughout the last IPL. I’d want him to keep doing that while sending the loose balls into the crowd (alright, into the empty chairs 😂).

At number 6 and 7, I want Hardik Pandya and Krunal Pandya to keep playing the way they do. I would swap the two brothers in between 6 and 7 positions according to the game situation. I’ve seen Krunal‘s ability to keep his calm in pressure situations.

Bottom Order

I would pick Rahul Chahar at number 8 to add depth to the batting order. He’s an awesome young talent and has proven it time and time again. He’s one of the main reasons why MI won the title last year.

At number 9, I want Trent Boult to come in. He has the ability to hit the oddball for a six and can swing the new ball well.

Mitchell McClenaghan would be my pick to play as my number 10. He is a big strong unit that could hit the deck hard and get it up there.

Of course, Boom Boom Bumrah is going to be my number 11. With Malinga not playing, Bumrah has to take the lead in picking up the crucial wickets and giving that edge to MI team.

Well, this is just my opinion and I would like to know your thoughts on this as well.

Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

IPL 2020 Team Review : CSK

Well, first of all, I’ve to say sorry for not being able to post at regular intervals. Since one of the most anticipated IPL seasons are starting on 19th of September, I thought of giving you guys a team review about each team. We can see many new faces in this season when compared to other IPL seasons.

Today I am going to start the article series off with a review about Chennai Super Kings (CSK).

Squad Members

  • MS Dhoni (wk, Captain)
  • Ambati Rayudu
  • KM Asif
  • Deepak Chahar
  • Dwayne Bravo (✈)
  • Faf du Plessis (✈)
  • Imran Tahir (✈)
  • Narayan Jagadeesan
  • Karn Sharma
  • Kedar Jadhav
  • Lungi Ngidi (✈)
  • Mitchell Santner (✈)
  • Monu Kumar
  • Murali Vijay
  • Ravindra Jadeja
  • Ruturaj Gaikwad
  • Shane Watson (✈)
  • Shardul Thakur
  • Sam Curran (✈)
  • Piyush Chawla
  • Josh Hazlewood (✈)
  • R Sai Kishore
Home Ground – M.A. Chidambaram Stadium
Head Coach – Stephen Fleming
Winners – 3 times (2010, 2011, 2018)
Runners-Up – 5 times (2019, 2015, 2013, 2012, 2008)

My Ideal Playing XI

Top Order

I would stick with Shane Watson and Faf du Plessis combination. Both players understand each other well. Both are attacking players and they read the game quite well to understand when to fall back and take the single. They are the type of players who can hit a six whenever they want. Of course, we can’t forget Watson’s amazing 80(59) that helped CSK win the title in 2018.

And I would have Ambati Rayudu coming one down. He’s a good calm character who can handle pressure situations. He has proved his ability to do so on many occasions.

Middle Order

First of all, I’ve to say that they will miss Suresh Raina very badly this year.

I haven’t seen any of these new faces bat before. I would probably want a newcomer to take the responsibility at Number 4 position. I can’t recommend anyone since I don’t know how they play. So, I would just leave the spot empty for a newcomer.

At number 5 I want captain cool, MS Dhoni to come out. Well, I don’t think there is anything to describe him. He is a master of reading bowler’s mind and playing accordingly. He has all the shots in the book and favours hitting the ball over the bowlers’ heads.

I would want the champion, DJ Bravo to come out at number 6. He is a big hitter and a classical all-rounder with his slower balls which do deceive the batsman most of the time. Even though the batsman know what’s coming, he can’t do much about it.

And as my number 7, I want Jaddu (Ravindra Jadeja) to come to the crease. I still remember his six that helped CSK win a tight match against RR. Here is the clip if you haven’t seen it.

Image Source – CricShots.com

Lower Order

My number 8 would be Shardul Thakur . He’s a good addition to the side. He can swing the ball with the new ball.

At number 9 I am going to have two picks according to the wicket. If it is a spinner friendly wicket, I would play Imran Tahir. Well, I really would love to go with Mitch Santner since he would add some more depth to the batting order. But I’ve pick Tahir over him because of Tahir’s amazing bowling spells in last season.

If it is a pacer-friendly wicket, I would go with Sam Curran at number 9. He’s a handy batsman to have at number 8 and he can swing the ball well.

I would want Deepak Chahar to be my number 10. He’s a genuine swing baller who can cause trouble in the first few overs.

I want Karn Sharma to be my number 11. I’ve to pick Karn over Piyush’s form hasn’t been that reliable in the past few years. Karn on the other hand can bowl quickly and get through his overs. I feel that CSK lacks a specialist spinner like Ashwin or Chahal. A guy who can take wickets in the middle overs. A guy who is willing to toss it up and challenge the batsman to go at it.

So, that is my ideal for CSK’s this year’s IPL season. Comment your thoughts down below. I’d love to know your ideal XI too.


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

Must Know Concepts About Designing APIs

Hello coders, I am back with a fully detailed article today. Designing APIs could be a pain in the ass if you don’t have a plan. Designing APIs is, in my opinion, one of the most important steps in building a product. If you create your APIs up to the standards, you will be able to find and solve bugs quite easily.

I am going to talk you through from the basic explanation of what an API is to all the things I find important that are not being discussed often.

What is an API?

API stands for Application Programming Interface. According to Webopedia,

An application program interface (API) is a set of routinesprotocols, and tools for building software applications. Basically, an API specifies how software components should interact. Additionally, APIs are used when programming graphical user interface (GUI) components. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.

Webopedia

I know you didn’t understand a word. Let me break it down with a simple example.

When you write a comment for a post on Facebook and press Enter, Facebook sends a request to its remote server and the server will send a response back accordingly. The part of the remote server that accepts the request and sends the response is called an API.

Adding APIs to a System

1. Adding to an existing system

This is the fastest way to get it going. Since we already have a working system underneath, we just have to analyze the code and the logic and design the API.

The main drawback here is that we might have to face unexpected problems due to errors made in the initial building process of the existing system.

2. Building from the scratch

We are less likely to face unexpected errors since we design the whole thing from scratch. Developers can utilize the latest technologies and architectures in building the system.

The drawback visible here would be that it could take a long time to get the system up and running

3. Replacing piece by piece

Most of the developers prefer this strategy since the customer has a working system to work with and in the meanwhile, the developer can develop his part of the system.

Most Popular HTTP Methods

1. GET

This should only be used to retrieve a collection of resources (or a resource)

2. DELETE

Used to delete a resource

3. PUT

Updates an existing resource

4. POST

Can be used to create new resources or modify them.

Matching Verbs with HTTP Methods

Let’s think we are building an online shopping store. Here is how you could use the HTTP Methods according to the activities.

Viewing or listing an item(s), Viewing orders can be done using a GET request.

Checking out an item, Creating the cart, Cancelling orders can be done using a POST request.

Adding items to the cart can be done using a PUT request since we’ve already created the cart.

Deleting or Clearing an item(s) can be done using DELETE requests.

Types of Relationships between Resources

1. Independent

Can exist on its own without other resources. For example, an item can exist on its own.

2. Dependent

Can only existing if another certain resource exists. For example, an order can’t exist without a cart

3. Associative

Can’t exactly say whether it is independent or dependent by just looking at it. For example, a role in a movie might be played by many actors and the same actor might act different roles at different times.

The Most Important Step in API Modeling

When you are designing an API, the first and the most important thing you need to do is to choose a medium that you would use to document your process. This could be a pen and paper or a document online. You can’t switch the medium while you are in between the process. So, choose what works for you.

This document should include all of your assumptions, decisions, tasks, the gaps you might have to take a look at later and anything else that might be important for you and your team.

You can share this document among your team members so that if a customer asks about a certain decision that has been made, your team could answer confidently.

HTTP Response Codes and Their Meanings

1. 1XX Series (Informational)

You are unlikely to see these errors. These errors are informational.

2. 2XX Series (Success)

2XX codes mean the request was successful. Here are all the 2XX codes with their meaning

  • 200 – OK
  • 201 – Resource has been successfully created
  • 202 – The performed action is underway, but not complete yet
  • 204 – No content (Usually when a requested resource was deleted)
3. 3XX Series (Redirecting)

3XX codes are received when a resource has been moved from its original URL

  • 301 – Moved Permanently (The requested resource is no longer available in the given URL)
  • 302 – Moved Temporarily ( Even though the resource is no longer available now. It has a chance of reappearing)
4. 4XX Series (Client Error)

4XX codes are errors made by the client who is making the request.

  • 400 – Bad Request (The request failed to an error of client)
  • 401 – Authentication Required
  • 403 – Forbidden (Request was correct and was authenticated, but failed)
  • 404 – Not Found (The requested resource does not exist. It was not deleted or moved. It simply does not exist)
5. 5XX Series (Server-Side Errors)

These errors are from the server-side. As a developer, you can’t do anything about them

And another thing I’ve learned from listening to coding experts is that we should always try to stick to these standard response codes and not create our own. These codes have been standardized for a reason.


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

Five Simple Steps to Crystal Clear Thinking

Hello guys, I am back after a small break. Well, not a small break to be honest. I took a two-week break from writing to freshen up. Let’s get into our normal routine.

Today I am going to discuss some simple steps that you could take to think clearly when making decisions in your life. Without further ado, let’s get into it.

1. Don’t Rely on Others

This is a common mistake most of the people make. They rely on other people to make decisions for them. This is a really unhealthy way to live life.

Actually, this is one of the main principles I live my life by. We are responsible for every single thing that happens to us. You need to take responsibility for your life events. Jimmy didn’t fail the exam just because he got sick the day before the exam. If he had studied without waiting for the last minute, he would have passed the exam easily.

You will eventually understand that when we include this principle into our lives, life starts to look much simpler. This principle is not applicable to all life events. But I would advise you to try to apply this to everything as much as possible.

GIF Source – Tenor

2. Learn how to Learn

This is another crucial factor for anyone who wants to be successful. Before you start to learn something, you should learn how to learn.

There is no hard and fast way about learning. It is really subjective and unique. You need to try the methods out there and find out what works out best for you.

Personally, I have to write down what I learn. I have my own way of writing down things and connecting them to one another. I can’t recall things I hear. But I can recall things if I write them down.

After you find your unique way, things will start to get a lot more clearer in your head. When you want to learn something new, you just have to apply your learning method into that and learn it. You will start to find out ways to optimize your learning method to make the process faster and smoother.

Image Source

3. The Fire has to start from inside

We all get pumped up after watching some random motivation videos on YouTube. But that motivation does not last that long. The motivation must come within you, not from outside.

It is okay to start working out after watching a motivational video about an amazing body transformation. But you can’t stop it right there. All the motivation you have is going to go away someday. When you have the will power to do something with zero motivation, you will start to grow.

This is why we should find our WHY before doing something. If you are doing something for the sake of doing it, you are going to fail sooner or later. You can’t just force yourself to do something. You have to learn to start loving what you do. You need find your WHY to do that.

When you love what you and when you know exactly why you are doing it, things are going to be so clear in your mind.

Image Source

4. Scientific Thinking

Well, this is a concept we are taught in our schools. Even though we all know this concept, very few of us learns to apply it to our day-to-day life.

Science is based on facts. There is no room for beliefs. If you believe in something, find a way to prove it. If others can get the results for themselves as well, your belief will become a fact.

Another thing that is really important in Science is constantly asking questions. This is something we should encourage children to do at a very young age. When someone says something is true, ask them why. If you feel a certain way about someone, ask yourself why.

Everyone must try this in their lifetime. You can’t even imagine how far our mind has taught about something. You may even get the answers to your questions from inside of you. This is why most of the people recommend self-talking or journaling.

Image Source

5. Find a Fresh Point of View

When we get stuck in some problem for some time, we eventually start to get a fixed-mindset. You’re going to start seeing the problem in the same way no matter hard you try.

I would love to share a coding experience of mine with you guys. When I get stuck in a place for more than 1-2 hours, I have felt that I only can read the code in a certain pattern. No matter how hard I try, I can’t see it in a fresher way. Here, what I usually do is ask one of my colleagues to help me out. If there is no one around, I would just shift to some other task and get back into the next day. Since I don’t remember what is in the code, I have to read the code from the top. When I do that, I usually start to see what’s wrong immediately.

This concept actually works really well in any situation. It could your best friend, girlfriend/boyfriend or just a stranger you met at the coffee shop. You talk to them about your problem and ask for their point of view. Their ideas will help you get out of your brain-freeze.

GIF Source – Tenor


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

How Much Should You Save Each Month?

Hello guys, today I am back with another article that is going to help you improve your lifestyle. Today we are going to be discussing the ideal amount of money one should save each month. If you are someone who is wandering around looking for financial advice, I would like to invite you to start from here. Let’s learn to save.

The 50/30/20 Rule

This is a popular rule most of you must have heard of. This famous rule suggests us to utilize the money we earn according to the following ratio.

  • 50% – For Basic Needs (Food, Rent, etc)
  • 30% – For whatever you want
  • 20% – For Saving

So, according to this, if you earn 500 dollars per month, you should save 100 dollars. Well, if you are a high-earner, you can go ahead and save more than 20%.

If you don’t have a significant wage, it is ok to decrease the percentage you save. But should always remember to earn something every month. It doesn’t matter whether it is 500 dollars or 5 dollars. You need to, first of all, create this habit of saving. To do that, you have to save some amount of money each month.

We are not getting any younger

Most people realize that they should start saving way after their forties. I think that is quite late since we are getting closer to our retirement. We should start saving from the day we get a regular income.

If you are in your 20s or 30s, you will be able to save a significant amount of money if you follow the 50/30/20 rule. When you are retiring you will have enough money to spend your latter years without depending on anyone.

How long will I have to save?

This depends on the amount you earn each month and the percentage you are going to leave for savings.

For example, if you are earning 540 dollars per month, you will be able to save something around 13000 dollars.

Hungry for More?

If you want to know more about saving money or to get any kind of financial advice, I would recommend the YouTube channel of Dave Ramsey and the YouTube channel of Nate O’Brien.

For starters, watch this video from Nate about money-saving tips.

Video Source – YouTube


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

Why Do Wicketkeepers Appeal for Everything?

An umpire can’t just signal a batsman as a dismissed player just because he thinks so. He needs some help from the fielding team as well. Do you know about the captain who recalled the batsman back to the field after being (wrongfully) given out by the umpire? Find out that and many more in today’s article.

Hello, Cricket Fans, I am writing a new cricket article after a very long break. I’ve been holding back because I wanted to add a YouTube video along with my cricket articles. I’ll link my YouTube video at the end of my article. Let’s get into it.

How can a Batsman Get Out?

1. Umpire can give the batsman out after fielders appeal

We all know that umpires give the batsman out after fielders appeal. But actually, umpires can give a batsman out only if the fielders appeal. An umpire can’t signal a batsman as a dismissed player if none of the fielders appeal.

This is the reason why almost all the wicketkeepers in cricket appeal for almost anything. Apart from the umpire, the wicket keeper is the one who usually has the best view of things. And if wicket keeper’s appeal is a strong one, the umpire is more likely to give the batsman out.

Well, this did not go well for Andrew Flintoff in the following incident.

Andrew Flintoff had a Bad Day at The Office

Video Source – YouTube

2. Umpire can give the batsman out if the batsman walks off (and if the umpire thinks it is out)

With the introduction of DRS, most of the players decide not to walk off even if he knows that he is out. But in the earlier days where we didn’t have DRS, some batsmen did walk-off if he is sure he is out. This made the job easier for the standing umpires especially when the umpire was not sure.

Adam Gilchrist walking off in 2003 WC Semi-Finals

Video Source – Youtube

If batsman decides to walk off due to a misapprehension, the umpire can ask him to come back.

A batsman may be recalled at any time up to the instant when the ball comes into play for the next delivery, unless it is the final wicket of the innings, in which case it should be up to the instant when the umpires leave the field.

The Laws of Cricket | MCC

When should fielders appeal?

  • Fielders should appeal before the bowler begins the run-up to bowl the next delivery
  • If there is no run-up, the fielders should appeal before the bowler gets into his bowling stride.
  • If it is the end of the over, the fielders should appeal before the next over starts

Another thing that I should mention is that Call of Over does not matter here. Call of Over is basically when the umpire says, “Over” at the end of an over. Fielders still can appeal after Call of Over.

In case of DRS, fielders can’t take that long. Fielding captain only gets 15 seconds to decide whether they want to take the review or not.

How should fielders appeal?

Usually asking ” How’s That ?” is the tradition. This covers all the ways the batsman can be given out.

How should umpires answer appeals?

  • Striker’s end umpire is in charge of answering appeals regarding Hit Wicket, Stumpings and Runouts at his end.
  • Bowler’s end umpire is in charge of answering appeals regarding all other ways of getting out and Runouts at his end.
  • If any of the umpires are capable of making the decision, he can go ahead and make the decision.
  • If the responsible umpire is not sure, he can have a chat with the other umpire before making the decision.
  • If they can’t still make the decision, they can ask for an umpire review to consult the third umpire.

Can we withdraw an appeal?

Yes. It is possible to withdraw an appeal.

Here the captain of the fielding team should ask to withdraw their appeal after obtaining the consent of the umpires.

This also has to be done before the next ball is bowled unless it is the last wicket of the innings. In that case, the fielding captain should do this before umpires walk off the field.

There is a popular occasion where this has happened. Andrew Symonds of Australia was given out in a match against Sri Lanka for covering the wicket. The replays clearly showed that there was a big inside edge. After seeing this, Sri Lankan captain Mavan Atapattu decided to recall Symonds to the field. Here is the full video.

Andrew Symonds gets a callback

Video Source – YouTube


Well, I’ve linked down my new YouTube video regarding Cricket Law 31 – Appeals and Dismissals for my Sri Lankan viewers.


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

TreeMaps – Java Collections Framework

If you want to save a sequence of key/value pairs and if you want them ordered by the key, what would be your ideal option? Don’t have an idea? Don’t worry. Let’s talk about that today.

Hello coders, I am back with a new article in my Java Collections Framework article series. Today I am going to discuss TreeMap class in Java. TreeMap class extends the SortedMap Interface and that extends the Map Interface.

HashMaps vs TreeMaps

TreeMaps are considerably similar to HashMaps. There are two main differences between these two classes.

  1. HashMaps are implemented as a Hash Table. TreeMaps are implemented based on Red-Black Tree Structure

If you are not aware of Hash Tables and Red-Black Tree Structure, please refer to the linked articles to get a better idea. I will be talking about Hash Tables later in this article series as well.

  1. HashMap does not maintain order. TreeMaps are ordered by the key.

Here is a small code snippet that explains the difference between HashMaps and TreeMaps.

        //Creating a TreeMap
        TreeMap<Integer, String> myTreeMap = new TreeMap<>();

        myTreeMap.put(34, "Smith");
        myTreeMap.put(62, "Virat");
        myTreeMap.put(1, "Marnus");
        myTreeMap.put(8, "Stokes");
        myTreeMap.put(2, "Williamson");

        System.out.println("TreeMap : " + myTreeMap);

        //Creating a HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        myHashMap.put(39, "Smith");
        myHashMap.put(61, "Virat");
        myHashMap.put(9, "Marnus");
        myHashMap.put(13, "Stokes");
        myHashMap.put(4, "Williamson");

        System.out.println("HashMap : " + myHashMap);
TreeMap : {1=Marnus, 2=Williamson, 8=Stokes, 34=Smith, 62=Virat}
HashMap : {4=Williamson, 39=Smith, 9=Marnus, 61=Virat, 13=Stokes}

Similarities

  1. Both are unsynchronized and should be synchronized explicitly to be used in a thread-safe environment
  1. Only contains unique elements. (Key should be unique)
  1. Keys can’t be null. Values can be null.
        //Creating a TreeMap
        TreeMap<Integer, String> myTreeMap = new TreeMap<>();

        myTreeMap.put(34, "Smith");
        myTreeMap.put(62, "Virat");
        myTreeMap.put(null, "Bro"); // Causes NullPointerException
        myTreeMap.put(4, null); //This is fine

        System.out.println("TreeMap : " + myTreeMap);
  1. Methods are almost the same.

I am not going to list down the methods here. You can take a look at all the available methods here in the Java Documentation


Now you know where to go to when you want to store key/value pairs ordered by the key.

Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

5 Life-Changing Advice from Billionaires

Hello guys, today I am going to talk about life lessons from billionaire entrepreneurs. These are things they’ve learned from experience in their amazing journey to success. As I always say, all of these pieces of advice might not be for you. You might be able to utilize these pieces of advice in your life journey.

Don’t directly add anything to your life and hope for it to change your life. Every one of us is different. We all have different lifestyles and different backgrounds. Experiment with these pieces of advice. If it doesn’t suit you, leave it.

Let’s get into the article.

1. Persevere

Life is not going to be a bed of roses. There is going to be times where you are going to feel down and out. There is going to be times where you feel like stopping. But don’t.

This is the corridor where most of us fail to go through. This is the reason why only 1% of the world population has become successful.

Here me out and say if this has happened to you too. You watched some crazy transformation video on YouTube. You look at yourself and say, “I wanna be like that. I can do that. I want a body like that”. So, you go and join the gym the next day. You are so pumped. You go to the gym for a week or two or maybe a month. On a gym day, one of your friends invites you to go to a party. You think to yourself, “There is no harm in skipping a day”. Next thing you know, you haven’t gone to the gym in a few months and you are watching motivational videos on YouTube.

I bet most of you guys have experienced something like this. Do you know why that happened? That happened because external motivation is crap. Motivation is good to make you get started. But it is going to fade away soon. On that day when your motivation comes down to zero, you are going to find whether you really have what it takes to build that amazing body. And that must come from inside of you. You need to know how to motivate yourself. You need to find out how you can persevere through this mental barrier. You’ve got to do that again and again.

2. Find a Strong Why

This one also can be associated with the last point. The main reason you fail when your motivation reaches zero is that you don’t have a clear vision.

The first thing you need to do is finding your Why. Let’s get back to that workout example. If the only reason why you are building your body is that someone made fun of your body, you are going to fail at some point. That is not a strong why. Your why should be a long term goal like getting fitter than yesterday or a short term goal like losing 10 kilos at the end of this month. These goals are more achievable and realistic. You can motivate yourself to get to realistic goals.

Listen to this amazing speech from one and only Arnold Schwarzenegger.

Video Source – Alpha Leaders Productions YouTube Channel

3. Have Humanity

In my opinion, this is something that is slowly getting away from today’s society. George Floyd incident was an eye-opening moment for everyone in the world to see how society has changed. I am not saying that society was better in the past. But it surely is not getting any better.

We all are going after money and fame. Yes, money is important. But there is a point where you earn enough to live your day-to-day life happily. That is enough. Most of the people are circling through a vicious cycle. When we want to earn more and more, we only get more greedy and inhumane. Today’s society has come to a point where a person would kill someone else for a few hundred bucks.

You are not going to take your money with you when you die. Always try to help people to get to a better place in their lives. In the end, your mental satisfaction is going the that is going to stay with you when you die.

4. Work Hard and Smart

Everyone says that you should work smart and not hard. But billionaires believe that both are equally important. Bill Gates once said that he didn’t believe in weekends when he was in his 20s. This is a common thing among most of the billionaires. They have dedicated their whole life to get to where they are in their lives.

What I mean by work hard and smart is that you need to be smart to choose the thing that you should be working on at the moment. And you need to focus on that task and work hard to achieve that goal.

5. Do what you Love

When you are choosing a career path, always choose a career which you are interested in. Do not choose a career just because it pays well. When you choose something you love, the money will come towards you.

When you do something you love and something you are really interested in, you won’t really feel it as working. You will be able to work really hard and still be motivated. You will not feel tired. When you work like that, the money will come to you. You will not even care because you are not doing it for the money. You are doing it for your own satisfaction


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

HashMaps – Java Collections Framework

Hello coders, I am back with a new article in my Java Collections Framework article series. Today, I am going to discuss the HashMap class in Java. HashMap extends the Map interface in Java. Let’s learn about HashMaps.

What is HashMap?

HashMap is a class that is being used for data mapping. We use HashMaps to store data in key & value pairs. HashMaps do not maintain order. So, you should not use HashMaps, if you expect your list to keep order. In addition, HashMaps allow null values and this implementation is not synchronized.

Let’s learn how you can use HashMaps to store data.

HashMap Class Methods

1. value put(key, value)

This will add a key and value pair to the map. The method returns the value that was paired with the given key earlier. If the given key was never used in the map before, it will return null.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        System.out.println(myHashMap.put(2, "Mahela"));
        System.out.println(myHashMap.put(2, "Sanga"));

Here is the console output.

null
Mahela
2. value get (Object key)

This method returns the values paired with the given key.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        myHashMap.put(2, "Mahela");
        myHashMap.put(3, "Sanga");

        System.out.println(myHashMap.get(3));

Here is the console output

Sanga
3. boolean isEmpty()

This method returns true if the map is empty.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        myHashMap.put(2, "Mahela");
        myHashMap.put(3, "Sanga");

        System.out.println(myHashMap.isEmpty());

Here is the console output.

false
4. boolean containsKey (Object key)

This returns true if the given key is there in the map.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        myHashMap.put(2, "Mahela");
        myHashMap.put(3, "Sanga");

        System.out.println(myHashMap.containsKey(2));

Here is the console output.

true
5. boolean containsValue(Object value)

This returns true if the given value is there in the map.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        myHashMap.put(2, "Mahela");
        myHashMap.put(3, "Sanga");

        System.out.println(myHashMap.containsValue("Sanga"));

Here is the console output.

true
6. Set keySet()

This method returns the set of keys in the map.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        myHashMap.put(2, "Mahela");
        myHashMap.put(3, "Sanga");

        System.out.println(myHashMap.keySet());

Here is the console output.

[1, 2, 3]
7. int size()

This returns the size of the map.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        myHashMap.put(2, "Mahela");
        myHashMap.put(3, "Sanga");

        System.out.println(myHashMap.size());

Here is the console output.

3
8. value remove(Object key)

This method removes the key and value pair according to the specified key and returns the values that key was paired to.

        //Creating HashMap
        HashMap<Integer, String> myHashMap = new HashMap<>();

        //Adding values
        myHashMap.put(1, "Thisura");
        myHashMap.put(2, "Mahela");
        myHashMap.put(3, "Sanga");

        System.out.println(myHashMap.remove(2));
        System.out.println(myHashMap);

Here is the console output.

Mahela
{1=Thisura, 3=Sanga}

I believe these methods are the important ones you should know to get started with HashMaps. If you are interested in learning more about HashMaps, go ahead and read the Java documentation here.


I am going to wrap up this article here. Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day. Have a nice day ✌

Set Interface – Special Article 02

Hello fellow coders, I am back with my second article of our Java Collections Framework article series. So far we have covered all the classes that extend the Set interface and List interface.

If you can remember I wrote my first special article after covering the classes that extend the List interface. Since I have covered the classes that extend the Set interface, I am dedicating this special article to point out important points about the Set interface.

When it comes to the classes that extend the Set interface, these are the points you should keep in mind.

1. They do not keep track of the order

There is no way to track and get your elements after you add them. Basically do not use the classes that extend the Set interface, if you want to access the elements by index or something. You can go with a class that extends the List interface for that.

2. They do not allow duplicate values

This is a unique and important point that is specific to the Set interface. If your requirement is to have a list where you are sure that all the values are unique, a class that extends the Set interface is your best bet.

3. HashSet is faster than TreeSet

If you don’t intend to use value-ordered iteration, always go with a HashSet. LinkedHashSet is a class that is in an intermediate state between HashSet and TreeSet. LinkedHashSet provides insertion-ordered iteration and is faster than TreeSets.

4. Choose the initial capacity for HashSet mindfully

Read this explanation from Java Documentation.

One thing worth keeping in mind about HashSet is that iteration is linear in the sum of the number of entries and the number of buckets (the capacity). Thus, choosing an initial capacity that’s too high can waste both space and time. On the other hand, choosing an initial capacity that’s too low wastes time by copying the data structure each time it’s forced to increase its capacity. If you don’t specify an initial capacity, the default is 16. In the past, there was some advantage to choosing a prime number as the initial capacity. This is no longer true. Internally, the capacity is always rounded up to a power of two. The initial capacity is specified by using the int constructor.

Common Methods for Set Interface Implementations

1. boolean add (Element e)

Adding a given element to the set.

2. void clear()

Removes all the elements from the set

3. boolean contains(Object obj)

Checks if a given object is there in the set

4. boolean isEmpty()

This returns true if the set is empty

5. boolean remove(Object obj)

If the specified object is present in the list, this removes that element from the set and returns true. If the specified object is not there in the list, this returns false.

6. int size()

This returns the number of elements in the set


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

6 Biggest Motivation Killers You Should Avoid

Hello guys, today I am going to talk about the biggest motivation killers in life and how you can avoid them. You may already have come to realize these motivation killers at some point in your life. The good news is that I am going to teach you guys tips on how to avoid them as well. Without further ado, let’s hop in.

1. Pessimism

Be Optimistic

Image Source

We all have met that person who whines about everything that goes on his life. I’ve met a lot of pessimistic people. I even have found myself stuck in a pessimistic mindset in some situations. Being optimistic does not mean that we should try to avoid and ignore stressful situations. It just means that we should try to be more productive in that given situation.

One proven technique to be more optimistic is to change the way you look at life events. If you find yourself being pessimistic, make yourself realize that there might be a better way to look at this. For example, think of a rainy day. If you are a pessimistic person, you might think, “This is horrible. I am not going to be able to do anything I had in mind. Oh, this is terrible. Why everything is happening to me?”. If you are an optimistic person, you might think, “Yeah. This is awesome. I can just relax and watch some movies today. Then I can read a book. I could cuddle close to my girlfriend the whole day”.

Do you see the difference? You see things the way you want them to be seen.

Another technique you could use is keeping a list to write down the things you have achieved in your life. You can either write it online or in a piece of paper. Read this list when you feel like you are being pessimistic. When you keep reading these achievements, you are enforcing positive emotions in your mind. This will keep you motivated and optimistic.

Another thing to keep in mind is that both negative and positive emotions are contagious. So, keep an eye on your social circle and get rid of the people who are pessimistic or teach them these techniques to become an optimistic person.

2. Don’t Limit Yourself. Explore

Explore

Image Source

You are making your limitations. You can achieve whatever you believe in. Nelson Mandela once said, “It always seems impossible until it’s done“. The only thing that is standing between you and success is you.

There is nothing impossible in this world. Don’t give up at something without even trying. Doing something is always better than procrastinating.

Stop feeling sorry for yourself. No one is going to come to save you. You are going to have to do it for yourself. We tend to procrastinate when we don’t have a clear vision of what you are trying to achieve.

Besides, try something new which is out of your comfort zone. This is harder than it sounds. But when you are done, you will feel so confident and awesome more than ever.

You can start by making a list of your fears and giving yourself small challenges that make you break out of your comfort zone. The more you break out of your comfort zone, the bigger it grows. Always try to widen your comfort zone.

3. Don’t Look for Excuses

When something goes wrong in your life, do not try to blame others. Do not try to find excuses. Learn to take responsibility for everything that happens in your life. When you learn to do this, everything becomes more clear.

When you stop looking for excuses, you will find the real reason why you failed and then you can make sure not to repeat it ever again. If you try to find excuses, you are never going to grow.

4. Lack of Planning

Plan your day

Image Source

I’ve said this many times in my earlier articles as well. You should always plan out your day from start to finish. This is going to stop you from procrastinating and will motivate you to get things done.

Just write down your goals for the day. Break them down to small actionable steps. Allocate time slots for each of those tasks and start your day.

5. Concentrating on previous Failures

Image Source

Everyone fails in their lifetime. Failing is nothing to be ashamed of. You don’t become a failure when you fail at something. You become a failure when you give up.

The only person who does not fail in this world is the person who doesn’t try anything new. The only way to grow is by making mistakes. You can’t make mistakes if you don’t try.

When you fail at something repeatedly, your inner-voice is going to say that you are going to fail again. You need to have the guts to say, “F**k it. I am going to do it again. I am not going to stop until I do this”.

Another thing that divides successful people from others is that ordinary people stop when they are tired. But successful people stop when they are done.

6. Worrying about What Others Think

Stop Thinking about What Others Think of You

Image Source

No matter how hard you try, you can’t please everyone. You have to accept it and move on with your life. Whatever you do, there is going to be that person who doesn’t support you.

When you are yearning for the acceptance of other people, you are going to forget who you are. Make choice based on how you want your life to be, not on what other people want it to be. This also happens when you don’t have a clear vision. When you know where you are going and how you can get there, nothing can stop you.

I would love to recommend this article of mine for you guys, to get more insight on this.


Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌

TreeSets – Java Collections Framework

Hello coders, I am back with another article in my Java Collections Framework article series. Today I am going to discuss our 3rd and final class that implement the Set Interface which is TreeSet class. TreeSet is quite similar to the HashSet class we talked about earlier.

Since you already know about the HashSet class, I am going to discuss the similarities and differences between the two classes to give you a clearer idea.

Similarities

1. Doesn’t allow duplicate elements

Both HashSet and TreeSet objects do not allow duplicate elements. If we insert duplicate elements, the existing elements will be overwritten.

        //Creating TreeSet and HashSet objects
        TreeSet<String> myTreeSet = new TreeSet<>();
        HashSet<String> myHashSet = new HashSet<>();

        //Adding elements to the TreeSet
        myTreeSet.add("Nicola Tesla");
        myTreeSet.add("Elon Musk");
        myTreeSet.add("Thomas Edison");
        myTreeSet.add("Gary V");
        myTreeSet.add("Elon Musk");
        System.out.println(myTreeSet);

        //Adding elements to the TreeSet
        myHashSet.add("Nicola Tesla");
        myHashSet.add("Elon Musk");
        myHashSet.add("Thomas Edison");
        myHashSet.add("Gary V");
        myHashSet.add("Elon Musk");
        System.out.println(myHashSet);

Here is the console output. If you look carefully, you might be able to notice one of the differences between these two classes as well. Don’t worry if you don’t. I am going to explain it in the latter part of the article anyway.

[Elon Musk, Gary V, Nicola Tesla, Thomas Edison]
[Thomas Edison, Gary V, Nicola Tesla, Elon Musk]
2. Both are not synchronized

Both classes are non-synchronized classes which means that they are not thread-safe.

Differences

1. Maintaining an order

HashSet class do not maintain order while the TreeSet class maintains the ascending order. If we look at the earlier code snippet, we can clearly see the difference. We can see the TreeSet maintaining the ascending order while HashSet don’t.

[Elon Musk, Gary V, Nicola Tesla, Thomas Edison]
[Thomas Edison, Gary V, Nicola Tesla, Elon Musk]
2. Performance

When it comes to performance, the HashSet class is in front. HashSet class provides a faster performance when performing general CRUD operations.

Converting HashSets into TreeSets

If you want, you can convert HashSets into TreeSets. This can be useful when you want to sort the elements in a HashSet. You can simply convert your HashSet into a TreeSet in order to sort the elements in ascending order.

        //Creating TreeSet and HashSet objects
        HashSet<String> myHashSet = new HashSet<>();

        //Adding elements to the TreeSet
        myHashSet.add("Mahela");
        myHashSet.add("Sanga");
        myHashSet.add("Dasun");
        myHashSet.add("Mavan");
        myHashSet.add("Dilshan");
        System.out.println(myHashSet);

        TreeSet<String> myTreeSet = new TreeSet<>(myHashSet);
        System.out.println(myTreeSet);

Here is the console output.

[Dasun, Sanga, Mavan, Dilshan, Mahela]
[Dasun, Dilshan, Mahela, Mavan, Sanga]

If you want to know more about the TreeSet class, refer to the Java Documentation.


This ends the article about the TreeSet class. If you liked the article, drop a like and follow my blog. If you have any doubts, drop a comment down below. Stay Safe ✌

5 Tips on How to Become an Everyday Leader

Hello guys, today I am going to give you some important tips to become an everyday leader. You may have noticed that some people take the responsibilities and boss the situation wherever they go. If you want to be that guy, you need to adapt these things to your life so you can boss the situation next time.

1. Learn about yourself first

Before you lead other people, you need to sort things out for yourself. People are more likely to listen to a person who has his shit together. Find your passion and start working on it. You always need to have a clear vision on what you should and should not do at a given situation.

Be a Man with a Plan

Image Source

When you learn about what you are passionate about, you can seek out opportunities to meet other people who have the same passion as you do.

2. Listen to other people

Listen to other people

Image Source

One of the most important qualities of a great leader is listening to what others have to say. You should always prefer to talk less and listen to more people. Listen to experts, colleagues and even to the people who disagree with your opinions. It does not matter whether they like you or not. What matters is that you get to learn their insights, perspective and experiences.

When you know how other people think and listen to their personal experiences, you will get to understand the people better. When you understand people better, you can lead them better. Besides, when you listen to others’ opinions, they automatically start to like you.

3. Speak Up

Speak Up

Image Source

You need to realize that leaders don’t talk things without thinking about them first. You can’t do that if you are going to be a leader. People are looking up to you. You should always set an example on how to go on in your life.

When you are sharing your opinion, whether it is in front of an audience or social media, always try to make your opinion clear and concise. This is another skill that you should master when you are becoming a good leader. You need to learn how to express your opinion constructively.

This makes you stand out from other people. As long as you believe in what you stand for, people will join by your side.

If people are already discussing something, go ahead and tell them what you perspective is. Try to add something fresh to the conversation. You will automatically be able to lead the conversation to a place where you are comfortable.

4. Failure is a muscle

Workout your Failure Muscle

Image Source

You need to understand that you are going just like everyone else is. Failure is like training a muscle. We go to the gym to workout and build our muscles. When you workout, you damage your muscle fibers. In the end, this process makes our muscles stronger.

Failure is just the same as training a muscle. When you fail, you get to learn about something what you should not have done. You get to correct yourself. In the end, failure is going to make you a stronger person.

So, you should always be willing to fail. You are not going to fail, if you don’t try. And if you don’t fail, you won’t get to become a stronger version of yourself. Always be willing to try out different things.

5. Smile

Smile with People

Image Source

Smile is the most powerful tool a person has. Everyone likes to be around a leader who smiles with them and makes them feel good inside. Even though this is a regular tip, you will realize how many people ignore this tip.


Thank you for reading my article. If you enjoyed it, drop a like and follow my blog. Stay safe ✌

LinkedHashSets – Java Collections Framework

Hello coders, today I am going to talk about another class that implements the Set interface in Java called LinkedHashSet.

Points to Notice

1. Contains Unique Values (Like HashSets)

LinkedHashSets also contain unique values. If we try to duplicate a value, the existing value gets overwritten by the new value.

        //Creating a LinkedHashSet
        LinkedHashSet<String> myLinkedHashSet = new LinkedHashSet<>();

        //Adding Elements
        myLinkedHashSet.add("Joey");
        myLinkedHashSet.add("Chandler");
        myLinkedHashSet.add("Ross");
        myLinkedHashSet.add("Monica");
        myLinkedHashSet.add("Chandler");
        System.out.println(myLinkedHashSet);

Here is the console output.

[Joey, Chandler, Ross, Monica]
2. Allows null values (Like in HashSets)
        //Creating a LinkedHashSet
        LinkedHashSet<String> myLinkedHashSet = new LinkedHashSet<>();

        //Adding Elements
        myLinkedHashSet.add("Joey");
        myLinkedHashSet.add("Chandler");
        myLinkedHashSet.add(null);
        myLinkedHashSet.add("Ross");
        myLinkedHashSet.add("Monica");
        myLinkedHashSet.add("Chandler");
        myLinkedHashSet.add(null);
        System.out.println(myLinkedHashSet);

Here is the console output.

[Joey, Chandler, null, Ross, Monica]
3. Saves values according to the Insertion Order

The LinkedHashSet saves values according to the order we add them. This makes it stand out from the HashSet class.

        //Creating a LinkedHashSet
        LinkedHashSet<String> myLinkedHashSet = new LinkedHashSet<>();

        //Adding Elements
        myLinkedHashSet.add("Joey");
        myLinkedHashSet.add("Chandler");
        myLinkedHashSet.add(null);
        myLinkedHashSet.add("Ross");
        myLinkedHashSet.add("Monica");
        myLinkedHashSet.add(null);
        myLinkedHashSet.add("The Ugly Naked Man");
        myLinkedHashSet.add("Ursula");
        myLinkedHashSet.add("Emily");
        System.out.println(myLinkedHashSet);

Here is the console output.

[Joey, Chandler, null, Ross, Monica, The Ugly Naked Man, Ursula, Emily]
4. Non-synchronized

Methods

LinkedHashSet class implements all the methods that are being used in HashSets. You can take a look at my HashSet article to read and learn about them.

Besides, I always recommend you to read the Java documentation for further details. Here is the link to LinkedHashSet class documentation.

Thank you for reading the article. I hope you got a good understanding of LinkedHashSets. If you liked it, drop a like and follow my blog. Stay Safe ✌

HashSets – Java Collections Framework

Hello guys, I am back with our 4th article in my article series regarding the Java Collections Framework. Today I am going to educate you guys about the HashSet class in Java. Let’s get into the article.

Characteristics

HashSet class implements the Set interface in Java. The main thing you need to know about HashSets is that they do not guarantee to keep a certain order. This is one of the reasons why it only has a limited number of methods.

HashSet class is not synchronized. We can add null elements to HashSet. Also, there is a special functionality in HashSets. We can’t add duplicate values to HashSets. If we add a duplicate value, it will automatically overwrite the existing value. The same thing applies even if we try to add a null value.

Let me demonstrate some of the characteristics with some examples.

Does not maintain any order
        //Creating a HashSet
        HashSet myHashSet = new HashSet();

        //Adding Elements
        myHashSet.add("Joey");
        myHashSet.add("Chandler");
        myHashSet.add("Ross");
        myHashSet.add("Monica");
        System.out.println(myHashSet);

        myHashSet.add("Rachel");
        myHashSet.add("Pheobe");
        myHashSet.add(null);
        System.out.println(myHashSet);

        myHashSet.add("Gunther");
        System.out.println(myHashSet);

Here is the console output for the above code snippet.

[Joey, Ross, Chandler, Monica]
[null, Rachel, Pheobe, Joey, Ross, Chandler, Monica]
[null, Gunther, Rachel, Pheobe, Joey, Ross, Chandler, Monica]

As you can see, the null value has come to the beginning of the list, even though we did add elements after adding the null value.

Can’t Add Duplicates
        //Creating a HashSet
        HashSet<String> myHashSet = new HashSet<>();

        //Adding Elements
        myHashSet.add(null);
        myHashSet.add("Joey");
        myHashSet.add("Chandler");
        myHashSet.add("Ross");
        myHashSet.add("Monica");
        myHashSet.add("Monica");
        System.out.println(myHashSet);

        myHashSet.add(null);
        System.out.println(myHashSet);

Here is the console output for this example.

[null, Joey, Ross, Chandler, Monica]
[null, Joey, Ross, Chandler, Monica]

You can clearly see even though we add duplicate elements in the code, there are no duplicates in the list.

Methods

1. boolean add (Element e)

We can add elements to the HashSet using this method. The method will return true if the process was successful. So, if we are trying to add a duplicate element, this will return false since the process was not successful.

2. void clear()

We can clear the whole HashSet using this method.

3. boolean contains (Object obj)

This returns true if the specified object is there in the HashSet.

4. boolean isEmpty()

This returns true if the HashSet is empty

5. boolean remove(Object obj)

If the specified object is present in the list, this remove that element from the HashSet and returns true. If the specified object is not there in the list, this returns false.

6. int size()

This returns the number of elements in the set

You can always refer to Java Documentation for more details.


Alright coders, this ends my article about HashSet class in Java. If you learned something new, drop a like and follow my blog. Stay Safe ✌