Java Program to Illustrate a Method without Parameters But with Return Type
The task is to illustrate a method that does not contain any parameter but should return some value. Methods are used to break a complete program into a number of modules that can be executed one by one. Considering any random shape to illustrate: Circle
Example: First a class named ‘Circle’ is supposed to be created, then with the help of this class, it can calculate the area and circumference of a circle.
- Area calculation
- Circumference calculation
Inside the class Circle, we will declare a variable called radius to take the value of the radius from the user so that by using this value of radius we will be able to calculate the area and circumference of a circle. Now, for calculating the area and circumference, we need to create two separate methods called area() and circumference(), which does not take any value as a parameter but will definitely return some value, and the value which this method will return are the final values of area and circumference of the circle. The methods will return the values after calculating it with the help of the values of variables. The most important thing to calculate the area and circumference, and to use these methods are first to need is to call those methods which are known as calling a function, for this we have to create an object of Circle class because in the main method, and we want to access them, methods of another class hence we need to make the object of that class which contains our methods area() and circumference() and by using the object of the class Circle, we will easily call the methods and those methods will return some value, and we will display it by using our predefined function.
Syntax:
class name
{
datatype MethodName()
{
statements....
..
..
return value;
}
}
Implementation:
Example 1: Area calculation
Java
import java.util.*;
import java.util.Scanner;
class Circle {
double radius;
double area()
{
double r = 7 ;
double ar = 3.14 * r * r;
return ar;
}
}
public class GFG {
public static void main(String args[])
{
Circle c = new Circle();
double area;
area = c.area();
System.out.println( "Area of circle is : " + area);
}
}
|
Output
Area of circle is : 153.86
Example 2: Circumference calculation
Java
import java.util.*;
class Circle {
double radius;
double circumference()
{
double r = 7 ;
double circum = 2 * 3.14 * r;
return circum;
}
}
public class GFG {
public static void main(String args[])
{
Circle c = new Circle();
double circum;
circum = c.circumference();
System.out.println( "Circumference of circle is : "
+ circum);
}
}
|
Output
Circumference of circle is : 43.96
Time complexity: O(1) as constant operations have been done
Auxiliary space: O(1)
Last Updated :
12 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...