# Memory Management in Java : Basics

This post will answer the questions like -

1. What is static memory allocation?
    
2. What is Dynamic memory allocation?
    
3. What is compile-time?
    
4. What is run-time?
    
5. What are strongly-typed languages and weakly-typed languages?
    

This post will also talk about the memory allocation concept of Java.

So let's begin, and get two basic questions out of the way -

## Compile-time

It’s the prior stage wherein code is converted to execution form. In java, `.java` files are converted to .class files in this stage by the `javac` compiler. This is how we compile a code in java.

```plaintext
javac fileName.java
```

Now, the above code will generate `.class` files same as the number of classes you wrote in the code. It converts the java code to bytecode that is closer to native machine language.

## Run-time

It’s the second stage wherein the .class file is getting executed. Here the java compiler present in the JVM (Java Virtual Machine) will convert this .class file (bytecode) to machine code (10101....) that our processor understands.

You do this by the following command -

```plaintext
java fileName // omit the .class
```

By doing this, the output of your code will be printed on the console window of your terminal.

Now, let's talk about *static memory allocation*.

## Static Memory Allocation

Memory allocated during the compile time is called **static memory allocation**. The memory allocated is fixed or cannot be changed during run-time.

```java
public void getValue {

    int [] array = {1,2,3,4,5}; // this is static memory allocation.

    }
```

## Drawbacks of static memory allocation

Size is fixed and cannot be increased or decreased during runtime. If we have assigned a huge size and do not use it fully then, we will end up wasting the memory or in the opposite case, we will run out of memory which is called **Stack Overflow**. Thus *Dynamic Memory allocation* concept came into the picture.

Operating System assigns memory to a particular application or a program and below is the architecture of memory.

![Memory assigned to a program](https://cdn.hashnode.com/res/hashnode/image/upload/v1656271410264/GNPCCJC-o.png align="center")

As shown in the above diagram, memory is divided into 04 segments — Heap, Stack, Static/Global (we will talk about this in another post) and Code/Instructions.

## Stack

Functions and local variables are stored in stack. A small segment of stack memory is assigned to `main()` method which is also called *stack-frame* as shown below.

Let's take an example to understand this thoroughly -

```java
// function with local variables a,b and z
public class DynamicMemory {
    public int getSum(int a, int b) { 
      int z = a + b;
      return z;
    }

    public static void main(String[] args) {
      
      DynamicMemory obj = new DynamicMemory();
      
      int x = 10;
      int y = 20;
      int sum = obj.getSum(x, y);
      
      System.out.println(“sum of 02 nos.= “ +sum);
  }
}
```

Steps of execution of this program -

1. `main()` method along with local variables x,y, and z will be stored in stack in stack-frame memory area.
    
2. `getSum()` function and its local variables a and b will be stored in stack.
    
3. Now main function is paused until `getSum()` function is executed and returns a value.
    
4. Once `getSum()` function is executed and returns a value, it will be erased from stack-frame and `main()` method will be into picture.
    
5. Once `main()` is also executed, it will be erased from stack. Now stack is empty.
    

This concept is essential for *Recursion*.

**Stack stores the data until the function is executed.**

## Heap

The process of allocating memory during the run time or at the time of execution is called **Dynamic Memory Allocation**.

Heap is the segment of memory where dynamic memory allocation takes place. Unlike stack where memory is allocated and de-allocated in defined order as seen above, heap is the memory segment where allocation and de-allocation happen randomly.

**Objects and Instance variables are stored in Heap area.**

```java
DynamicMemory obj = new DynamicMemory(); // it will be stored in heap memory
```

### new keyword

`new` keyword does three things in a java program -

1. It will reserve a memory space in the heap area and will load all the non-static members into this area.
    
2. It will assign the location address of this memory area to the object. (In this case obj).
    
3. If you are not assigning any value to the fields (variables) then, `new` will assign default values to these variables.
    

## Strongly and Weakly typed language

Let's put it out one final time - Java is a strongly and statically typed language.

On the other hand, JavaScript is a weakly and dynamically typed language.

**Strongly typed language** -

Strongly typed language means that once you have declared a variable with a particular data type, you cannot assign some other type of data to that variable. The compiler will throw a compile-time error of mismatch type.

Eg -

```java
int numA = 10;
byte numB = 1;

int numC = numB; // this will be done implicitly

// Java is a strongly-typed language

byte numD = numA; // this will throw a compile-time error

byte numD = (byte) numA; // correct code

int numC = "Hello World";
// this is wrong code as you are assigning a String to a int variable.
```

In other words, the compiler will not do implicit type conversion when you assign a 'wider' data to a 'narrower' data type variable, or a different type of data to that variable. You would have to do the narrow type casting explicitly, or make a different variable.

On the other hand, with Java, widening type casting will be done implicitly by the compiler.

**Weakly typed language** -

Weakly typed language means that compiler will make the conversion between unrelated datatypes automatically.

Eg -

```javascript
variable = 21;
variable = variable + "String";
console.log(variable);    // will not throw error.
```

### Statically and Dynamically typed language

**Statically-typed** programming languages do *type checking* (i.e., the process of verifying and enforcing the constraints of types on values) at *compile time*, whereas **dynamically-typed** languages do type checks at *runtime*.

This means for statically typed languages you have to assign the type of data at compile time, and for dynamically typed languages, the data type is resolved at runtime.

```javascript
let num = 10;    // dynamically typed -> JavaScript
```

```java
int num = 10;    // statically typed -> Java
```

C and C++ are static and weak typed.

Python is strong and dynamic typed.

That's it for my first post. Will be talking more about Java memory management in a series of other articles. Thank you and bye for now. Keep Learning !
