Fix To: The Out Parameter Must Be Assigned to Before Control Leaves the Current Method

DZone 's Guide to

Fix To: The Out Parameter Must Be Assigned to Before Control Leaves the Current Method

For Java beginners: how to use out parameters with methods.

· Java Zone ·
Free Resource


  • The out keyword causes arguments to be passed by reference.
  • To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
  • Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.


Here is a simple program to check whether the given character exists or not:

using System;  
class Program  
    static void Main ( )  
        bool sharpsymbol; // Used as out parameter.  
        bool AndSymbol;  
        bool Paranthesis;  
        const string value = "& # @";// Used as input string.  
        CheckString ( value, out sharpsymbol, out AndSymbol, out Paranthesis );  
        Console.WriteLine ( value ); // Display value.  
        Console.Write ( "sharpsymbol: " ); // Display labels and bools.  
        Console.WriteLine ( sharpsymbol );  
        Console.Write ( "AndSymbol: " );  
        Console.WriteLine ( AndSymbol );  
        Console.Write ( "Paranthesis: " );  
        Console.WriteLine ( Paranthesis );  
        Console.ReadLine ( );  
    static void CheckString ( string value,  
    out bool sharpsymbol,  
    out bool AndSymbol,  
    out bool Paranthesis )  
        // Assign all out parameters to false.  
        sharpsymbol = AndSymbol = Paranthesis = false;  
        for(int i = 0; i < value.Length; i++)  
                case '#':  
                        sharpsymbol = true; // Set out parameter.  
                case '&':  
                        AndSymbol = true; // Set out parameter.  
                case '(':  
                        Paranthesis = false; // Set out parameter.  



When the Problem Occurs:



In the above program, even though you assigned the out variable value inside the looping/case statement, if you don't assign any value in the method definition like the above snagit then you will get the following error:



I hope the above information is useful for beginners, kindly let me know your thoughts.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}