0% found this document useful (0 votes)
4 views16 pages

Understanding Java Methods and Call Stack

Uploaded by

feret75857
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

Understanding Java Methods and Call Stack

Uploaded by

feret75857
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Methods

Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving
both efficiency and organization. All methods in Java must belong to a class. Methods are similar to
functions and expose the behavior of objects.

public class Geeks

{ // An example method

public void printMessage() {

[Link]("Hello, Geeks!");

} public static void main(String[] args) {

// Create an instance of the class

// containing the method

Geeks obj = new Geeks();

// Calling the method

[Link](); }}

Output Hello, Geeks!

Syntax of a Method

Key Components of a Method Declaration

Method consists of a modifier (Define access level), return type (what value returned or void), name
(Define the name of method follows camelCase), parameters (optional inputs), and a body (Write your logic
here).
Method Call Stack in Java

Java is an object-oriented and stack-based programming language where methods play a key role in controlling the
program's execution flow. When a method is called, Java uses an internal structure known as the call stack to manage
execution, variables, and return addresses.

What is the Call Stack

The call stack is a data structure used by the program during runtime to manage method calls and local variables. It
operates in a Last-In-First-Out (LIFO) manner, meaning the last method called is the first one to complete and exit.

How Are Methods Executed

When a method is called:

A new stack frame is added to the call stack to store method details.
The method runs its code.
After execution, the stack frame is removed, and control goes back to the calling method.

Java automatically manages the call stack using the Java Virtual Machine (JVM).

how the method call stack works


