Latest Posts

Thursday, July 8, 2021

Memory Management in JAVA

One of the most important features of Java is its memory management. Since Java uses automatic memory management, it becomes superior to those languages that do rely on programmers for their memory management. Having said that, although Java automates its memory management, it is very important to understand the functionality so that we do not end up in a situation where we start blaming JAVA for any out of memory because of our coding issues.

When we say JAVA memory, we mean JVM memory. JVM primarily defines 5 run-time data areas which are used in program execution:

Method Area | Heap Memory | Stack | PC Registers | Native Method Stack


Let us try to understand each one of them and the linkage between them:

1. Method Area:

  • All the class data is available in the method area. 
  • Corresponding static variables associated with the class are also part of the Method Area.
  • Its size can be customized as peruse.
  • Apart from the class data, it also stores superclass name, interface name, and constructors information
  • If the memory in the method area can not satisfy an allocation request, JVM throws an OutOfMemoryError.

2. Heap Area:

  • All the object data is available in the Heap area.
  • The instance variable will also be stored in Heap Area. 
  • It is very important for a programmer to understand the Heap Area as all the object-level information is present here and garbage collection keeps a check for this area only.
  • Its size can be customized as per need.
  • Heap is further divided into few parts which we will be discussing in detail along with garbage collection in our next blog.
  • If more heap is required for the storage management system, JVM throws an OutOfMemoryError.

3. Stack Area:

  • For every thread, a separate run-time stack is created and is stored in Stack Area. 
  • Thus, if we have "n" number of threads, "n" number of stacks will be created and will be stored in the stack area.
  • Further, each entry in each stack contains three parts i.e. Local variable array, operand stack, and Frame data, and these three are collectively known as a stack frame.
  • If more JVM stack memory is required than is permitted, JVM throws a StackOverflowError. On the other hand, if JVM tried to expand the Stack memory or if there is a shortage of memory during initial JVM stack creation for a new thread, JVM throws OutOfMemoryError.

Relation between Stack and Heap:

1
String s = new String("abc");

  • In the above syntax, an object of type String and value "abc" will be created in the Heap area. 
  • "s" will be created in Stack which will refer to the object created in the Heap area.

4. PC Registers:

  • For each thread, a stack is created in the stack area and a PC register is created in PC Registers memory. 
  • Thus, if we have "n" number of threads, then again "n" number of stacks will be created in the stack area, and "n" number of PC registers will also be created. 
  • It holds the address of the currently executing instruction and it moves to the next instruction once the current instruction is executed.

Relation between Stack Area and PC Registers:

  • For each thread created in Stack Area, a program counter is associated with it.
  • PC register stores the address of the current running instruction.

5. Native Method Stack:

  • It is similar to Stack Area but the difference is that the native methods of JAVA are stored in this area. 
  • If we deep dive into the architecture of JVM, we will find that there is a JNI (Java Native Interface) which deals with all the native methods.
  • If more JVM native stack memory is required than is permitted, JVM throws a StackOverflowError. On the other hand, if JVM tried to expand the native stack memory or if there is a shortage of memory during the initial creation for a new thread, JVM throws OutOfMemoryError.



Wednesday, July 7, 2021

Compile Time and Run Time Polymorphism | Method Overloading and Method Overriding

Polymorphism can be divide into poly + morphs which are greek words and means many forms. In Java, a concept via which we can perform the same job in different ways is known as polymorphism. It can be further divided into compile-time polymorphism and run-time polymorphism. Let us have a look at each of them:

1. Compile time polymorphism (Method Overloading):

Whenever the object is assigned the functionality at compile-time, it is known as compile-time polymorphism. It is achieved via Method overloading in java. Method overloading is a concept in which two methods of a class have the same signature but different parameters. For Example:

If we have a class called AutoPace, and we wanted to declare a method as 

public void study(String subject)

We can declare the "study" method only once with the argument as "String". But in case we need some additional functionality, say we need to pass the time duration for the study method as well, we can achieve it with method overloading by declaring another "study" method and changing the argument to: 

public void study(String subject, int duration)

