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 ✌

The Art of Giving Constructive Criticism

Hello guys, in today’s article, I am going to discuss the art of giving constructive criticism. This is going to be one of the most important tools you need especially when you are in a working environment. Have you ever wanted to give constructive criticism, but couldn’t because you didn’t know how to properly convey your idea?

Let me teach you how to do it in 6 simple steps. Let’s hop in.

Why should we learn to give Constructive Criticism?

Constructive criticism is one of the best ways a person can improve. This gives us a new perspective and makes us see the things that we oversaw or didn’t even consider before. Constructive criticism is especially beneficial at work since it shows that your managers and peers care for you and wants to see you succeed.

Everyone makes mistakes. It is really normal to make mistakes in a working environment. What matters is how you are going to point it out. You can either just blame him which would make him feel bad or you could give him constructive criticism. If you wanna go with the second option, let me show you the way.

1. Use the PIP Sandwich

PIP stands for Positive-Improvement-Positive. This means that we are sandwiching our criticism between two positive comments.

So, first of all, you have to start your comment by focusing on your strengths. After that, provide your criticism and point out where he could improve. And you can finish by telling about what positive things he can expect if he acts upon the problem.

You may have seen people use this technique everywhere. For example, judges in reality shows use this technique all the time when commenting on auditions.

When we use this PIP sandwich to give our feedback, they understand that we are on their side. They would understand that we know what they did correctly and that we appreciate it. And they would also understand that you just want them to succeed by correcting their mistakes.

2. Focus on the situation, not the person

This is also one of the most important tips you should definitely consider using. If the person feels like that they are being accused, our criticism is more likely to be dismissed. This happens automatically because the victim feels like they are being targeted.

A simple example is that if someone says, “You look ugly”, we take it personally. But if someone says, “Those clothes don’t suit your body type”, we are more likely to focus on picking out different clothing. These simple things are quite valuable when we want to get our idea across without affecting them negatively.

Using passive voice also can be a great trick to get your idea across. When we use passive voice, we are less likely to mention a person’s name. So, the next time you are confronted with a situation where you have to give someone constructive criticism, try to stick to passive voice.

And also, explaining your side of the story is also a great technique to implement. This way the victim will realize the reason why you decided to speak up. You can tell him how this affected you and your work. The victim will feel guilty and will never repeat that same mistake again.

3. Be Specific

When you are trying to give your constructive criticism, try to be specific as possible. Because when you are specific, the victim is more likely to take action to fix it. When you say something vaguely, the victim won’t know what you really mean. He might even second guess himself about the things he did well. So, try to be specific. Make the process easier and actionable as possible for the victim.

For example, If you say, “Your coding style is bad”, the victim will question his programming knowledge and try to learn more. But he might never understand what you meant. If you specifically say, “You are adding comments properly. Read online resources on how to comment when coding”, he will go ahead and learn that.

4. Comment on what he can change

You have to choose your wording carefully when you are giving your criticism. You have to realize that there are things that are under the victim’s control and things that are out of his control. You need to make sure that you are focusing on and commenting on the issue that is under his control.

If you comment on something that he can’t change, he will keep thinking about it every day which will definitely mess up his workflow.

5. Give Recommendations if possible

When you are giving your constructive criticism, give some recommendations on how he could act upon it. But you should only give recommendations if you have a good enough understanding and experience. Don’t just give him some random recommendations you heard from the internet (but never tried yourself).

For example, if the victim lacks knowledge on some concept, you can recommend the courses, books or the YouTube videos you followed to get better at that concept.

6. Don’t Make Assumptions

This is one of the main things that you should avoid when giving constructive criticism. When you say the things out loud, there is no turning back. So, think twice and verify the sources. You need to have clear evidence to prove what you are going to talk about. This also connects with the point about being specific.

When you are talking about something, you need to be able to pinpoint the exact moment this incident took place. Don’t make your decisions on assumptions. First of all, verify the source and re-check with at least two more ways to verify for sure.


This ends the article. I hope you guys learn something valuable. If you did, drop a like and follow my blog. I’ll end the blog with a quote from an English poet called A. C. Benson.

People seldom refuse help, if one offers it in the right way.

A. C. Benson

What is Video Encoding, Decoding and Transcoding?

Hello coders, today I am going to talk about what is encoding and decoding videos mean. If you have heard about encoding, decoding and codes but have never gone on to find out what it was, let me do it for you. Let’s get into the article

