Home

The Members of the Primary Class

 

Introduction to Members

 

Introduction to Methods

One of the purposes of writing a program is to perform assignments. An assignment can also be called a function. In J#, a function must belong to a class. Therefore, a function is a section whose job is to take care of an operation that would complement a class. Because a function in this case belongs to a particular class, the function is also called a method. From now on, the name method will be used for a function.

Author Note   C++ Note

In C++, a function can be declared anywhere, making it distinct from a method. In J#, a function can be declared only inside of, or as a member of, a class

Like everything else, a method must have a name. We will follow the same rules and conventions we defined for all names. An example of a method's name would be Welcome. To distinguish a method from a variable, it is always followed by parentheses, sometimes empty. Since a method is used to perform an assignment, its job is included between an opening curly bracket "{" and a closing curly bracket "}". Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	Welcome() { }

	public static void main(String[] args)
	{
	}
}

If the assignment performed by a method is long, you can use many lines to define its behavior. For this reason, each bracket can be typed on its own line.

After a method has performed its assignment, it may provide a result. The result of a method is called a return value. Each return value follows a particular type based on one of the data types we reviewed on variables. Any time you create a method, the compiler needs to know the type of value that the method would return. The type of value that a method would return is specified on the left side of the method's name.

Some, even many, of the methods used in your programs will not return a value after they have performed an assignment. When a method doesn't return a value, it is considered void. The return type of such a method is the void keyword. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	void Welcome()
	{
	}

	public static void main(String[] args)
	{
	}
}

In the exercises of this lesson, we will perform calculations for a cylinder with circular base:

Figure Areas Volume
Cylinder
Base Area = R * R * Pi
Lateral Area = 2 * Pi * R * H
Total Area = 2PiRH + 2PiR2     
 
PiR2H

 

Practical Learning Practical Learning: Introducing Global Members

  1. Start Visual Studio .NET and create a new Visual J# Console Application
  2. In the Name text box, type Cylinder1
  3. In the Location text box, type a path or select the folder we created in the previous lesson: C:\JSharp Lessons
  4. Press Enter

Static Methods

Unlike some other languages such as C/C++, Pascal, Visual Basic, etc, but like Java and C#, J# doesn't have the notion of global function: every method must belong to a class. For this reason, every program uses at least one class and we call this primary class, the main class. Because of this feature of the language, it imposes some rules on the way methods can be called. If you create a method in the main class of your project, you should indicate that the method will always belong to this main class. The method must be created as static.

To define a method as static, type the static keyword to its left. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static void Welcome()
	{
	}

	public static void main(String[] args)
	{
	}
}

As we have used the Main() function so far, the behavior of a method is defined between its delimiting curly brackets, "{" and "}". The section inside the curly brackets is called the body of a method. In the body of the method, you can simply display a sentence. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static void Welcome()
	{
		Console.WriteLine("Welcome to the Wonderful World of J#");
	}

	public static void main(String[] args)
	{
	}
}

In the same way, you can use a method to perform any other assignment. After creating a method, you can use it where needed. Using a method is also referred to as calling it. If you create a simple method like the above Welcome(), to call it, type its name followed by parentheses and ending with a semi-colon. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static void Welcome()
	{
		Console.WriteLine("Welcome to the Wonderful World of J#");
	}

	public static void main(String[] args)
	{
		Welcome();
	}
}

This would produce:

Welcome to the Wonderful World of J#
Press any key to continue

Practical Learning Practical Learning: Create a Static Method

  1. To define a static method, change the file as follows:
     
    package Cylinder1;
    import System.*;
    
    public class Cylinder
    {
    	static void ProcessCylinder()
    	{
    		Console.WriteLine("Cylinder Characteristics");
    	}
    
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    	}
    }
  2. Save the file and switch to the Command Prompt
  3. Compile and execute the application
  4. Return to Notepad

Local Variables

In the body of a method, you can also declare variables that would be used internally. A variable declared in the body of a method is referred to as a local variable. It cannot be accessed outside of the method it belongs to. After declaring a local variable, it is made available to the method and you can use it as you see fit, for example, you can assign it a value prior to using it.