public class CallStackExample {public static void D() {

float d = 40.5f;

[Link]("In Method D");

}public static void C() {

double c = 30.5;

[Link]("In Method C");

}public static void B() {

int b = 20;

C(); // Calling C

[Link]("In Method B");

}public static void A() {

int a = 10;

B(); // Calling B

[Link]("In Method A");

}public static void main(String[] args) {

A(); // Start with function A

D(); // Then call D }}

Output

In Method C

In Method B
In Method A

In Method D

Types of Methods in Java – Short Summary

Methods in Java are used to define reusable blocks of code that perform specific tasks.

1. Predefined Methods

Methods already defined in Java class libraries


Also called built-in or standard library methods
Called using [Link]()

Examples:

[Link]() → returns a random value


[Link] → returns value of π

2. User-Defined Methods

Methods written by the programmer


Created to perform custom tasks
Modified according to program requirements

Examples:

sayHello()
greet()
setName()

Ways to Create Methods in Java

1. Instance Method
Accesses instance data
Called using an object
Declared inside a class (without static)

void methodName() { }

2. Static Method

Accesses static data


Belongs to the class
Called using class name
Declared using static

static void methodName() { }

Method Signature

Uniquely identifies a method


Includes:
Method name
Number of parameters
Type of parameters
Order of parameters
Does NOT include return type or exceptions

Example:

max(int x, int y)

Naming a Method

Should start with a verb in lowercase


Use camelCase for multi-word names
Must be unique within a class (unless overloaded)

Examples:

calculateSum()
getName()
setAge()

Calling Different Types of Methods

1. Calling a User-Defined Method

Requires an object (if non-static)

Geeks obj = new Geeks();

[Link]();

2. Calling an Abstract Method


Abstract methods have no body
Must be implemented in a subclass
Called using subclass object

3. Calling Predefined Methods

Available in Java Standard Library


Example:

[Link]();

4. Calling a Static Method

No object required
Called using class name

[Link]();

Key Takeaways

Predefined methods come from Java libraries


User-defined methods are programmer-written
Instance methods need objects
Static methods do not need objects
Method signature helps method overloading
Proper naming improves readability and maintainability

Static Method vs Instance Method in Java

methods define the behavior of classes and objects. Understanding the difference between static methods
and instance methods is essential for writing clean and efficient code.

What is a Static Method?

A static method belongs to the class rather than any specific object.

Can be called without creating an instance of the class.


Since static methods are not object-specific, they can access only static members (data and
methods), and cannot access non-static members.

import [Link].*;

class Geeks {// static method

public static void greet() { [Link]("Hello Geek!");}

public static void main(String[] args) {

// calling the method directily

greet();

// using the class name

[Link](); }}

Output

Hello Geek!

Hello Geek!

What is an Instance Method?

An Instance method belongs to an object.

Need to create an instance of the class to call.


Can access instance variables, other instance methods, and static members of the class.
Have access to this reference, which points to the current object.

import [Link].*;
class Test {

String n = "";

// Instance method

public void test(String n) {

this.n = n; }}

class Geeks {

public static void main(String[] args) {

// create an instance of the class

Test t = new Test(); // calling an instance method in the class 'Geeks'

[Link]("GeeksforGeeks");

[Link](t.n); }}

Output

GeeksforGeeks

Access Modifiers in Java

In Java, access modifiers are essential tools that define how the members of a class, like variables,
methods, and even the class itself, can be accessed from other parts of our program.

There are 4 types of access modifiers available in Java:

Private Access Modifier


The private access modifier is specified using the keyword private. The methods or data members declared
as private are accessible only within the class in which they are declared.

class Person {// private variable

private String name;

public void setName(String name) { [Link] = name; // accessible within class

} public String getName() { return name; }}


public class Geeks {

public static void main(String[] args){

Person p = new Person();

[Link]("Alice");

// [Link]([Link]); // Error: 'name'

// has private access

[Link]([Link]()); }}

Output

Alice

Default Access Modifier


When no access modifier is specified for a class, method, or data member, it is said to have the default
access modifier by default. This means only classes within the same package can access it.

class Car {

String model; // default access

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

Car c = new Car();

[Link] = "Tesla"; // accessible within the same package

[Link]([Link]);}}

Output

Tesla

[Link]: Default class within the same package

// default access modifier

package p1;// Class Geek is having // Default access modifier

class Geek { void display() { [Link]("Hello World!"); }}

[Link]: Default class from a different package (for contrast)

// package with default modifier


package p2;

import p1.*; // importing package p1// This class is having // default access modifier

class GeekNew {

public static void main(String args[]) {

// Accessing class Geek from package p1

Geek o = new Geek();

[Link](); } }

Protected Access Modifier

The protected access modifier is specified using the keyword protected. The methods or data members
declared as protected are accessible within the same package or subclasses in different packages.

class Vehicle {protected int speed; // protected member

}class Bike extends Vehicle {

void setSpeed(int s){speed = s; // accessible in subclass }

int getSpeed(){

return speed; // accessible in subclass }}

public class Main {

public static void main(String[] args){

Bike b = new Bike();

[Link](100);

[Link]("Access via subclass method: "+ [Link]());

Vehicle v = new Vehicle();

[Link]([Link]); }}

Output

Access via subclass method: 100

Public Access Modifier


The public access modifier is specified using the keyword public. Public members are accessible from
everywhere in the program. There is no restriction on the scope of public data members.

class MathUtils { public static int add(int a, int b) {

return a + b; }}

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

[Link]([Link](5, 10)); // accessible anywhere }}

Output

15

Explanation: add() is globally accessible due to the public modifier.

Top-level classes or interfaces can not be declared as private because, private means "only visible within
the enclosing class".

Comparison Table of Access Modifiers in Java

When to Use Each Access Modifier in Real-World Projects

Private: The idea should be use as restrictive access as possible, so private should be used as much as
possible.
Default (Package-Private): Often used in package-scoped utilities or helper classes.
Protected: Commonly used in inheritance-based designs like framework extensions.
Public: This is used for API endpoints, service classes, or utility methods shared across different parts
of an application.

Command Line Arguments in Java

Java command-line argument is an argument, i.e., passed at the time of running the Java
program. Command-line arguments passed from the console can be received by the Java
program and used as input.

Example:

java Geeks Hello World


Note: Here, the words Hello and World are the command-line arguments. JVM will collect
these words and will pass these arguments to the main method as an array of strings
called args. The JVM passes these arguments to the program inside args[0] and args[1].

Example: In this example, we are going to print a simple argument in the command line.

// Java Program to Illustrate First Argument

class GFG{public static void main(String[] args) { // Printing the first argument

[Link](args[0]); }}

Output

Why Use Command Line Arguments?

It is used because it allows us to provide input at runtime without modifying the whole program.
It helps to run programs automatically by giving them the needed information from outside.

Working of Command-Line Arguments

Command-line arguments in Java are space-separated values passed to the main(String[] args)
method.
JVM wraps them into the args[] array, where each value is stored as a string (e.g., args[0], args[1], etc.).
The number of arguments can be checked using [Link].

Example: Display Command-Line Arguments Passed to a Java Program

To compile and run a Java program in the command prompt, follow the steps written below.

Save the program as [Link]


Open the command prompt window and compile the program- javac [Link]
After a successful compilation of the program, run the following command by writing the arguments-
java Hello
For example - java Hello Geeks at GeeksforGeeks
Press Enter and you will get the desired output.

class Geeks { // Main driver method

public static void main(String[] args) { // Checking if length of args array is // greater than 0
if ([Link] > 0) { // Print statements [Link]("The command line" + " arguments are:");

// Iterating the args array // using for each loop

for (String val : args) [Link](val); }

else [Link]("No command line " + "arguments found.")}}

Output:

Variable Arguments (Varargs) in Java

In Java, Variable Arguments (Varargs) allow methods that can take any number of inputs, which simply
means we do not have to create more methods for different numbers of parameters. This concept was
introduced in Java 5 to make coding easier. Instead of passing arrays or multiple methods, we can
simply use one method, and it will handle all the input cases.

Example: Now, let us see the demonstration of using Varargs in Java to pass a variable number
of arguments to a method.

import [Link].*;

class Geeks { // Method that accepts variable number of String arguments using varargs

public static void Names(String... n) { // Iterate through the array and print each name

for (String i : n) {[Link](i + " "); }

[Link](); }public static void main(String[] args) {

// Calling the 'Names' method with different number of arguments

Names("geek1", "geek2");

Names("geek1", "geek2", "geek3"); }}

Output

geek1 geek2

geek1 geek2 geek3


What is Varargs?

Varargs lets a method to take many values or even no value at all. Java will treat these values
like a list, so that we can use them inside the method easily.

Syntax:

Internally, the Varargs method is implemented by using the single dimensions arrays concept.
Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length
argument is specified by three periods or dots(…).

public static void fun(int ... a)


{
// method body
}

This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result,
here, a is implicitly declared as an array of type int[].

Why do we Need Varargs?

Until JDK 4, we can not declare a method with variable no. of arguments. If there is any
change in the number of arguments, we have to declare a new method. This approach
increases the length of the code and reduces readability.
Before JDK 5, variable-length arguments could be handled in two ways. One uses an
overloaded method(one for each). Another puts the arguments into an array and then
passes this array to the method. Both of them are potentially error-prone and require
more code.
To resolve these problems, Variable Arguments (Varargs) were introduced in JDK 5. From
JDK 5 onwards, we can declare a method with a variable number of arguments. Such types
of methods are called Varargs methods. The varargs feature offers a simpler, better option.

Example: Demonstrating the working of varargs with integer argument

class Geeks {// A method that takes variable number of integer arguments.

static void fun(int... a){ [Link]("Number of arguments: " + [Link]);

​// using for each loop to display contents of a

for (int i : a)

[Link](i + " ");

[Link](); } // Driver code

public static void main(String args[]){// Calling the varargs method with one parameter
fun(100);// four parameters

fun(1, 2, 3, 4); // no parameter

fun(); }}

Output

Number of arguments: 1

100

Number of arguments: 4

1234

Number of arguments: 0

Note: A method can have variable length parameters with other parameters too, but one
should ensure that there exists only one varargs parameter that should be written last in the
parameter list of the method declaration. For example:

int nums(int a, float b, double … c)

In this case, the first two arguments are matched with the first two parameters, and the
remaining arguments belong to c.

Example: Varargs with Other Arguments

class Geeks{

// Takes string as a argument followed by varargs

static void fun2(String s, int... a) {[Link]("String: " + s);

[Link]("Number of arguments is: " + [Link]);// using for each loop to display contents of a

for (int i : a) [Link](i + " ");

[Link](); }

public static void main(String args[]) {// Calling fun2() with different parameter

fun2("GeeksforGeeks", 100, 200);

fun2("CSPortal", 1, 2, 3, 4, 5);

fun2("forGeeks"); }}

Output
String: GeeksforGeeks

Number of arguments is: 2

100 200

String: CSPortal

Number of arguments is: 5

12345

String: forGeeks

Number of arguments is: 0

Important Rules and Limitations

Case 1: Specifying two Varargs in a single method:

void method(String... gfg, int... q)


{
// Compile time error as there
// are two varargs
}

Note: Only one Varargs parameter is allowed per method.

Case 2: Specifying Varargs as the first parameter of the method instead of the last one:

void method(int... gfg, String q)


{
// Compile time error as vararg
// appear before normal argument
}

You might also like