1. Why do we need Video Encoding?

Video Encoding allows us to transmit video content over the internet more easily. Encoding is crucial as it compresses the raw video which reduces the bandwidth. This makes the video keep good quality and transmit easily without bandwidth issues. The main goal we are trying to achieve by encoding is reducing the size of the video without losing much quality. The video encoding process is imposed by codecs. We are going to discuss codecs later in the article.

2. What is Video Encoding?

Webopedia defines video encoding like this.

In video editing and production, video encoding is the process of preparing the video for output, where the digital video is encoded to meet proper formats and specifications for recording and playback through the use of video encoder software. Also called video conversion.

There are two types of video encoding processes. First one is live video encoding. YouTube is the best example of this. The second one is the file-based video encoding.

Firstly, let’s talk about Live video encoding. Live video encoding compresses the large, raw video and audio files so that they use less network bandwidth. This is really important since it is not efficient to send the uncompressed raw video over the internet. We won’t even have a platform like YouTube if we didn’t the video encoding technology.

When we talk about file-based video encoding, we don’t have the need to stream the video. Here the reason why we use encoding is to reduce the size of the video which makes it easier to transport the video from one place to the other.

In addition, re-encoding a video into a different format is also called encoding sometimes.

3. What is Video Decoding?

This is the complete opposite of video encoding. This is the process of uncompressing an encoded video in real-time. The encoded video and audio streams are converted into HDMI to be displayed on our computer screens.

This process is usually done by the video player that you use to watch videos on your laptop. There are some video decoders that can handle multiple input streams as well.

4. What is Video Transcoding?

Video Transcoding is converting an encoded stream from one format to another or from one size to another. So, usually what they do is they decode the stream and re-encodes it into the format we want. This process also can be done live or file-based.

Here the difference is that they are not decoding the encoded stream to the original source. What they do is that they decode the stream into an intermediate format called Mezzanine. Then they convert that stream into the requested format by re-encoding.

5. What are the Codecs and Codec Types?

Codec stands for Coder and Decoder. The codecs are the tools that we use to compress the video files. A codec can be a device or a computer program that encodes or decodes a digital data stream.

Different players support different types of codecs. Have you ever downloaded a video that your player couldn’t play eventually and it asked for you to download a codec pack? Nowadays, the player comes with almost all of the popular codes. Media Player Classic is one of the players that have never failed me in playing a video.

H.264 is the most commonly used video codec. There are several other codec types like MPEG-2, HEVC, VP9, Quicktime and WMV. There are audio codes available like GSM, iLBC, Speex, ITU G.711, LPC10 and etc.


This is it for today’s article guys. Thank you for tuning in. I hope you learned something valuable today. Don’t forget to drop a like and follow my blog. Stay Safe ✌

Learning these 6 Tough Skills will Change your Entire Life

Hello guys, I am back with another interesting article. Today, I am going to talk about 9 skills that are tough to learn which can change the quality of your entire life. If that sounds interesting, let’s hop into the article.

1. Thinking of time as money

Time is Money

Image Source

We all are going to die someday. We all have a limited amount of time on this earth. Everyone knows this. This has become the most overlooked reality ever. If you actually realize this, you won’t be wasting your time anymore.

If we think about the smaller scale, we all have 24 hours in a day. If you don’t know the importance of time and if you don’t know how to manage your time, other people are going to do it for you.

So, if you spend your “free time” watching cat videos on YouTube, you have to rethink of your decisions and how you manage your time. Because the time is going to pass and you are going to age, whether you plan your day or not. But if you don’t take this seriously, you are going to have a lot more regrets in the latter part of your life.

2. Waking up Early

This is another thing that has been so overlooked. There are so many people out there who say that waking up early is not for them and they are more productive at night. And that they can’t just get up early no matter how much they try. But I don’t think any of those people have searched to find the root cause for that.

Most of us are used to use screens the whole day and we usually take our phones to bed. We have no idea how much this is affecting our lives. Just try this experiment for a week.

Stop using screens an hour before bed. Schedule an exact time for getting up and going to sleep. Stop taking mobile phones to bed and don’t your mobile phone as your alarm clock.

Try this for a week, you will realize how much these screens are affecting your sleep cycle. We are doing this mistake over and over again every single day without even thinking.

The biggest benefit that comes from waking up is that you get some alone time. No one is up. You can play your day. You can get a good sweaty workout early in the morning. You can meditate. You can do whatever you want by yourself. This gives you a head start to conquer the daily challenges.

This video might motivate you to get up early.

Video Source

3. Networking

This is especially important for someone who is thinking about being an entrepreneur in the future. Having a good network of people around you is going to help you in the moments you don’t even think. The chances are very low for you to overcome every challenge that comes your way by yourself. You have to learn how to communicate and connect with people.

This doesn’t mean that you have to throw your business card at everyone you meet. The chances are that you already have a network of people around you. You might realize that you are authentic and you can live freely when you are around them. What matters is how strong the bond is between you and the network of people.

If you want to learn more about networking, watch this video about 10 ways to have a better conversation by Celeste Headlee.

10 ways to have a better conversation by Celeste Headlee.

Video Source

4. Planning Everything

Plan your Day The Night Before

Image Source

We all have planned our life events at some time. But working for a schedule when you want is not going to help if you want to succeed in the long run. The time is running out. I am ageing second by second as I type these words. We can’t do everything that is out there in the world. Choose your priorities. Schedule every single event of your day.

One of the arguments people bring is that they can’t simply plan everything and that we can’t predict everything that happens in our lives. I agree with that. It is okay for your plans to change. The point is that you should always have a plan.

Let’s say you were going to write your blog from 3 pm to 6 pm today, and one of your relatives gets hospitalized. You can’t say that I have scheduled this time to write my blog and I can’t come. This is common sense. You have to go. I already talked about how you should prioritize your life. Here what you should simply do is re-schedule. You can push the blogging slot for later at night.

5. Setting short-term goals

Image Source

I am not saying not to have long-term goals. We should have both long-term and short-term goals. The reason why I especially say about short-term goals is that we have to spend a lot of time to achieve our long-term goals.

This picture might look so far away from you. This feeling can demotivate you in a bay way. This is when our short-term goal setting becomes handy. Our short-term goals can be achieved in a smaller time frame. Achieving these goals bring us that dopamine rush which motivates us to keep going.

When you achieve a short-term goal, take a break and celebrate that milestone. This feeling of success will refresh and motivate you for the long journey ahead.

6. Learning to Wind Down

Image Source

Facebook’s COO Sheryl Kara Sandberg turns off her phone at night as a habit. Greek-American author, Arianna Huffington and Bill Gates read books to sleep.

One thing all of these people have in common is that they don’t use electronics in the bedroom. After a long day of work, we have to let our body wind down properly. Staring at computer screens or your smartphone is not to help the cause. Here is an article about the effects of using electronics before sleeping.

Meditation is one of the best ways that you could try out. There are a lot of night time rituals out there on the internet. Pick one for yourself and stick to it. The important is that it should help your body wind down naturally.


I hope you guys enjoyed and learned something valuable from today’s article. If you did, please drop a like and follow my blog. Stay Safe ✌

Movie Ratings and Their Meanings

Hello geeks, today I am going to talk about the film rating system. We are going to take a look at who is rating these movies and movie trailers, movie rating components and what each rating sign mean. If it sounds interesting, let’s hop into the article.

Who is rating the Movies?

Motion Pictures Association (MPA) in the United States is rating suitability of the movies for certain audiences. This is a voluntary scheme and it is not enforced by the law to get your film rated. But some movie theatres refuse to exhibit the movies that are non-rated(NR). Most of the parents are using these ratings to decide whether it is appropriate for children or not.

Movie Rating Types

1. G (General Audience)

People of any age can watch these movies

Jimmy Neutron: Boy Genius

Image Source

2. PG (Parental Guide Suggested)

Children are allowed to watch these movies with parental guidance. This probably means there can be some small parts that might not be appropriate for children.

Image Source

3. PG – 13 (Parental Guide Cautioned)

Parents are urged to be cautious with these movies. Some of the material might not be appropriate for pre-teenagers.

The Half of It

Image Source

4. R (Restricted)

A child under 17 years requires accompanying parent or adult guardian to watch the movie. These movies contains adult material and parents are urged to learn more about the movie before letting their child see it.

Joker

Image Source

5. NC – 17 (Adult Only)

No one 17 or under is admitted. Only for adults. These were also called X Rated Movies in the past.

Concussion

Image Source

6. NR / UR (Not Rated / Unrated)

These movies haven’t been submitted to be rated by the MPA.

