Functions & Methods in Java 

Lecture

 

Functions & Return Types
Scope of a Variables
Call Stack
Stack vs Heap Memory
Primitives vs Object References
Garbage Collection
Problems

 

Methods

Methods

A method is a block of code which only runs when it is called.

 

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Example 👨‍💻

public class Main {

  static void sayHi() {
    System.out.println("Hi!");
  }

  public static void main(String[] args) {
    sayHi();
    sayHi();
    sayHi();
  }
}
public class Main {

  static void sayHi(String name) {
    System.out.println("Hi " + name);
  }

  public static void main(String[] args) {
    sayHi("Prateek");
    sayHi("Tarun");
    sayHi("Scaler");
  }
}

Data can be passed to functions using one or more parameters. Parameters can have default values.

public class Main {

  static void sayHi(String name) {
    System.out.println("Hi " + name);
  }

  public static void main(String[] args) {
    sayHi("Prateek");
    sayHi("Tarun");
    sayHi("Scaler");
  }
}

Data can be passed to functions using one or more parameters. Parameters can have default values.

Methods  have Return Types

public class Main {

  static int areaOfSquare(int side) {
    return side*side;
  }

  public static void main(String[] args) {
	int area = areaOfSquare(5);
    System.out.println(area);
  }
}

Data can be returned by functions by specifying the return type and having a return statement inside function.

Why Create Methods.

 

 

  • Methods increase the reusability of code. 
  • Code looks more modular & organised.

Scope of Variable

Scope

In Java, variables are only accessible inside the region they are created. This is called scope.

 

Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared

public class Main {

  public static void main(String[] args) {
    int money = 100;
    if(money>10){
    	int spends = 50;
    }
    System.out.println(spends); //error
  }
}

Block Scope

Block Scope

A block of code may exist on its own or it can belong to an if, while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block's scope.

Function Scope

Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared

Problems-I 🚀 

Write a method to find absolute value of a number.

Problems-II 🚀 

Write methods to convert

- check if a number is prime

- print all primes between A and B

Primitives vs Objects

The Memory View

Objects live on the Heap!

Stack & Heap Memory

Memory

To run an application in an optimal way, JVM divides memory into stack and heap memory.

 

Whenever we declare new variables and objects, call a new method, declare a String, or perform similar operations, JVM designates memory to these operations from either Stack Memory or Heap Space.

Stack Memory

Stack Memory in Java is used for static memory allocation. It contains primitive values that are specific to a method and references to objects referred from the method that are in a heap.

 

Access to this memory is in Last-In-First-Out (LIFO) order. Whenever we call a new method, a new block is created on top of the stack.

 

When the method finishes execution, its corresponding stack frame is flushed, the flow goes back to the calling method, and space becomes available for the next method.

Key Features of Stack Memory

 

  • It grows and shrinks as new methods are called and returned, respectively.
  • Variables inside the stack exist only as long as the method that created them is running.
  • It's automatically allocated and deallocated when the method finishes execution.
  • If this memory is full, Java throws java.lang.StackOverFlowError.
  • Access to this memory is fast when compared to heap memory.

Heap Memory

Heap space is used for the dynamic memory allocation of Java objects at runtime.

 

New objects are always created in heap space, and the references to these objects are stored in stack memory.

 

These objects have global access and we can access them from anywhere in the application

 

 

Heap Memory Features

 

  • If heap space is full, Java throws java.lang.OutOfMemoryError.

 

  • Access to this memory is comparatively slower than stack memory

 

  • This memory, in contrast to stack, isn't automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage.

Garbage Collector!

Garbage Collection deals with finding and deleting the garbage from memory.

 

However, in reality, Garbage Collection tracks each and every object available in the JVM heap space and removes unused ones.

 

 

 

In simple words, GC works in two simple steps known as Mark and Sweep:

 

 

Mark – it is where the garbage collector identifies which pieces of memory are in use and which are not
Sweep – this step removes objects identified during the “mark” phase

Advantages

  • No manual memory allocation/deallocation handling because unused memory space is automatically handled by GC
  • Automatic Memory Leak management (GC on its own can't guarantee the full proof solution to memory leaking, however, it takes care of a good portion of it)

 

Disadvantages

 

  • Since JVM has to keep track of object reference creation/deletion, this activity requires more CPU power than the original application. It may affect the performance of requests which required large memory

 

  • Programmers have no control over the scheduling of CPU time dedicated to freeing objects that are no longer needed

 

  • Automatised memory management will not be as efficient as the proper manual memory allocation/deallocation

Prime Number Print

That's it!

[Java 06] Functions & Memory

By Prateek Narang

[Java 06] Functions & Memory

  • 12