Monday, April 28, 2025

Java Tutorial - Returning a Value from Method

The "return" keyword is used in methods to specify the value that the method should produce as output when it is called. The return type of a method determines the type of value that the method can return.

When a method is called, it executes its code and may produce a result. This result can be returned to the calling code using the "return" keyword. The value that is returned can be assigned to a variable or used in an expression in the calling code.

public class Main {	
	
	public static int simpleCalc(int x, int y) {
		int result = x + y;
		return result;
	}
	
	public static void doubleIt(int x, int y) {
		int dResult = (simpleCalc(x, y) * 2);
		System.out.println(dResult);
	}

	public static void main(String[] args) {								
				
		System.out.println(simpleCalc(5, 5));	
		
		doubleIt(5, 5);		
		
	}	
}

Here is a block by block explanation of the code: 

	public static int simpleCalc(int x, int y) {
		int result = x + y;
		return result;
	}

This block defines a static method called "simpleCalc" that takes two integer arguments "x" and "y", adds them together, and returns the result as an integer. 

	public static void doubleIt(int x, int y) {
		int dResult = (simpleCalc(x, y) * 2);
		System.out.println(dResult);
	}

This block defines another static method called "doubleIt" that takes two integer arguments "x" and "y". It calls the "simpleCalc" method with the arguments "x" and "y" to calculate their sum, doubles the result, and prints it to the console. 

	public static void main(String[] args) {								
				
		System.out.println(simpleCalc(5, 5));	
		
		doubleIt(5, 5);		
		
	}	
}

This block defines the "main" method which is the entry point for the program. It contains two lines of code. The first line calls the "simpleCalc" method with arguments 5 and 5 and prints the result to the console. The second line calls the "doubleIt" method with the same arguments and prints the doubled result to the console.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...