FunctionX Logo

Variables

 

Overview

 

Definition

One of the jobs of a program is to request information from the user who types it using the keyboard. In some cases, the user provides information using the mouse. In the computer world, a piece of information that is part of a program is called datum and the plural is data. Sometimes the word data is used both for singular and plural items.

Imagine you write a program as an employment application. A person would use it to enter different names of various job applicants as they apply for the same job. Because the names change from one job applicant to another, it (the job applicant's name) is called a variable.

When the user enters data in a program, the computer receives it and must store it somewhere to eventually make it available to the program as needed. Referring to the employment application analogy, the types of information a user would enter into the program are the name, the residence, the desired salary, years of experience, education level, etc. Because there can be so much information for the same program, you must specify to the computer what information you are referring to and when. To do this, each category of piece of information must have a name.

Names in J#

To name the variables of your program, you must follow strict rules. In fact, everything else in your program must have a name. J# uses a series of words, called keywords, for its internal use. This means that you must avoid naming your objects using one of these keywords. They are:

abstract class double goto null short true
break const else if private static try
byte continue false int protected switch void
case default finally interface public this volatile
catch delegate float long return throw while
char do for new      

Once you avoid these words, there are rules you must follow when naming your objects. On this site, here are the rules we will follow:

  • The name must start with a letter or an underscore
  • After the first letter or underscore, the name can have letters, digits, and/or underscores
  • The name must not have any special characters other than the underscore
  • The name cannot have a space

Besides these rules, you can also create your own but that abide by the above.

J# is case-sensitive. This means that the names Case, case, and CASE are completely different. For example, the main function is always written Main.

Data Types

Before using a variable in your program, you must let the computer (in reality the compiler) know about it. Once the compiler knows about a variable, it would reserve an amount of memory space for that variable. Using its name, you can refer to a particular variable when necessary. Because there are various types of variables a program can use, such as the employee's name, the residence, the desired salary, years of experience, education level, etc for our employment application analogy, the compiler needs a second piece of information for each variable you intend to use. This piece of information specifies the amount of space that a variable needs. You can see that, to store a character, such as an employee's gender (M or F) or an answer as Y or N to a question, the compiler would certainly not need the same amount of space to store the name of the last school attended by an employee.

A data type is an amount of space needed to store the information related to a particular variable.

The name of a variable allows you and the compiler to refer to a particular category of information in your program. The data type allows the compiler to reserve an adequate amount of memory space for a variable. Because you are the one who writes a program, you also tell the computer the amount of memory space each particular variable will need. Based on this, the J# language provides categories of data types used  to specify this amount of space needed for a variable.

As stated already, in order to use a variable, the compiler must be aware of it. Making the compiler aware is referred to as declaring the variable. To declare a variable, provide the data type followed by the name of the variable. Therefore, the syntax used to declare a variable is:

DataType VariableName;

After declaring a variable, you can ask the compiler to store some value into its reserved memory space. This is done using the assignment operator represented with =. Of course, throughout your program, you can assign another value to the variable as you judge necessary. Giving its first value to a variable is referred to as initializing it.

If you plan to use various variables of the same type, you can declare them and specify their names on the same line, sharing the common data type. The syntax used would be:

DataType Variable1, Variable2, Variable_n;

The variables declared like this must be of the same type.

Practical Learning: Using Variables

  1. Start Notepad and, based on what we reviewed in the previous lesson, type the following:
     
    package Variables;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    		
    	}
    }
  2. Save the file in a new folder named Variables1 inside the JSharp Lessons folder
  3. Save the file as Exercise.jsl in the Variable1 folder
  4. Open the Command Prompt and switch to the JSharp Lessons\Variables1 folder
  5. To compile the application, type vjc Exercise.jsl and press Enter
  6. To execute the application, type Exercise
  7. After viewing the DOS window, return to Notepad

Primary Types

 

Strings

A string is an empty space, a character, a word, or a group of words that you want the compiler to consider "as is", that is, not to pay too much attention to what the string is made of, unless you explicitly ask it to. This means that, in the strict sense, you can put in a string anything you want.

Primarily, the value of a string starts with a double quote and ends with a double-quote. An example of a string is "Welcome to the World of J# Programming!". You can include such a string in the Console.Write() method to display it on the console. Here is an example:

package Exercise;
import System.*;

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

This would produce:

Welcome to the World of J# Programming!

Sometimes, you will need to use a string whose value is not known in advance. Therefore, you can first declare a string variable. To do this, use the String class name followed by a name for the variable. The name will follow the rules we defined above. An example of a string declaration is:

String Msg;

After declaring a string, you can give it a primary value by assigning it an empty space, a character, a symbol, a word, or a group of words. The value given to a string must be included in double-quotes. Here are examples of string variables declared and initialized:

String empty  = "";
String gender = "F";
String firstName  = "Nelson Mandela";
String msg    = "Welcome to the World of J# Programming! ";

After initializing a string variable, you can use its name in any valid operation or expression. For example, you can display its value on the console using the Console.Write() or the Console.WriteLine() methods. Here is an example:

package Exercise;
import System.*;

class Exercise
{
	public static void Main()
	{
		String msg = "Welcome to the World of J# Programming! ";
		Console.WriteLine(msg);
	}
}
 

Practical Learning: Using Strings

  1. To declare a string, in Visual Studio .NET, change the file as follows:
     
    package Variables;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    		// Fast food order
    		String foodItem, drink;
    
    		foodItem  = "Hamburger";
    		drink = "20 Oz Soda";
    
    		// Display information about this order
    		Console.Write("Food Item: ");
    		Console.WriteLine(foodItem);
    		Console.Write("Drink:     ");
    		Console.WriteLine(drink);
    	}
    }
  2. Save the file and switch to the Command Prompt
  3. Compile and execute the application. This would produce:
     
    Food Item: Hamburger
    Drink:     20 Oz Soda
  4. Return to Notepad
 