Love and Other Drugs

Image Source

Movie Trailer Rating Types

1. Green Band

MPA has rated these movies as green band considering things like foul language, violence, sexual scenes and etc. They have approved these trailers for all audiences.

Green Band

Image Source

2. Yellow Band

These trailers have been approved for age-appropriate internet users.

Image Source

3. Red Band

These trailers have been approved for “mature” and “restricted” audiences.

Red Band

Rating Components

These movies and movie trailers are rated considering 4 components.

  • Language
  • Violence
  • Nudity and Sex
  • Substances (Drug Usage)

I hope guys learned something valuable today. If you did, drop a like and follow my blog. See you next time. Stay Safe ✌

Increase your Dopamine Levels with these simple tips

Hello guys, today I’ve brought you an interesting article on how to increase your dopamine levels without using any medications. Increased dopamine levels will help you to lose weight, be motivated and improve your memory just to make a few.

Let’s learn how you can increase your dopamine levels naturally and thus improve your overall quality in life.

What is Dopamine?

Dopamine is a hormone and a neurotransmitter that is made in your brain which affects many parts of your functions directly.

Why do we need Dopamine?

Dopamine helps us to,

  • Be motivated
  • Feel happy
  • Stay strong mentally
  • Lose weight
  • Fight depression
  • Improve memory
  • Avoid bad habits, etc.

Everyone wants to achieve these things. So, let’s learn how you can urge your brain naturally to keep your dopamine levels high which in return will keep you happy.

1. Give Me Some Sunshine

Image Source

Go outside and feel that sunlight on your skin. Researches have shown that just going for walk in the sunshine is going to increase our dopamine levels.

2. Turn Off Your Smartphone
Blue Light Messes with your sleep

Image Source

Try to stay away from the electronic screen as much as possible. Electronic devices emit radiation that affects our brain’s dopamine production.

I know it is hard for someone who have to work from their laptops and computers in their job to go along with this. Do what you can. Take a break every hour or so and go outside or just look outside through a window. This is going to drastically change your mood and keep you motivated.

3. More Protein. Less Fat. No Sugar
Add Good Proteins to your diet

Image Source

Proteins are made from amino acids which are the root of making dopamine in your brain. Your body can only synthesize 23 types of amino acids. You have to get others from your food. Add more protein sources to your diet to increase your dopamine production.

Having food with saturated fat disrupts dopamine signaling in your brain when you consume them in large quantities. This includes milk and white chocolate, toffee, cakes, puddings, biscuits, processed meat, etc.

Having food with high levels of sugar regularly is not good for you either. This can interfere with your brain’s dopamine centre.

4. Exercise more often

Image Source

Exercising, even just walking or climbing stairs can increase your dopamine production. Exercising boosts endorphin levels in your body and improves your mood too.

5. Sleep tight
Sleep Tight

Image Source

Having a good night’s sleep can help a lot. Dopamine is released in large amounts in the mornings when we are supposed to wake up. This creates that feeling of alertness and wakefulness in our body. And at the evenings, our dopamine levels drops and tells us to go to sleep.

But not having enough sleep could cause problems to this natural rhythm and mess up dopamine production in your brain.

6. Meditate
Meditate Regularly

Image Source

Meditation is a wonderful habit that can do wonders for you. Meditation clears our mind and enables us to focus on our thoughts. Meditation can be done while you are sitting, standing or however you are comfortable and it only take few minutes.

Researches have shown that doing regular meditation can improve your dopamine levels.

7. Tick off your to-do list
Tick off your to-do list items

Image Source

We have talked about this in earlier articles as well. Ticking off things in your to-do list causes a dopamine rush in your brain which motivates you to keep going.


I hope you guys enjoyed the article. Thank you for taking the time to read the article. If you liked it drop a like and follow my blog. Stay safe ✌

List Interface – Special Article 01

Hello guys, as I promised you, today I am bringing you a special article about List Interface in Java. Since we have covered all 3 classes that implement List interface in Java Collections Framework, I thought of giving you guys kind of a summary to help to memorize the concepts better. Let’s get into it.

The 3 classes that implement List Interface in Java Collections Framework are,

  • ArrayList
  • LinkedList
  • Vector

First of all, let’s get some general idea about the List Interface in Java.

  • Lists can contain duplicate elements
  • The elements in the lists can be accessed through a zero-based index.
  • List Interface extends Collection in Java

