Super friendly <br/>code & developer communities

Super friendly
code & developer communities

A place for coders and developers to share, learn and grow together.

Java Programming | Function passing and returning object

This is a tutorial for function passing and returning object in java. The program is given below that adds two complex numbers. The program is extendable. Go enjoy the program. Let begin…

Before you begin, Do this
Create a separate java file for other class.
Create a java file for main class.
Import the created java class in main class file.
Program for addition of two complex numbers using class in java.

1. Create a class.

//declare the package name if the class file is
//created in other package.
package Myclasses;
//import scanner
import java.util.Scanner;
//declare class
public class ComplexNo {
    //declare variables.
    private int a,b;
    //functions should be public if needed to access from other class
    public void getdata()
        //print message to enter numbers
        System.out.println("Enter a and b of a+ib:");
        //Take input
        Scanner input = new Scanner(;
        a = input.nextInt();
        b = input.nextInt();
    public ComplexNo addit(ComplexNo x)
        ComplexNo tmp = new ComplexNo();
        tmp.a = a+x.a;
        tmp.b = b+x.b;
        return tmp;
    public void print()
        System.out.println("The Sum of Complex Numbers = "+a+"+i"+b);

2. Create file.

//import our class
import Myclasses.ComplexNo;
// the name of our class its public
public class ClassFunct {
    //void main
        public static void main (String[] args)
            //declare class
            ComplexNo no1 = new ComplexNo();
            ComplexNo no2 = new ComplexNo();
            ComplexNo sum = new ComplexNo();
            //call functions
            sum = no1.addit(no2);


Enter a and b of a+ib:
Enter a and b of a+ib:
The Sum of Complex Numbers = 2+i5

How it Works
1. Objects of class are created.
2. The getdata function is called from main class.
3. The sum function is called from main class.
4. The print function is called from main class.

Extending it
The program can be extended by using the concept in any program.
Remember this is a basic part of java which can be used in any program.


Your class
1. Create class.
2. Import the Scanner.
3. Declare the class as public
4. Declare variables.
5. Create functions.

Main class
1. Create other class
2. Import your class.
3. Declare the class as public.
4. Add the void main function.
5. Declare class.
6. Declare objects.
7. Call functions.

At the end.
You learnt creating the Java program for Function passing and returning object . So now enjoy the program.

P.S. If you have any questions, click here to join our community and feel free to ask any questions.