Characters

In the English alphabet, a character is one of the following symbols: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Besides these readable characters, the following symbols are called digits and they are used to represent numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. In addition, some symbols on the (US QWERTY) keyboard are also called characters or symbols. They are ` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > "

Besides the English language, other languages use others or additional characters that represent verbal or written expressions.

J# recognizes that everything that can be displayed as a symbol is called a character. To declare a variable whose value would be a character, use the char keyword. Here is an example:

char Gender;

To initialize a character variable, include its value in single quotes. Here is an example:

package Exercise;
import System.*;

class Exercise
{
	public static void main()
	{
		char gender = 'M';

		Console.Write("Student Gender: ");
		Console.WriteLine(gender);
	}
}

This would produce:

Student Gender: M

Natural Numbers

 

Byte

A byte is a small positive number whose value can range from 0 to 255. You can use it when you know a variable would hold a relatively small value such as people's age, the number of children of one mother, etc.

To declare a variable that would hold a small natural number, use the Byte keyword. Here is an example:

Byte age;

 You can initialize a Byte variable when declaring it or afterwards. Here is an example that uses the Byte data type:

package Exercise;
import System.*;

class ObjectName
{
	public static void main()
	{
		byte age = 14;

		Console.Write("Student Age: ");
		Console.WriteLine(age);
		age = 12;
		Console.Write("Student Age: ");
		Console.WriteLine(age);
	}
}

Make sure you do not use a value that is higher than 255 for a Byte variable, you would receive an error. When in doubt, or when you think that there is a possibility a variable would hold a bigger value, don't use the Byte data type as it doesn't like exceeding the 255 value limit.

Signed Byte

A byte number is referred to as signed if it can hold a value that ranges from -128 to 127. To declare a variable for that kind of value, use the sbyte keyword.

Short Numbers

A natural number is short if its value is between -32768 and 32767. A variable for such a number is declared using the short data type.

Positive Short Numbers

If a short number must always by positive, it is called unsigned. A variable for this type is declared using the ushort keyword.

Integers

An integer is a natural number, that is, a number that doesn't hold a decimal value or that is not a fraction. Its value can range from -2,147,483,648 to 2,147,483,647.

To declare a variable for an integer type, use the int keyword.

Unsigned Integers

When an integer must always have a positive value, it is referred to as unsigned. To declare a variable for an unsigned integer, use the uint data type.

Long Integers

A natural number that can hold a very large value qualifies as a long integer. The value of a long integer can range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. A variable for such a value can be declared using the long keyword.

Unsigned Long Integers

If a long integer must always assume a positive value, such as ranging from 0 to 18,446,744,073,709,551,615, it is called long integer. Such a variable can be declared with the ulong keyword.

Floating-Point Values

 

Float Values

A number is referred to as floating it can assume a decimal fraction, that is, a number that includes a period. To declare a variable that can hold such a value, use the float keyword. Here is an example:

float shoeSize;

Double-Precision

A number is referred to as double-precision when its value requires significantly more precision than a regular decimal value. To declare a double-precision value in J#, use the double keyword. Here is an example:

double distance;

Use a double data type not only if the variable would need precision but also if its value would range from ±5.0 × 10−324 to ±1.7 × 10308 with up to 16 digits precision.

Here is an example:

package Exercise;
import System.*;

class ObjectName
{
	public static void main()
	{
		double distance = 224.62;

		Console.Write("Distance = ");
		Console.WriteLine(distance);
	}
}

This would produce:

Distance = 224.62

Decimal

The Decimal keyword is used for a variable that would hold significant large values that can range from ±1.0 × 10−28 to ±7.9 × 1028.

 

Details on Using Variables

 

Value Casting

Value casting consists of converting a value of one type into a value of another type. For example, if you want a decimal value and you may want that value in an expression that expects an integer.

There are various ways to cast a value from one type to another but J# is particularly flexible on this issue. Here is an example:

package Exercise;
import System.*;

class Exercise
{
   public static void main()
   {
      double number1 = 22.285;
      // Cast a decimal number into a natural number
      int number2 = (int)number1;
   }
}

Value Types Methods

In J# (unlike many other languages such as C/C++, Pascal, etc), all of the data types we have used so far are in fact complete classes. This means that they are equipped to handle their own assignments called functions as we will learn in subsequent lessons. When a data type (in this case a class) has to ability to perform assignments through its functions, it is able to better communicate with other variables, functions, or classes (the fact that the other languages, namely C/C++, Pascal, etc, use data types that are not considered classes doesn't mean they are less efficient or that they have an anomaly: it is simply the construct of the langauge!). These classes are defined in the System namespace. The classes of these data types are defined as:

  Data Type Class   Data Type Class
  bool Boolean   char Char
  byte Byte   sbyte SByte
  short Int16   ushort UInt16
  int Int32   uint UInt32
  long Int64   ulong UInt64
  float Single   double Double
 

This means that, if you don't want to use the data types we have reviewed so far, you can use the class that is defined in the System namespace. To use one of these types, type the System namespace followed by a period. Then type the equivalent class you want to use. Because the regular names of data types we introduced in the previous lesson are more known and familiar, we will mostly use them.

Because the data type are defined as classes, they are equipped with methods. One of the methods that each one them has is called ToString. As it s name implies, it is used to convert a value to a string.

 

Final Variables

 

Introduction

A variable is referred to as final when its value doesn't change throughout the program. This is the C/C++/C# equivalent to a constant.

To create a final value, type final, followed by the type of the variable, its name, the assignment operator "=", and the desired value.

 
 

Previous Copyright © 2003-2004 FunctionX, Inc. Next