Let’s learn about the methods that List Interface provides. So, since ArrayList, LinkedList and Vector classes implement List Interface, all of these methods can be used when we are using these 3 classes.

I am going to use ArrayList class to provide examples

1. void add (int index, Object obj)

The object gets added to the specified index in the list. If there is an object in the specified index already, that element is pushed to the next position.

Take a look at this code snippet.

        //Creating an ArrayList
        ArrayList myArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");

        System.out.println(myArrayList);
        myArrayList.add(3, "Rachel");
        System.out.println(myArrayList);

Here is the console output :

[Joey, Chandler, Ross, Monica]
[Joey, Chandler, Ross, Rachel, Monica]
2. void addAll(int index, Collection c)

Here we can add data in some other list into our ArrayList. We can specify an index as from where to start adding the data in the list. If we don’t specify an index, the data will be added to the end of the list. Here is an example.

        //Creating ArrayLists
        ArrayList myArrayList = new ArrayList();
        ArrayList newArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");

        newArrayList.add("Rachel");
        newArrayList.add("Pheobe");

        myArrayList.addAll(newArrayList);
        System.out.println(myArrayList);

Here is the console output :

[Joey, Chandler, Ross, Monica, Rachel, Pheobe]
3. Object get(int index)

Returns the element in the specified index of the list

        //Creating a vector object
        ArrayList myArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");

        System.out.println(myArrayList.get(2));

Here is the console output :

Ross
4. int indexOf (Object obj)

This returns the index of the specified element if it exists. It returns -1 if the element does not exist.

        //Creating a vector object
        ArrayList myArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");

        System.out.println(myArrayList.indexOf("Chandler"));
        System.out.println(myArrayList.indexOf("Rachel"));

Here is the console output :

1
-1
5. int lastIndexOf(Object obj)

Returns the last index of the specified object.

        //Creating an ArrayList
        ArrayList myArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");
        myArrayList.add("Chandler");

        System.out.println(myArrayList);
        System.out.println(myArrayList.lastIndexOf("Chandler"));

Here is the console output :

[Joey, Chandler, Ross, Monica, Chandler]
4
6. Object remove(int index)

This removes the element in the specified index and returns true if the removal process was done successfully.

        //Creating an ArrayList
        ArrayList myArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");
        myArrayList.add("Rachel");

        System.out.println(myArrayList);
        System.out.println(myArrayList.remove("Ross"));
        System.out.println(myArrayList);

Here is the console output :

[Joey, Chandler, Ross, Monica, Rachel]
true
[Joey, Chandler, Monica, Rachel]
7. Object set(int index, Object obj)

This updates the element in the specified index with the given object. And it returns the object that is currently in the specified index.

        //Creating an ArrayList
        ArrayList myArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");
        myArrayList.add("Rachel");

        System.out.println(myArrayList);
        System.out.println(myArrayList.set(2,"Pheobe"));
        System.out.println(myArrayList);

Here is the console output :

[Joey, Chandler, Ross, Monica, Rachel]
Ross
[Joey, Chandler, Pheobe, Monica, Rachel]
8. List subList(int start, int end)

This returns a list from the specified starting index to the specified ending index(Excluding the element in the starting index).

        //Creating an ArrayList
        ArrayList myArrayList = new ArrayList();

        //Adding Elements
        myArrayList.add("Joey");
        myArrayList.add("Chandler");
        myArrayList.add("Ross");
        myArrayList.add("Monica");
        myArrayList.add("Rachel");
        myArrayList.add("Pheobe");

        System.out.println(myArrayList);
        System.out.println(myArrayList.subList(2,4));

Here is the console output :

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

This ends our special article about List Interface in Java. I hope you guys have a much clearer understanding now. If you enjoyed the article, drop a like and follow my blog. I’ll see you guys next time. Stay Safe ✌

Vectors – Java Collections Framework

Hello guys, I am back with my 3rd article in this Java Collections Framework article series. Today, I am going to talk about a class you may not have heard about that often. It is called Vector. Let’s get into the article and explore what Vector can do for us.

What is a Vector?

Vector class implements the List Interface. This reminds me that after this article we will have completed talking about all the classes with Java Collections Framework that implements the List Interface in Java. I am thinking of writing a special article about List Interface next time.