Practical Learning Practical Learning: Using a Method's Local Variables

  1. To declare and use local variables of a method, change the static method as follows:
     
    package Cylinder1;
    import System.*;
    import System.Math.*;
    
    public class Cylinder
    {
    	static void ProcessCylinder()
    	{
    		double radius, height;
    		double baseArea, lateralArea, totalArea;
    		double volume;
    
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		Console.Write("Radius: ");
    		radius = Double.parseDouble(Console.ReadLine());
    		Console.Write("Height: ");
    		height = Double.parseDouble(Console.ReadLine());
    
    		baseArea    = radius * radius * Math.PI;
    		lateralArea = 2 * Math.PI * radius * height;
    		totalArea   = 2 * Math.PI * radius * (height + radius);
    		volume      = Math.PI * radius * radius * height;
    
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", (System.Double)radius);
    		Console.WriteLine("Height:  {0}", (System.Double)height);
    		Console.WriteLine("Base:    {0:F}", (System.Double)baseArea);
    		Console.WriteLine("Lateral: {0:F}", (System.Double)lateralArea);
    		Console.WriteLine("Total:   {0:F}", (System.Double)totalArea);
    		Console.WriteLine("Volume:  {0:F}", (System.Double)volume);
    	}
    
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    	}
    }
  2. Save the file and switch to the Command Prompt
  3. Compile and execute the application. Here is an example:
     
    Enter the dimensions of the cylinder
    Radius: 38.64
    Height: 22.48
    
    Cylinder Characteristics
    Radius:  38.64
    Height:  22.48
    Base:    4690.55
    Lateral: 5457.75
    Total:   14838.85
    Volume:  105443.65
  4. Return to Notepad

A Method that Returns a Value 

If a method has carried an assignment and must make its result available to other methods or other classes, the method must return a value and cannot be void. To declare a method that returns a value, provide its return type to the left of its name. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static double Operation()
	{
	}

	public static void main(String[] args)
	{
	}
}

After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To do this, you use the return keyword followed by the value that the method is returning. The value returned must be of the same type specified as the return type of the method. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static double Operation()
	{
		return 24.55;
	}

	public static void main(String[] args)
	{
	}
}

A method can also return an expression, provided the expression produces a value that is conform to the return type. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static double Operation()
	{
		return 24.55 * 4.16;
	}

	public static void main(String[] args)
	{
	}
}

When a method returns a value, the compiler considers such a method as if it were a regular value. This means that you can use Console.Write() or Console.WriteLine() to display its value. To do this, simply type the name of the method and its parentheses in the Console.Write() of the Console.WriteLine() methods' parentheses. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static double Operation()
	{
		return 24.55 * 4.16;
	}

	public static void main(String[] args)
	{
		Console.WriteLine(Operation());
	}
}

This would produce:

102.128
Press any key to continue

In the same way, a method returns a value can be assigned to a variable of the same type.

Practical Learning Practical Learning: Returning a Value From a Method 

  1. To create methods that return values, change the program as follows:
     
    package Cylinder1;
    import System.*;
    import System.Math.*;
    
    public class Cylinder
    {
    	static double GetTheRadius()
    	{
    		double rad;
    
    		Console.Write("Radius: ");
    		rad = Double.parseDouble(Console.ReadLine());
    
    		return rad;
    	}
    
    	static double GetTheHeight()
    	{
    		double h;
    
    		Console.Write("Height: ");
    		h = Double.parseDouble(Console.ReadLine());
    
    		return h;
    	}
    
    	static void ProcessCylinder()
    	{
    		double radius, height;
    		double baseArea, lateralArea, totalArea;
    		double volume;
    
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		radius = GetTheRadius();
    		height = GetTheHeight();
    
    
    		baseArea    = radius * radius * Math.PI;
    		lateralArea = 2 * Math.PI * radius * height;
    		totalArea   = 2 * Math.PI * radius * (height + radius);
    		volume      = Math.PI * radius * radius * height;
    
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", (System.Double)radius);
    		Console.WriteLine("Height:  {0}", (System.Double)height);
    		Console.WriteLine("Base:    {0:F}", (System.Double)baseArea);
    		Console.WriteLine("Lateral: {0:F}", (System.Double)lateralArea);
    		Console.WriteLine("Total:   {0:F}", (System.Double)totalArea);
    		Console.WriteLine("Volume:  {0:F}", (System.Double)volume);
    	}
    
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    	}
    }
  2. Save, compile, and test the file. Here is an example of running the program:
     
    Enter the dimensions of the cylinder
    Radius: 52.08
    Height: 36.44
    
    Cylinder Characteristics
    Radius:  52.08
    Height:  36.44
    Base:    8521.02
    Lateral: 11924.20
    Total:   28966.25
    Volume:  310506.14
  3. Return to Notepad

Pseudo-Global Variables

As mentioned with functions, J# doesn't have the notion of global variables (in C/C++, Visual Basic, Pascal, etc, a global variable is one that is declared outside of any class; such a variable is made available to any function, or even file, of the same program without being declared again where needed). Still, if you want to use the same variable in various methods of the main class, you can declare it outside of any method. The variable must be declared as static. That is, you must type the static keyword to its left when declaring it. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static double Length;

	static double Operation()
	{
		return 24.55 * 4.16;
	}

	public static void main(String[] args)
	{
		Console.WriteLine(Operation());
	}
}