The class will look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class AutoPace{

	public static void study(String subject){
		System.out.println("Lets study: " + subject);
	}

	public static void study(String subject, int duration){
		System.out.println("Let's study : " + subject + " for next " + duration + " hours");
	}

	public static void main(String args[]){
		study("Java"); //Lets study: Java
		study("Java", 2); //"Let's study : Java for next 2 hours"
	}

}


Few more conecpts of Compile Time Polymorphis when dealing with int -> long -> float -> double:

Next, let us have a look at few method calls and try to understand their output:

Case 1:

Let's assume we have couple of methods in a class say:

1
2
3
4
5
6
7
public int sum(int i, int j){

	System.out.println("Integers arguments called")

	return i+j;

}

and, 

1
2
3
4
5
public long sum(long i, long j){
	System.out.println("Long arguments called")
	return i+j;
}

This is a case of polymorphism as the arguments are different for the method "sum". In this case, if we call method sum from the main class, something like: 

sum(1,2) -> Since the arguments are integers, the first method will be called and the output will be printed as "Integers arguments called".

Case 2:

Next, let us assume that only one method is available i.e.

1
2
3
4
5
6
7
public long sum(long i, long j){

	Systemout.println("long argument called");

	return i+j;

}

and let's make the same call as the first one i.e. sum(1,2) -> In this case, even if the passed parameters are (int,int) and the corresponding method is not available, it will pass on to the next method which will accept (long,long).

Note: The hierarchy followed in this case should be int -> long -> float -> double i.e. for any lower arguments passed as a parameter if the appropriate argument method is not available it will check for the higher-order argument.

Case 3:

Next, let's try to understand the behavior if we will try to write a couple of methods like:

1
2
3
4
5
6
7
8
public int sum(int i, int j){
  return i+j;
}


public long sum(int i, int j){
  return i+j;
}

In this case, the method name and parameters are the same, but the return type is different. But, this is not a valid scenario as the method signature is the same and the return type doesn't play any role in method overloading. Hence, it will throw an error.

Case 4: 

Next, let us try to understand the behavior if we will try to write a couple of methods like:

1
2
3
4
5
6
7
public int sum(int i, long j){
  return i+j;
}

public int sum(long i, int j){
  return i+j;
}

In this case, the method name is the same but the parameters are different as they are in a different order. One can argue that this is following method overloading, but since we are dealing with int and long type, this is an error. 

To understand it better, let us try to understand what happens if someone tries to call sum(1,2) from the main method. 

It will get confused between both the sum methods and will not be able to figure out which method to call and will throw an error stating that the method is ambiguous.


2. Run-Time Polymorphism (Run-Time Polymorphism):

Whenever the object is assigned the functionality at run-time, it is known as run-time polymorphism. It is achieved via Method overriding in java. Method overriding is a concept in which two methods can have the same signature but different definitions. It can be achieved by the use of the parent-child class relationship. For example:

If we have a class HatchBack with a method carSegment, something like:

1
2
3
4
5
public class HatchBack{
 public void carSegment(){
  System.out.println("This is a hatchback car")
 }
}

But let's suppose there is a child class known as Maruti that wants to extend the HatchBack class for its hatchback segments of cars. In this case, they can override the carSegment and update the definition of the method by:

1
2
3
4
5
6
public class Maruti extends HatchBack{
  @Override
  public void carSegment(){
    System.out.println("This is a maruti hatchback car.")
  }
}

In this case, the Maruti class has overridden the functionality of carSegment method and this polymorphism can be achieved at run-time as one can decide which object to instantiate during run-time. Complete implementation of Run-Time Polymorphism:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class HatchBack {
 
    public void carSegment()
    {
        System.out.println("This is a hatchback car");
    }
}
 
public class Maruti extends HatchBack {
 
    public void carSegment()
    {
        System.out.println("This is a maruti hatchback car.");
    }
 
    // Main Code
    public static void main(String args[])
    {
        HatchBack hatchBack = new Maruti();
        hatchBack.carSegment(); //This is a maruti hatchback car.
    }
}

Thursday, June 3, 2021

ETMONEY - Invest in Mutual Funds

 ETMONEY - Invest in Mutual Funds

This post is in continuation to the previous post where we discussed about starting to invest in mutual funds using the ETMONEY  platform. If you haven't gone through the previous post, I would strongly recommend going through the post first - All You Need to Know to Start Investing

