CodeByAkram: Java
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

What is Polymorphism in Java with example


What is Polymorphism in Java with example.

Polymorphism is one of the most important concept of OOPS that means "one object having many forms".

Polymorphism is a Greek word which means "Many Forms", Polymorphism = (Poly + Morphism) = Many + Forms.

 Lets understand above line in more details with example.

Every concept of OOPS also exist in Real Life, so for better understanding lets first understand real life example of Polymorphism.


Real Life example

There are many English words when used without context will have multiple meanings.
Example:

If I don't give you context and simply say word, you will not able to exactly tell what it is used for.

bear:
    • bear can be used to represent a mammal "The black bear". 
    • bear can also be used in context of pain like "I cannot bear his constant criticism".
Similarly,

close:
    • close can be used in context of opposite of far like "Please close the window".
    • close can also be used in context of opposite of open like "Please close the door".
So many words in English has multiple meanings that is "same word but multiple meanings".
Isn't it matching with our Polymorphism definition "same object many forms"!!!


In Java

Similarly in Java, there can be a situation where we need to write more than one methods with same name (because they all do the same job) but they behave differently based on the parameters supplied.

Lets take an example:


  1. getSum(int a, int b) { return a+b; } used to calculate the sum of two integer number.
  2. getSub(int a, int b, int c) { return a+b+c; } used to calculate the sum of three integer number.

If you look at above two method names "getSum", they both are doing same job of calculating sum of integer numbers, so given only name, you cannot say, whether method is used to calculate sum of two or three numbers. but you will definitely get a broad idea that method is used to calculate the sum.

Parameters supplied to the method will give the exact meaning to the method. whether it is used to calculate sum of two numbers or three numbers.

We can achieve Polymorphism in Java by,
  1. Method Overloading
  2. Method Overriding.


Another example of Polymorphism,
We use "System.out.println()" method and passed int, float, String, Object etc as a parameter like,
System.out.println(10) -> 10
System.out.println("hello") -> hello
System.out.println(50.5) -> 50.5
same method name println(), can sometime print integer, sometime float, sometime String etc.

Internally there are multiple println() method written as shown below,



What is Thread in Java

What is Thread in Java?


Java Thread is an independent path of execution within a program which can run in parallel with other existing Threads.

Now lets talk about Process.

A process is a self contained execution environment and it can be seen as a program. However a program itself contains multiple processes inside it. Java runtime environment runs as a single process which contains different classes and programs as processes.

So we can say that, thread can be light weight process because it require less resources and also multiple threads can share the same resource. Java provides built-in support for multi-threaded programming.

Let’s summarize  in points:

1. The main purpose of multi-threading is to provide simultaneous execution of two or more parts of a program. Each such part of a program called thread.

2. Threads are lightweight processes, they share the common memory space. 

3. In Multi threaded environment, programs that are benefited from multi-threading, utilize the maximum CPU time so that the idle time can be kept to minimum.

Now lets talk about the state of a thread. Thread can be in one of the following states:-

NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
WAITING – A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING – A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED – A thread that has exited is in this state.
A thread can be in only one state at a given point in time.








Simple Deadlock Explanation

Deadlock Explanation with Example.


Deadlock means, it is a situation where 2 or more threads are blocked and waiting for each other.

Let's take an example, in the office we have shared printer and scanner where employees has ability to do scanning and printing.

1. Deepak has bunch of documents that it wants to print first and also want to take a scan later.
(Print and Scan)
2. Rohit has bunch of documents that it wants to scan first and also want to take a print later.
(Scan and Print)

Thread 1 ------ (Got Printer) ------ (Need to Scan) (Blocked)
Thread 2 -------(Got Scanner) -----(Need to Print) (Blocked)


Reverse Integer in Java.

Algorithm 


Reversing Integer is very easy, start collecting the digits from the back of the number until no digits is remaining.

How we will get the last digit of a number?
when a number is Mod by 10, we will get the last digit of a number. 
Example  int lastDigit = number % 10.

We just collected the last digit, so now we need to get the remaining number to work on except the last digit which we already worked on, how we will get the remaining number except last digit?
By dividing the number by 10. Example: int remainingNumber = number / 10.

We need to collect all the last digits we get in reverse order, how to do that?
int reversedNumber = reversedNumber * 10 + lastDigit;

Continue above steps in loop  until remaining number is 0.

Note: We may hit integer overflow when we do (reversedNumber * 10 + lastDigit), so make sure before executing that line we check for overflow.

1. reversedNumber * 10 can overflow, so check reversedNumber  > Integer.MAX_VALUE / 10, if yes then (reversedNumber * 10) will surely overflow.

2. reversedNumber * 10 + lastDigit
Adding the + lastDigit can also overflow, if reversedNumber is exactly equal to Integer.MAX_VALUE / 10 then we need to check the + lastDigit we add should be less that 7 (for positive number) because in Java, the integer ranges from -2,147,483,648 to +2,147,483,647 and greater than -8 in case negative number.