After declaring such a variable, you can access from any method that belongs to the same class.

 

Practical Learning Practical Learning: Using Global Variables 

  1. To declare and use global variables, change the program as follows:
     
    package Cylinder1;
    import System.*;
    import System.Math.*;
    
    public class Cylinder
    {
    	static double radius;
    	static double height;
    	static double baseArea;
    	static double lateralArea;
    	static double totalArea;
    	static double volume;
    
    	static double GetTheRadius()
    	{
    		double rad;
    
    		Console.Write("Radius: ");
    		rad = Double.parseDouble(Console.ReadLine());
    
    		return rad;
    	}
    
    	static double GetTheHeight()
    	{
    		double h;
    
    		Console.Write("Height: ");
    		h = Double.parseDouble(Console.ReadLine());
    
    		return h;
    	}
    
    	static void ProcessCylinder()
    	{
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		radius = GetTheRadius();
    		height = GetTheHeight();
    
    		baseArea    = radius * radius * Math.PI;
    		lateralArea = 2 * Math.PI * radius * height;
    		totalArea   = 2 * Math.PI * radius * (height + radius);
    		volume      = Math.PI * radius * radius * height;
    	}
    
    	static void ShowCylinder()
    	{
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", (System.Double)radius);
    		Console.WriteLine("Height:  {0}", (System.Double)height);
    		Console.WriteLine("Base:    {0:F}", (System.Double)baseArea);
    		Console.WriteLine("Lateral: {0:F}", (System.Double)lateralArea);
    		Console.WriteLine("Total:   {0:F}", (System.Double)totalArea);
    		Console.WriteLine("Volume:  {0:F}", (System.Double)volume);
    	}
    
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    		ShowCylinder();
    	}
    }
  2. Save, compile, and test the file. Here is an example of running the program:
     
    Enter the dimensions of the cylinder
    Radius: 38.24
    Height: 32.58
    
    Cylinder Characteristics
    Radius:  38.24
    Height:  32.58
    Base:    4593.94
    Lateral: 7827.96
    Total:   17015.85
    Volume:  149670.68
  3. Return to Notepad

Methods and Conditional Statements

 

Using Conditions in Functions

The use of methods in a program allows you to isolate assignments and confine them to appropriate entities. While the methods take care of specific requests, you can provide them with conditional statements to validate what these methods do. There are no set rules to the techniques involved. Everything depends on the task at hand. To make effective use of methods, you should be very familiar with different data types because you will need to return the right value.

Suppose you write an ergonomic program that needs to check different things including answers from the user in order to proceed. These various assignments can be given to methods that would simply hand the results to the main() function that can, in turn, send these results to other methods for further processing. Here is an example:

package Exercise;
import System.*;

public class Exercise
{
	static char GetPosition()
	{
		char position;
		String strPos;

		do 
		{
			Console.Write("Are you sitting down now(y/n)? ");
			strPos = Console.ReadLine();;
			position = Char.Parse(strPos);

			if( position != 'y' && position != 'Y' &&
				position != 'n' && position != 'N' )
				Console.WriteLine("Invalid Answer\n");
		} while( position != 'y' && position != 'Y' &&
			position != 'n' && position != 'N' );

		return position;
	}

	public static void main(String[] args)
	{
		char pos;

		pos = GetPosition();
	
		if( pos == 'n' || pos == 'N' )
			Console.WriteLine("Could you please sit down for the next exercise?");
		else
			Console.WriteLine("Wonderful!!!\n");
	}
}

Here is an example of running the program:

Are you sitting down now(y/n)? V
Invalid Answer

Are you sitting down now(y/n)? z
Invalid Answer

Are you sitting down now(y/n)? n

Could you please sit down for the next exercise?

Methods don't have to return a value in order to be involved with conditional statements. In fact, both issues are fairly independent. This means that, void and non-void methods can manipulate values based on conditions internal to them.

 