How to select which fund to invest in? For this, if you open any fund , you will land on the homepage of that fund like below:


You can look through different insights about the fund here to understand how is the fund performing till now before proceeding with your investment. I will be discussing those in details in this blog post.

The below image shows the top section of the page which contains an overview of the fund Like the fund category, the start of duns, the motive and businesses it invests in.


Next, we can see a graph just below this section. This graph is very insightful, as we have the option to compare the returns of this fund with avg of the category in which the fund falls into in different intervals of time. I would suggest to make use of this as much as possible. Based on your goals you can check whether it would be beneficial to invest in this fund or any other fund of this category.

Just next to the side of this graph, we have the below section where we can get the information about the fund expense ratio, fund size, fund age etc.[refer image below]

The Fund Analysis and Investment Strategy Section are purely based on ETMONEY's market research related to the fund.

Fund Analysis - This section grades funds based on the risk, returns and consistency. 

Investment Strategy - This section has a small investment strategy given, in case you feel like investing in this fund.[refer the image below]



Furthermore, if we scroll down, we can see Investments Return Calculator and fund investment distribution under Large Asset & Portfolio Allocation section. 

Investments Return Calculator - calculate your returns based on the investment amount and the duration you would like to invest.This calculator, we get in the home page of each and every fund.

Large Asset & Portfolio Allocation - shows the holdings in which this fund is currently investing.

I would like to highlight one more section here - Comparison with Funds. With this section, it becomes very easy to drill down to a fund by comparing the performance of the funds falling under the same category that is collated in this section.[refer the image below]


We are also given with a Riskometer to let you know the risk you would be having by investing in this fund.

 Further we can see Fund Details like address, fund manager and a FAQ section, if you still have some unanswered questions, you can refer the FAQ section. 

Hope after reading this article, you would get a good idea of this platform and can start investing in Mutual Funds. 


Tuesday, June 1, 2021

Reverse Linked List

Each element of the linked list consists of two parameters i.e. the value of the element and the address of the next element in the linked list. When we talk about reversing the linked list, we mainly focus on manipulating the address of the next linked list for each element. 

If we observe the above figure while reversing the linked list, we didn't reverse the value of each element rather we reversed the address of the next element of each element in the linked list. 

To execute this, we can make use of three pointers, the main pointer will iterate throughout the linked list, and the other two pointers will help in reversing the address of the next element in the linked list. Let's have a look at the below logic to reverse the linked list:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
ListElement main = head;
ListElement prev = null;
ListElement next = null;
while (main != null) {
    next = main.next;
    main.next = prev;
    prev = main;
    main = next;
}
head = prev;
return head;

In the above logic, ListElement is the object for an element of the linked list which contains the value and the address of the next element. We will start by declaring three pointers, i.e. main, prev, and next.

Next, the while loop will help us to iterate through the list, let us have a look at the first iteration:
If we observe here, at step 3 of the iteration, the linkage between the first and second element became null and the prev pointer is pointing to the first element so that we can point back the second element to the first element in the second iteration and reverse the first two elements.  Let's have a look at the second iteration:

            
Again after the second iteration, the second element is pointing to the first element of the linked list, and the first two elements are reversed at Step 2. Also, while the second element starts pointing to the first element, the linkage between the second element and the third element became null and is set to reverse in the third iteration. Let's have a look at the third iteration:
            
After the third iteration, the second and third elements are reversed and the last element is pointing to null. This will eventually point to the third element in the fourth iteration with the help of the prev pointer. Let us have a look at the fourth iteration:
                
Eventually, after the fourth iteration, all the elements will point in the reverse direction and the next and main pointers will become null. Since the main pointer becomes null, the iterations will stop. The only thing left is to point the head correctly. Since the linked list is reversed, the head should point to the last element of the original linked list. This can be achieved with the help of the prev pointer again. We can simply assign head = prev after the iterations are completed and return the new head of the reversed link list.
The above logic will help in reversing the linked list.







Contact Form

Name

Email *

Message *

Latest Post

Memory Management in JAVA

One of the most important features of Java is its memory management. Since Java uses automatic memory management, it becomes superior to tho...

Popular Posts