Vector can grow or shrink according to the number of elements just like in an ArrayList. And there is a good reason why we haven’t heard about this class often. This class is not being used in a non-thread environment because it is a synchronized class. This makes the class perform poorly than fellow classes like ArrayLists.

Creating Vector Objects

There are three eligible ways to create a vector object.

1. First Method
Vector myVector = new Vector();

This creates a vector with an initial capacity of 10 elements. And when we insert the 11th element, vector increases its capacity by doubling the current capacity which makes the capacity to 20. Take a look at this code snippet.

        //Creating a vector object
        Vector myVector = new Vector();

        //Adding elements
        myVector.add("1");
        myVector.add("2");
        myVector.add("3");
        myVector.add("4");
        myVector.add("5");
        myVector.add("6");
        myVector.add("7");
        myVector.add("8");
        myVector.add("9");
        myVector.add("10");

        System.out.println("The number of elements is " + myVector.size() + " and the capacity is " + myVector.capacity());
        myVector.add("11");
        System.out.println("The number of elements is " + myVector.size() + " and the capacity is " + myVector.capacity());

Output:

The number of elements is 10 and the capacity is 10
The number of elements is 11 and the capacity is 20
2. Second Method
Vector myVector = new Vector(5);

This creates a vector object with a capacity of 5 elements. And when we insert the 6th element, the capacity will be set to 10 just like in the earlier example. Take a look this code snippet for more clarification

        //Creating a vector object
        Vector myVector = new Vector(5);

        //Adding elements
        myVector.add("1");
        myVector.add("2");
        myVector.add("3");
        myVector.add("4");
        myVector.add("5");

        System.out.println("The number of elements is " + myVector.size() + " and the capacity is " + myVector.capacity());
        myVector.add("6");
        System.out.println("The number of elements is " + myVector.size() + " and the capacity is " + myVector.capacity());

Output:

The number of elements is 5 and the capacity is 5
The number of elements is 6 and the capacity is 10
3. Third Method
Vector myVector = new Vector(5, 10);

This sets the capacity to 5 and capacity increment to 10. Look at this code snippet.

        //Creating a vector object
        Vector myVector = new Vector(5, 10);

        //Adding elements
        myVector.add("1");
        myVector.add("2");
        myVector.add("3");
        myVector.add("4");
        myVector.add("5");

        System.out.println("The number of elements is " + myVector.size() + " and the capacity is " + myVector.capacity());
        myVector.add("6");
        System.out.println("The number of elements is " + myVector.size() + " and the capacity is " + myVector.capacity());

Output:

The number of elements is 5 and the capacity is 5
The number of elements is 6 and the capacity is 15

Adding Elements

        //Adding elements - First Way
        System.out.println(myVector.add("Finch")); //Prints true to the console
        myVector.add("Warner");
        myVector.add("Smith");
        myVector.add("Marnus");
        System.out.println("The list after first set : " + myVector);

        //Adding elements - Second Way
        myVector.add(2, "Marsh"); // Adds Marsh to the 2nd index
        System.out.println("The list after second set : " + myVector);

Output:

true
The list after first set : [Finch, Warner, Smith, Marnus]
The list after second set : [Finch, Warner, Marsh, Smith, Marnus]

Retrieving Elements

        //Getting elements with index
        System.out.println("The person in the 2nd index is : " + myVector.get(2));

Output:

The person in the 2nd index is : Marsh

Removing Elements

        System.out.println(myVector);
        
        //Removing elements from the vector
        System.out.println(myVector.remove("Warner")); // This prints true

        System.out.println(myVector);

Highlighted line prints true to the screen since the removal process was done successfully. Here is the console output :

[Finch, Warner, Marsh, Smith, Marnus]
true
[Finch, Marsh, Smith, Marnus]

Other Useful Methods

1. int capacity()

This returns the current capacity of the vector

2. void clear()

This removes all the elements from the vector

3. boolean contains (Object obj)

This returns true if the specified element is there in the vector

4. Element elementAt(int index)

This returns the element at the specified index of the vector.

5. int indexOf (Object obj, int index)

This returns the index of the first occurrence of a specified object in the vector. And the searching starts from the index we specify. This returns -1 if the element was not found

6. void trimToSize()

This trims the capacity of the vector to its current size


This takes us to the end of the article about Vectors in Java. I hope you guys learned something valuable. If you are new, please follow the blog to receive email notifications when I publish new articles. If you liked the article, go ahead and drop a like and share it among your friends. Stay Safe ✌