Javatpoint Logo
Javatpoint Logo

Nesting Of Methods in Java

In Java, methods and variables that are defined within a class can only be accessed by creating an instance of that class or by using the class name if the methods are static. The dot operator is used to access methods and variables within a class. However, there is an exception to this rule: a method can also be called by another method using the class name, but only if both methods are present in the same class. Efficient code organization and simplified method calls within a class are possible through nesting of methods. Understanding how methods can call other methods within the same class is an important aspect of Java programming.

Syntax:

Example 1:

The program takes input for the length, breadth, and height of a cuboid. The volume method is called first, which in turn calls the area method. The area method then calls the perimeter method. By invoking a series of methods, the output for the cuboid can be obtained for its perimeter, area, and volume.

Filename: NestingMethodsExample1.java

Output:

Length of the rectangle: 24
Breadth of the rectangle: 32
Height of the cuboid: 19
Perimeter: 224
Area: 768
Volume: 14592

Example 2:

The program takes input for two numbers. First, the user is prompted to enter the first number, and then the second number. Then, the program creates an object of the class and calls a method to calculate the product of the two numbers entered by the user by invoking different methods.

Filename: NestingMethodsExample2.java

Output:

Enter first number: 5
Enter second number: 3
Product of 5 and 3 is 8

Example 3:

The input to this program is hardcoded in the main method which calls the main method of the class with arguments. Inside the main method of the class, the swap method is called first to swap the values of x and y, and then the product of x and y is calculated and returned.

Filename: NestingMethodsExample3.java

Output:

Before swap: x = 5, y = 10
After swap: a = 10, b = 5
Product: 50






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA