Home > Blockchain >  Do Void in java actually not returning any values?
Do Void in java actually not returning any values?

Time:07-09

I read that the keyword void doesn't return any values in java. I tried to run a simple program. But I don't think void working on the way that i read. Here's the example....

public class Main {
    public static void main(String args[]){
        intro("Arun", "Saravanampatti");
        intro("Kalyana Sundram", "Kovil Patti");
    }

    static void intro(String name, String place){
        System.out.println("Hello bro my name is "   name  ". and I'm from "   place);
    }
}

Now I created a method called intro with a keyword of void. So values of the method like name and place shouldn't get out of the intro method. And it shouldn't return the value to the main method. But here it does. How is this possible.

CodePudding user response:

You are confusing printing/outputting and returning.

Printing (using System.out.println) means you send some information to the console the program is executed in.

Returning, on the other hand, is sending a value back to the calling method:

public void caller(){
    int i=calee();//get a value from a method (must be returned from callee) 
    System.out.println(i);//print the value
}
public int calee(){
    return 1337;//give 1337 back to the calling method 
}

CodePudding user response:

Your intro does not return anything but it is calling another method of System.out which does prints value to your standard output.(e.g. console)

Now Standard output & input are accessible from all types of methods so that is reason you are seeing values.

CodePudding user response:

Value returning in Java with "return" keyword usage means explicit returning from the method call for next value processing or usage.

public static int method(){
  // do something
  int result = ...
  return result;
}

// method call and get his result
int result = method();

Method with "void" keyword just exits from the method without value returning.

public static void voidMethod(){
      // do something
      return;
    }

    // method call
    voidMethod();

CodePudding user response:

Void doesn't return a value if we were in C we would talk about a procedure but what is a procedure? It's a function that doesn't return a value

  •  Tags:  
  • java
  • Related