Void in Java

Solved
filem_ro3b Posted messages 9 Status Member -  
KX Posted messages 19031 Status Moderator -
Hello everyone
I am completely new to Java and I would like an explanation regarding the keyword "void" and its use
in the definition of methods or procedures of classes. Indeed, I have googled a lot but everything I found are similar and unsatisfactory information saying almost all that void defines a method that does not return any value! What is a value and what do we mean by returning a value?
So I would be very grateful if someone could explain this to me in a simplified and exemplified way
Thank you and best regards.
Configuration: Windows 2003 Internet Explorer 6.0

9 answers

  1. sendoshi Posted messages 22 Status Member 70
     
    It's quite simple: a method that returns void returns... nothing. Zilch, nada.
    For example, the method System.out.println returns void, meaning nothing.
    The result of the process will therefore be used in another way (in the case of println, displayed on the screen) but will not be something that can be returned in a variable. The method returns an empty set (void = empty in English) of elements.

    Be careful not to confuse it with null (a mistake I made often in my early days, shame on me).
    void is a sort of variable type that we only use for the return value in a method declaration:
    example:

    public void myMethod(int number){
    System.out.println("I return nothing");//displays and returns nothing
    }

    whereas null is an object that represents something empty, a bit like the word "nothing" in French (like in "what gift did you bring me?" "nothing. just die.")
    example:

    public Object myMethod(int number){
    return null;//returns the null object, meaning a null value, not even equal to zero
    }

    I hope I've shed some light on your mind.
    76
    1. Moi
       
      Thank you
      0
      1. jj > Moi
         
        Perfect, so that's the difference between a procedure and a function in other languages.
        0
      2. KX Posted messages 19031 Status Moderator 3 020 > jj
         
        "so that's the difference between procedure and function in other languages"
        Yes and no. The comparison with the notion of procedure/function only makes sense for static methods. As soon as we can modify the current object this, we call it a method, whether it returns a value or not.
        0