Practical Learning Practical Learning: Using Conditional Statements With Methods

  1. To include conditional statements in your methods, change the program as follows:
     
    package Cylinder1;
    import System.*;
    import System.Math.*;
    
    public class Cylinder
    {
    	static double radius;
    	static double height;
    	static double baseArea;
    	static double lateralArea;
    	static double totalArea;
    	static double volume;
    
    	static double GetTheRadius()
    	{
    		double rad;
    
    		do 
    		{
    			Console.Write("Radius: ");
    			rad = Double.parseDouble(Console.ReadLine());
    			if( rad < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( rad < 0 );
    
    		return rad;
    	}
    
    	static double GetTheHeight()
    	{
    		double h;
    
    		do 
    		{
    			Console.Write("Height: ");
    			h = Double.parseDouble(Console.ReadLine());
    			if( h < 0 )
    				Console.WriteLine("Please enter a positive number");
    		} while( h < 0 );
    
    		return h;
    	}
    
    	static void ProcessCylinder()
    	{
    		Console.WriteLine("Enter the dimensions of the cylinder");
    		radius = GetTheRadius();
    		height = GetTheHeight();
    
    		baseArea    = radius * radius * Math.PI;
    		lateralArea = 2 * Math.PI * radius * height;
    		totalArea   = 2 * Math.PI * radius * (height + radius);
    		volume      = Math.PI * radius * radius * height;
    	}
    
    	static void ShowCylinder()
    	{
    		Console.WriteLine("\nCylinder Characteristics");
    		Console.WriteLine("Radius:  {0}", (System.Double)radius);
    		Console.WriteLine("Height:  {0}", (System.Double)height);
    		Console.WriteLine("Base:    {0:F}", (System.Double)baseArea);
    		Console.WriteLine("Lateral: {0:F}", (System.Double)lateralArea);
    		Console.WriteLine("Total:   {0:F}", (System.Double)totalArea);
    		Console.WriteLine("Volume:  {0:F}", (System.Double)volume);
    	}
    
    	public static void main(String[] args)
    	{
    		ProcessCylinder();
    		ShowCylinder();
    	}
    }
  2. Save, compile, and test the file. Here is an example of running the program:
     
    Enter the dimensions of the cylinder
    Radius: -24.55
    Please enter a positive number
    Radius: 24.55
    Height: -18
    Please enter a positive number
    Height: 18.75
    
    Cylinder Characteristics
    Radius:  24.55
    Height:  18.75
    Base:    1893.45
    Lateral: 2892.23
    Total:   6679.12
    Volume:  35502.11
  3. Return to Notepad

Conditional Returns

A method defined other than void must always return a value. Sometimes, a method will perform some tasks whose results would lead to different results. A method can return only one value (this is true for this context, but there are ways to pass arguments so that a method can return more than one value) but you can make it render a result depending on a particular behavior. If a method is requesting an answer from the user, since the user can provide different answers, you can treat each result differently.

Imagine you write the following method:

package Exercise;
import System.*;

public class Exercise
{
	static String GetPosition()
	{
		char position;
	
		Console.Write("Are you sitting down now(y/n)? ");
		String strPos = Console.ReadLine();
		position = Char.Parse(strPos);
	
		if( position == 'y' || position == 'Y' )
			return "Yes";
		else if( position == 'n' || position == 'N' )
			return "No";
	}

	public static void main(String[] args)
	{
		String answer;
	
		answer = GetPosition();
		Console.WriteLine("Answer = " + answer);
	}
}

When running this program, you would receive an error. On paper, the function looks fine. If the user answers with y or Y, the function returns the string Yes. If the user answer with n or N, the function returns the string No. Unfortunately, this function has a problem: what if there is an answer that does not fit those we are expecting? The values that we have returned in the function conform only to the conditional statements and not to the function. Remember that in if(Condidion)Statement, the Statement executes only if the Condition is true. Here is what will happen. If the user answers y or Y, the function returns Yes and stops. If the user answers n or N, the function returns No, which also is a valid value. If the user enters another value (other than y, Y, n, or N), the execution of the function will not execute any of the returned statements and will not exit. This means that the execution will reach the closing curly bracket without encountering a return value. This would mean to the compiler that you wrote a non-void method that is supposed to return a value, but by the end of the method, it didn't return a value. That's why the compiler displays an error. The solution is to provide a return value so that, if the execution reaches the end of the function, it would still return something. Here is a solution to the problem:

package Exercise;
import System.*;

public class Exercise
{
	static String GetPosition()
	{
		char position;
	
		Console.Write("Are you sitting down now(y/n)? ");
		String strPos = Console.ReadLine();
		position = Char.Parse(strPos);
	
		if( position == 'y' || position == 'Y' )
			return "Yes";
		else if( position == 'n' || position == 'N' )
			return "No";
		return "Invalid Answer";
	}

	public static void main(String[] args)
	{
		String answer;
	
		answer = GetPosition();
		Console.WriteLine("Answer = " + answer);
	}
}

Here is an example of running the program:

Are you sitting down now(y/n)? g

Answer = Invalid Answer

void Methods and Conditional Returns

So far, we have seen that void methods don't return a value. Still, the return keyword can be used in a void method. It allows you to exit a method before the last line if you judge it necessary. Suppose that you ask a question in a method or validate a condition. Once the condition is valid, you may not see any reason to continue further. In this case, you would like to interrupt the flow in that method and continue with the next task in another method.

To get an early exit from a method, where you judge it necessary, type the return keyword followed by a semi-colon. Of course, since this is usually used to value a condition, the return keyword can be typed at the end of a conditional statement.


Previous Copyright © 2005-2016, FunctionX Next