Introduction to Operators and Operands
Introduction to Operators and Operands
Fundamental Visual Basic Operators
The Parentheses: ()
Parentheses are used in two main circumstances: in a procedure as we have used Main and Console.WriteLine so far, or in an operation. The parentheses in an operation help to create sections in an operation. This regularly occurs when more than one operators are used in an operation. Consider the following operation:
8 + 3 * 5
The result of this operation depends on whether you want to add 8 to 3 then multiply the result by 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you to specify which operation should be performed first in a multi-operator operation. In our example, if you want to add 8 to 3 first and use the result to multiply it by 5, you would write (8 + 3) * 5. This would produce 55. On the other hand, if you want to multiply 3 by 5 first then add the result to 8, you would write 8 + (3 * 5). This would produce 23.
As you can see, results are different when parentheses are used on an operation that involves various operators. This concept is based on a theory called operator precedence. This theory manages which operation would execute before which one; but parentheses allow you to completely control the sequence of these operations.
Practical Learning: Introducing Operators
Imports System.Console
Module Program
Sub Main()
WriteLine("Hello World!")
End Sub
End Module
| From now on, we will only as you to start Microsoft Visual Studio and create a Console App |
The Comma ,
The comma is used to separate variables used in a group. For example, a comma can be used to delimit the names of variables that are declared on the same line. Here is an example:
Module Exercise
Sub Main()
Dim CustomerName, AccountNumber, InitialDeposit
Dim RegularDeposit, TotalDeposits
End Sub
End Module
The comma can also be used to separate the member of an enumeration or the arguments of a method. We will review all of them when the time comes.
The assignment operation is used to make a copy of a value or the value of a variable and give the copy to another variable. The assignment operation is performed with the = sign.
After you have declared a variable, before using it, it must have a value. One way you can give a value to a variable is to assign one.
The Double Quotes: ""
A double-quote is used to delimit a group of characters and symbols. To specify this delimitation, the double-quote is always used in combination with another double-quote, as in "". What ever is inside the double-quotes is the thing that need to be delimited. The value inside the double-quotes is called a string. Here is an example:
Sub Main()
Dim Country
Country = "Grande Bretagne"
End Sub
If a procedure expects a string, you can type that string in the parentheses of the procedure, we will use Console.WriteLine() and Console.ReadLine() procedures.
Practical Learning: Requesting Some Values
Module Training
Sub Main()
Dim CustomerName
Dim AccountNumber
Dim InitialDeposit
Console.Write("Enter Customer Name: ")
CustomerName = Console.ReadLine()
Console.Write("Enter Customer Acnt #: ")
AccountNumber = Console.ReadLine()
Console.Write("Enter Initial Deposit: ")
InitialDeposit = Console.ReadLine()
Console.WriteLine("======================================")
Console.WriteLine("Yugo National Bank")
Console.WriteLine("--------------------------------------")
Console.Write("Customer Name: ")
Console.WriteLine(CustomerName)
Console.Write("Account Number: ")
Console.WriteLine(AccountNumber)
Console.Write("Initial Deposit: ")
Console.WriteLine(InitialDeposit)
Console.WriteLine("======================================")
End Sub
End Module| Enter Customer Name: | Gertrude Monay |
| Enter Customer Acnt #: | 92-37293-30 |
| Enter Initial Deposit: | 450.00 |
Enter Customer Name: Gertrude Monay Enter Customer Acnt #: 922-3729-305 Enter Initial Deposit: 450.00 ====================================== Yugo National Bank -------------------------------------- Customer Name: Gertrude Monay Account Number: 922-3729-305 Initial Deposit: 450.00 ====================================== Press any key to close this window . . .
The Colon Operator :
Most of the time, to make various statements easier to read, you write each on its own line. The Visual Basic language allows you to write as many statements as necessary on the same line. To do this, the statements can be separated by a colon. Here is an example:
Module Exercise
Sub Main()
Dim CustomerName
Dim AccountNumber
Dim InitialDeposit
Console.Write("Enter Customer Name: ")
CustomerName = Console.ReadLine()
Console.Write("Enter Customer Acnt #: ")
AccountNumber = Console.ReadLine()
Console.Write("Enter Initial Deposit: ")
InitialDeposit = Console.ReadLine()
Console.WriteLine("Yugo National Bank") : Console.WriteLine(CustomerName)
Console.WriteLine(AccountNumber) : Console.WriteLine(InitialDeposit)
End Sub
End Module
String Concatenation: &
The & operator is used to append two strings or expressions. This is considered as concatenating them. For example, it could allow you to concatenate a first name and a last name, producing a full name. The general syntax of the concatenation operator is:
Value1 & Value2
To display a concatenated expression, use the assignment operator on the field. To assign a concatenated expression to a variable, use the assignment operator the same way:
Sub Main()
Dim FirstName
Dim LastName
Dim FullName
FirstName = "Francis "
LastName = "Pottelson"
FullName = FirstName & LastName
End Sub
To concatenate more than two expressions, you can use as many & operators between any two strings or expressions as necessary. After concatenating the expressions or values, you can assign the result to another variable or expression using the assignment operator.
Practical Learning: Concatenating Some Strings
Module Training
Sub Main()
Dim CustomerName
Dim AccountNumber
Dim InitialDeposit
Console.Write("Enter Customer Name: ")
CustomerName = Console.ReadLine()
Console.Write("Enter Customer Acnt #: ")
AccountNumber = Console.ReadLine()
Console.Write("Enter Initial Deposit: ")
InitialDeposit = Console.ReadLine()
Console.WriteLine("Yugo National Bank")
Console.WriteLine("Customer Name: " & CustomerName)
Console.WriteLine("Account Number: " & AccountNumber)
Console.WriteLine("Initial Deposit: $" & InitialDeposit)
End Sub
End ModuleTabs and Carriage Return
If you are displaying a string but judge it too long, you can segment it in appropriate sections as you see fit. To do this, you can use vbCrLf.
Practical Learning: Using Carriage Return-Line Feed
Imports System
Module Program
Sub Main(args As String())
Dim CustomerName
Dim AccountNumber
Dim InitialDeposit
Console.Write("Enter Customer Name: ")
CustomerName = Console.ReadLine()
Console.Write("Enter Customer Acnt #: ")
AccountNumber = Console.ReadLine()
Console.Write("Enter Initial Deposit: ")
InitialDeposit = Console.ReadLine()
Console.WriteLine("=======================================")
Console.WriteLine(" =-= Yugo National Bank =-=")
Console.WriteLine("---------------------------------------")
Console.WriteLine("Customer Name: " & CustomerName)
Console.WriteLine("Account Number: " & AccountNumber)
Console.WriteLine("Initial Deposit: $" & InitialDeposit)
Console.WriteLine("=======================================")
End Sub
End ModuleEnter Customer Name: Michael Elroy Enter Customer Acnt #: 0548089 Enter Initial Deposit: 450.00 ======================================= =-= Yugo National Bank =-= --------------------------------------- Customer Name: Michael Elroy Account Number: 0548089 Initial Deposit: $450.00 ======================================= Press any key to close this window . . .
Appying a Tab
From your experience with using the computer keyboard, you probably know already that, to create a tab white space, you can press the Tab key. If you want to get the same effect in the results you present to the user, you can use the vbTab operator of the Visual Basic language. Here are examples:
Module Program
Sub Main(args As String())
Dim FirstName
Dim LastName
Dim FullName
FirstName = "Francis "
LastName = "Pottelson"
FullName = LastName & ", " & FirstName
Console.WriteLine("First Name: " & vbTab & FirstName)
Console.WriteLine("Last Name: " & vbTab & LastName)
Console.WriteLine("Full Name: " & vbTab & FullName)
End Sub
End Module
This would produce:
First Name: Francis Last Name: Pottelson Full Name: Pottelson, Francis Press any key to close this window . . .
In the same way, you can create as many vbTab combinations as necessary.
Unary Operators
Positive Unary Operator: +
Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive:
| -∞ | -6 | -5 | -4 | -3 | -2 | -1 | 1 | 2 | 3 | 4 | 5 | 6 | +∞ | |||
| 0 | ||||||||||||||||
| -∞ | -6 | -5 | -4 | -3 | -2 | -1 | 1 | 2 | 3 | 4 | 5 | 6 | +∞ | |||
A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand.
The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side.
As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned.
The Negative Operator -
As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative.
The - sign must be typed on the left side of the number it is used to negate.
Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.
Arithmetic Operators
Addition +
The addition is performed with the + sign. It is used to add one value to another.
To add two numbers, such as 225 and 64, you could use 225 + 64. The result would be 289. The addition is also used to add the values of two variables as in MondayHours + TuesdayHours to get a total number of hours worked on Monday and Tuesday.
Besides arithmetic operations, the + symbol can also be used to concatenate strings, that is, to add one string to another. This is done by appending one string at the end of another. Here is an example:
Module Exercise
Sub Main()
Dim FirstName
Dim LastName
Dim FullName
FirstName = "James "
LastName = "Fame"
FullName = FirstName + LastName
Console.WriteLine("Full Name: " & FullName)
End Sub
End Module
Practical Learning: Using the Addition Operator
Imports System
Module Program
Sub Main(args As String())
Dim CustomerName
Dim AccountNumber
Dim InitialDeposit
Dim RegularDeposit
Dim TotalDeposits
CustomerName = "Paul Bertrand Yamaguchi"
AccountNumber = "52-92074-95"
InitialDeposit = 325
RegularDeposit = 750
TotalDeposits = InitialDeposit + RegularDeposit
Console.WriteLine("=========================================")
Console.WriteLine(" =-= Yugo National Bank =-=")
Console.WriteLine("-----------------------------------------")
Console.WriteLine("Customer Name: " & CustomerName)
Console.WriteLine("Account Number: " & AccountNumber)
Console.WriteLine("Total Deposits: $" & (InitialDeposit + RegularDeposit))
Console.WriteLine("=========================================")
End Sub
End Module========================================= =-= Yugo National Bank =-= ----------------------------------------- Customer Name: Paul Bertrand Yamaguchi Account Number: 52-92074-95 Total Deposits: $1075 ========================================= Press any key to close this window . . .
Multiplication *
The multiplication operation allows you to add a number to itself a certain number of times set by another number. The multiplication operation is performed using the * sign. For example, to add 25 to itself 3 times, you would perform the operation as 25 * 3
Subtraction -
The subtraction operation is performed using the - sign. This operation produces the difference of two or more numbers. It could also be used to display a number as a negative value. To subtract 28 from 65, you express this with 65-28.
The subtraction can also be used to subtract the values of two values.
Practical Learning: Using the Subtraction Operator
Module Program
Sub Main(args As String())
Dim CustomerName, AccountNumber
Dim InitialDeposit, Withdrawals
Dim RegularDeposit, TotalDeposits
Dim CurrentBalance
CustomerName = "Henriette Jolana"
AccountNumber = "84-48662-72"
InitialDeposit = 1500
RegularDeposit = 468.75
TotalDeposits = InitialDeposit + RegularDeposit
Withdrawals = 300
CurrentBalance = TotalDeposits - Withdrawals
Console.WriteLine("====================================")
Console.WriteLine(" =-= Yugo National Bank =-=")
Console.WriteLine("------------------------------------")
Console.WriteLine("Customer Name: " & CustomerName)
Console.WriteLine("Account Number: " & AccountNumber)
Console.WriteLine("Total Deposits: $" & (InitialDeposit + RegularDeposit))
Console.WriteLine("Withdrawals: $" & Withdrawals)
Console.WriteLine("Current Balance: $" & CurrentBalance)
Console.WriteLine("====================================")
End Sub
End Module==================================== =-= Yugo National Bank =-= ------------------------------------ Customer Name: Henriette Jolana Account Number: 84-48662-72 Total Deposits: $1968.75 Withdrawals: $300 Current Balance: $1668.75 ==================================== Press any key to close this window . . . 
Integer Division \
Dividing an item means cutting it in pieces or fractions of a set value. Therefore, the division is used to get the fraction of one number in terms of another. Microsoft Visual Basic provides two types of operations for the division. If you want the result of the operation to be a natural number, called an integer, use the backlash operator "\" as the divisor. The formula to use is:
Value1 \ Value2
This operation can be performed on two types of valid numbers, with or without decimal parts. After the operation, the result would be a natural number.
Decimal Division /
The second type of division results in a decimal number. It is performed with the forward slash "/". Its formula is:
Value1 / Value2
After the operation is performed, the result is a decimal number.
Exponentiation ^
Exponentiation is the ability to raise a number to the power of another number. This operation is performed using the ^ operator (Shift + 6). It uses the following formula:
yx
In Microsoft Visual Basic, this formula is written as:
y^x
and means the same thing. Either or both y and x can be values, variables, or expressions, but they must carry valid values that can be evaluated. When the operation is performed, the value of y is raised to the power of x.
The division operation gives a result of a number with or without decimal values, which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result.
The remainder operation is performed with keyword Mod. Its formula is:
Value1 Mod Value2
The result of the operation can be used as you see fit or you can display it in a control or be involved in another operation or expression.
Bit Operations
Introduction
From our introduction to variables, you may remember that the computer stores its data in memory using small locations that look like boxes and each box contains a bit of information. Because a bit can be represented only either as 1 or 0, we can say that each box contains 1 or 0. Bit manipulation consists of changing the value (1 or 0, or 0 or 1) in a box. As we will see in the next few operations, it is not just about changing a value. It can involve reversing a value or kind of "moving" a box from its current position to the next position.
The operations on bits are performed on 1s and 0s only. This means that any number is decimal or hexadecimal format involved in a bit operation must be converted to binary first.
You will almost never perform some of the operations we are going to review. You will hardly perform some other operations. There is only one operation you will perform on a regular basis. The OR operation is very regular in Microsoft Windows (Win32) programming so much that we were obliged to include this whole section in the lesson, as opposed to mentioning only OR.
"Reversing" a Bit
Remember that, at any time, a box (or chunk) in memory contains either 1 or 0:

Bit reversal consists of reversing the value of a bit. If the box contains 1, you can reverse it to 0. If it contains 0, you can reverse it to 1. To support this operation, the Visual Basic language provides the Not Operator.
As an example, consider the number 286. The decimal number 286 converted to binary is 100011110. You can reverse each bit as follows:
| 286 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| Not 286 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 1 |
Bitwise Conjunction
Bitwise conjunction consists of adding the content of one box (a bit) to the content of another box (a bit). To support the bitwise conjunction operation, the Visual Basic language provides the And operator.
To perform the bit addition on two numbers, remember that they must be converted to binary first. Then:
| Bit0 | 0 |
| Bit1 | 0 |
| Bit0 And Bit1 | 0 |
| Bit0 | 1 |
| Bit1 | 0 |
| Bit0 And Bit1 | 0 |
| Bit0 | 0 |
| Bit1 | 1 |
| Bit0 And Bit1 | 0 |
| Bit0 | 1 |
| Bit1 | 1 |
| Bit0 And Bit1 | 1 |
As an example, consider the number 286 bit-added to 475. The decimal number 286 converted to binary is 100011110. The decimal number 4075 converted to binary is 111111101011. Based on the above 4 points, we can add these two numbers as follows:
| 75 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| 4075 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 |
| 286 And 4075 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 |
Therefore, 286 And 4075 produces 100001010 which is equivalent to:
| Bit8 | Bit7 | Bit6 | Bit5 | Bit4 | Bit3 | Bit2 | Bit1 | Bit0 | |
| 256 | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | |
| 286 And 4075 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 |
| 256 | 0 | 0 | 0 | 0 | 8 | 0 | 2 | 0 |
This means that 286 And 4075 = 256 + 16 + 2 = 266
This can also be programmatically calculated as follows:
Module Exercise
Sub Main()
Dim Number1 = 286
Dim Number2 = 4075
Dim Result = Number1 And Number2
Console.WriteLine("286 And 4075 = " & (Result))
End Sub
End Module
This would produce:
286 And 4075 = 266 Press any key to close this window . . .
Bitwise Disjunction
Bitwise disjunction consists of disjoining one a bit from another bit. To support this operation, the Visual Basic language provides the Or operator.
To perform a bitwise conjunction on two numbers, remember that they must be converted to binary first. Then:
| Bit0 | 0 |
| Bit1 | 0 |
| Bit0 Or Bit1 | 0 |
| Bit0 | 1 |
| Bit1 | 0 |
| Bit0 Or Bit1 | 1 |
| Bit0 | 0 |
| Bit1 | 1 |
| Bit0 Or Bit1 | 1 |
| Bit0 | 1 |
| Bit1 | 1 |
| Bit0 Or Bit1 | 1 |
As an example, consider the number 305 bit-disjoined to 2853. The decimal number 305 converted to binary is 100110001. The decimal number 2853 converted to binary is 101100100101. Based on the above 4 points, we can disjoin these two numbers as follows:
| 305 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 1 |
| 2853 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 |
| 305 Or 2853 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 |
Therefore, 305 Or 2853 produces 101100110101 which is equivalent to:
| Bit11 | Bit10 | Bit9 | Bit8 | Bit7 | Bit6 | Bit5 | Bit4 | Bit3 | Bit2 | Bit1 | Bit0 | |
| 2048 | 1024 | 512 | 256 | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | |
| 305 Or 2853 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 |
| 2048 | 0 | 512 | 256 | 0 | 0 | 32 | 16 | 0 | 4 | 0 | 1 |
This means that 286 And 4075 = 2048 + 512 + 256 + 32 + 16 + 4 + 1 = 2869
This can also be programmatically calculated as follows:
Module Exercise
Sub Main()
Dim Number1 = 305
Dim Number2 = 2853
Dim Result = Number1 Or Number2
Console.WriteLine("286 Or 4075 = " & (Result))
End Sub
End Module
This would produce:
286 Or 4075 = 2869 Press any key to close this window . . .
Bitwise Exclusion
Bitwise exclusion consists of adding two bits with the following rules. To support bitwise exclusion, the Visual Basic language provides an operator named Xor:
| Bit0 | 0 | 1 |
| Bit1 | 0 | 1 |
| Bit0 Xor Bit1 | 0 | 0 |
| Bit0 | 0 | 1 |
| Bit1 | 1 | 0 |
| Bit0 Xor Bit1 | 1 | 1 |
As an example, consider the number 618 bit-excluded from 2548. The decimal number 618 converted to binary is 1001101010. The decimal number 2548 converted to binary is 100111110100. Based on the above 2 points, we can bit-exclude these two numbers as follows:
| 618 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |
| 2548 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 |
| 618 Xor 2548 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
Therefore, 305 Or 2853 produces 101110011110 which is equivalent to:
| Bit11 | Bit10 | Bit9 | Bit8 | Bit7 | Bit6 | Bit5 | Bit4 | Bit3 | Bit2 | Bit1 | Bit0 | |
| 2048 | 1024 | 512 | 256 | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | |
| 618 Xor 2548 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| 2048 | 0 | 512 | 256 | 128 | 0 | 0 | 16 | 8 | 4 | 2 | 0 |
This means that 286 And 4075 = 2048 + 512 + 256 + 128 + 16 + 8 + 4 + 2 = 2974
This can also be programmatically calculated as follows:
Module Exercise
Sub Main()
Dim Number1 = 618
Dim Number2 = 2548
Dim Result = Number1 Xor Number2
Console.WriteLine("286 Xor 4075 = " & (Result))
End Sub
End Module
This would produce:
286 Xor 4075 = 2974 Press any key to close this window . . .
Left-Shifting the Bits
Left shifting the bits consists of pushing each bit from right to left. You can do this by one ore more bits. Once again, to perform this operation, the number has to be converted to its binary equivalent. To support this operation, the Visual Basic language provides an operator represented as <<.
Imagine you have a number as 741. Its binary equivalent is 1011100101 and can be represented as:
| 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 |
To perform a left shift operation on these bits, you push each from its position to the left, depending on the number of pushes you want. For example, to left-shift by 1 bit, you push each bit to the left by one position. Actually, you consider the bit at position x and the bit to its left at position y. You replace the value of Bit y by the value of Bit x. If Bit x is the most right bit, it receives a value of 0. This can be illustrated as follows:
| Original | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | |
| << by 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 0 |
As a result, we get 10111001010. The decimal result can be calculated as follows:
| Bit10 | Bit9 | Bit8 | Bit7 | Bit6 | Bit5 | Bit4 | Bit3 | Bit2 | Bit1 | Bit0 | |
| 1024 | 512 | 256 | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | |
| 741 << 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 0 |
| 1024 | 0 | 256 | 128 | 64 | 0 | 0 | 8 | 0 | 2 | 0 |
Consequently, 741 << 1 = 1024 + 256 + 128 + 64 + 8 + 2 = 458
This can also be evaluated programmatically as follows:
Module Exercise
Sub Main()
Console.WriteLine("741 << 1 = " & (741 << 1))
End Sub
End Module
This would produce:
741 << 1 = 1482 Press any key to close this window . . .
In the same way, you can push the bits to the left by more than one unit.
Right-Shifting the Bits
You can shift the bits to the right. Everything is done as reviewed for the left shift but in reverse order. To support this operation, the Visual Basic language provides the >> operator.
Variable Declaration With Type
Introduction
As we will see in the next lessons, when a user is asked to provide a value in a program, the value is primarily considered a normal group of characters, also called a string. If you intend to involve that value in an operation that is not meant for a string, you should (usually must) first convert that string to the appropriate value. Fortunately, each data type that we are going to review presents an appropriate and easy mechanism to perform this conversion.
To specify the amount of memory that a variable would use, on the right side of the variable's name, you type the As keyword followed by the data type. The formula to declare a variable is:
Dim variable-name As data-type
Type Characters
To make variable declaration a little faster and even convenient, you can replace the As DataType expression with a special character that represent the intended data type. Such a character is called a type character and it depends on the data type you intend to apply to a variable. When used, the type character must be the last character of the name of the variable. We will see what characters are available and when it can be applied.
Numeric Data Types
Introduction
A natural number is one that contains either only one digit or a combination of digits and no other character, except those added to make it easier to read. Examples of natural numbers are 122 and 2864347. When a natural number is too long, such 3253754343, to make it easier to read, the thousands are separated by a special character. This character depends on the language or group of languages and it is called the thousands separator. For US English, this character is the comma. The thousands separator symbol is used only to make the number easier to read. You will never use it in your code when referring to a number.
To support different scenarios, Visual Basic provides different types of natural numbers.
A byte is a group of 8 bits. Since each bit can have a value or either 1 or 0. The total number of possible combinations of 8 bits is 27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255. Since all bits can have values of 0 each, a byte can have values from 0 to 255. Therefore, a byte can hold a small natural positive number that ranges from 0 to 255.
To declare a variable for a small number, use the Byte keyword. Here is an example:
Module Exercise
Sub Main()
Dim StudentAge As Byte
End Sub
End Module
A Byte variable is initialized with 0. Otherwise, to initialize it, you can assign it a small number from 0 to 255. To convert a value to a Byte value, you can use CByte(). To do this, enter the value or the expression in the parentheses of CByte(). If the conversion is successful, CByte() produces a Byte value.
There is no type character for the Byte data type.
Practical Learning: Using Bytes
Module Program
Sub Main(args As String())
Dim Shirts As Byte
Dim Pants As Byte
Console.Write("Enter Number of Shirts: ")
Shirts = Console.ReadLine()
Console.Write("Enter Number of Pants: ")
Pants = Console.ReadLine()
Console.WriteLine("====================================")
Console.WriteLine("-/- Georgetown Cleaning Services -/-")
Console.WriteLine("====================================")
Console.WriteLine("Item Type" & vbTab & "Qty")
Console.WriteLine("------------------------------------")
Console.WriteLine("Shirts " & vbTab & vbTab & Shirts)
Console.WriteLine("Pants " & vbTab & vbTab & Pants)
Console.WriteLine("====================================")
End Sub
End ModuleEnter Number of Shirts: 4 Enter Number of Pants: 2 ==================================== -/- Georgetown Cleaning Services -/- ==================================== Item Type Qty ------------------------------------ Shirts 4 Pants 2 ==================================== Press any key to close this window . . .
If you want to use a very small number but it does not have to be positive, the Visual Basic language provides an alternative. A signed byte is a small number that is between -127 and 128. To declare a variable for such a number, you can use the SByte data type. This can be done as follows:
Module Exercise
Sub Main()
Dim Temperature As SByte
End Sub
End Module
To convert a value to an SByte value, use CSByte().
There is no type character for the SByte data type.
An integer is a natural number larger than the Byte. Examples of such ranges are the number of pages of a book, the age of a person. To declare a variable that can hold natural numbers in the range of -32768 to 32767, you can use the Short data type.
Here is an example:
Module Exercise
Sub Main()
Dim MusicTracks As Short
End Sub
End Module
By default, a Short variable is initialized with 0. After declaring a Short variable, you can initialize it with the necessary value that must be a relatively small integer from -32768 to 32767. Here is an example:
Module Exercise
Sub Main()
Dim MusicTracks As Short
MusicTracks = 16
Console.WriteLine(MusicTracks)
End Sub
End Module
In some cases, the compiler may allocate more memory than the variable needs, beyond the area required by a Short value. To indicate that the number must be treated as a Short and not another type of value, type s or S on the right of the initializing value. Here is an example:
Module Exercise
Sub Main()
Dim MusicTracks As Short
MusicTracks = 16S
Console.WriteLine("This album contains " & MusicTracks & " tracks.")
End Sub
End Module
This would produce:
This album contains 16 tracks. Press any key to close this window . . .
To convert a value to a short integer, you can use CShort() by entering the value or the expression in the parentheses of CShort(). If the conversion is successful, CShort() produces a Short value.
There is no type character for the Short data type.
As mentioned above, a short integer can be either negative or positive. If you want to use a relatively small number that must be positive, you must store it as an unsigned short integer. An unsigned short integer is a natural number between 0 and 65535.
To declare a variable that would hold a short positive number, you can use the UShort data type. Here is an example:
Module Exercise
Sub Main()
Dim TotalNumberOfStudents As UShort
End Sub
End Module
There is no type character for the UShort data type.
To convert something to an unsigned short integer, put in the parentheses of CUShort().
Practical Learning: Using Unsigned Short Integers
Module Program
Sub Main(args As String())
Dim Shirts As Byte
Dim Pants As Byte
Dim OtherItems As UShort
Console.Write("Enter Number of Shirts: ")
Shirts = Console.ReadLine()
Console.Write("Enter Number of Pants: ")
Pants = Console.ReadLine()
Console.Write("Enter Number of Other Items: ")
OtherItems = Console.ReadLine()
Console.WriteLine("====================================")
Console.WriteLine("-/- Georgetown Cleaning Services -/-")
Console.WriteLine("====================================")
Console.WriteLine("Item Type" & vbTab & "Qty")
Console.WriteLine("------------------------------------")
Console.WriteLine("Shirts " & vbTab & vbTab & Shirts)
Console.WriteLine("Pants " & vbTab & vbTab & Pants)
Console.WriteLine("Other Items " & vbTab & OtherItems)
Console.WriteLine("====================================")
End Sub
End ModuleEnter Number of Shirts: 2 Enter Number of Pants: 5 Enter Number of Other Items: 3 ==================================== -/- Georgetown Cleaning Services -/- ==================================== Item Type Qty ------------------------------------ Shirts 2 Pants 5 Other Items 3 ==================================== Press any key to close this window . . .
If you want a variable to hold values larger than the Short data type can accommodate, you can use the Integer data type to declare it. A variable declared with the Integer data type can hold a value between -2,147,483,648 and 2,147,483,647. Here is an example:
Module Exercise
Sub Main()
Dim NumberOfPages As Integer
End Sub
End Module
Alternatively, you can use the % type character to declare an integral variable. Here is an example:
Module Exercise
Sub Main()
Dim NumberOfPages%
End Sub
End Module
To convert a value to an integer, use CInt(): enter the value or the expression in the parentheses of CInt(). If the conversion is successful, CInt() produces an integral value.
After declaring an Integer variable, the compiler initializes it with a 0 value. Still, you can initialize it with the necessary value but you have three or four alternatives. To initialize the variable with a regular natural number, you can simply assign it that number. Here is an example:
Module Exercise
Sub Main()
Dim NumberOfPages As Integer
NumberOfPages = 846
Console.WriteLine("This book contains " & NumberOfPages & " pages.")
End Sub
End Module
This would produce:
This book contains 846 pages. Press any key to close this window . . .
The Visual Basic language considers three types of integer values. Instead of just assigning a regular natural number, to indicate that the value must be considered as an integer, you can enter i or I on the right side of the value. Here is an example:
Module Exercise
Sub Main()
Dim NumberOfPages As Integer
NumberOfPages = 846I
End Sub
End Module
The second type of integral number is referred to as hexadecimal. On a surface, it is primarily a different way of representing a number by using a combination of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, A, B, C, D, E, or F. This still allows you to represent any natural number. To initialize an integer variable with a hexadecimal number, start the value with &h or &H. Here is an example:
Module Exercise
Sub Main()
Dim NumberOfStudents As Integer
NumberOfStudents = &H4A26EE
Console.WriteLine("School Current Enrollment: " & NumberOfStudents & " students.")
End Sub
End Module
This would produce:
School Current Enrollment: 4859630 students. Press any key to close this window . . .
Besides the regular natural or the hexadecimal numbers, the third type of value an Integer variable can hold is referred to as octal. This is a technique used to represent a natural number using a combination of 0, 1, 2, 3, 4, 5, 6, and 7. To use such a value, start it with &o or &O (the letter O and not the digit 0). Here is an example:
Module Exercise
Sub Main()
Dim NumberOfStudents As Integer
NumberOfStudents = &O4260
Console.WriteLine("School Current Enrollment: " & NumberOfStudents & " students.")
Console.WriteLine("=========================================")
End Sub
End Module
This would produce:
School Current Enrollment: 2224 students. ========================================= Press any key to close this window . . .
We saw that the Integer data type is used to declare a variable for a large number that can be negative or positive. If you want the number to only be positive, you can declare it as an unsigned integer. An unsigned integer is a number between 0 and 4294967295. Examples are the population of a city, the distance between places of different countries, the number of words of a book.
To declare a variable that can a large positive number, use the UInteger data type. Here is an example:
Module Exercise
Sub Main()
Dim Population As UInteger
End Sub
End Module
You can initialize the variable using a positive integer in decimal, hexadecimal, or octal format.
To convert a value to an unsigned short integer, use CUInt() by entering the value or the expression in the parentheses.
There is no type character for the UInteger data type.
A long integer is a very large natural number that is between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. To declare a variable that can hold a very large natural number, use the Long data type. Here is an example:
Module Exercise
Sub Main()
Dim Population As Long
End Sub
End Module
Instead of the AS Long expression, as an alternatively, you can also use the @ symbol as the type character to declare a Long variable. Here is an example:
Module Exercise
Sub Main()
Dim Population@
End Sub
End Module
To convert a value to a long integer, you can use CLng(). To do this, enter the value or the expression in the parentheses of CLng(). If the conversion is successful, CLng() produces a Long integer value.
Like all integers, a Long variable is initialized, by default, with 0. After declaring a Long variable, you can initialize with the necessary natural number. Here is an example:
Module Exercise
Sub Main()
Dim Population@
Population@ = 9793759
Console.WriteLine("Country Population: " & Population)
Console.WriteLine("============================")
End Sub
End Module
This would produce:
Country Population: 9793759 ============================ Press any key to close this window . . .
To indicate that the value must be treated as Long, type l or L on the right side of the number. Here is an example:
Module Exercise
Sub Main()
Dim Population@
Population@ = 9793759L
End Sub
End Module
Because Long is primarily an integral like the Integer data type we reviewed earlier, you can also initialize it using a decimal, a hexadecimal, or an octal value. Here is an example of a variable initialized with a hexadecimal value:
Module Exercise
Sub Main()
Dim Population@
Population = &HFF42AD
Console.WriteLine("Country Population: " & Population)
Console.WriteLine("============================")
End Sub
End Module
This would produce:
Country Population: 16728749 ============================ Press any key to close this window . . .
We saw that a long integer can be a very large negative or positive natural number. If you want to store a very large number but the number but be positive, you can consider it as an unsigned long integer. Such a number can be between 0 and 18446744073709551615.
To declare a variable that can hold a very large natural positive number, use the ULong data type. Here is an example:
Module Exercise
Sub Main()
Dim DistanceBetweenBothPlanets As ULong
End Sub
End Module
There is no type character for the ULong data type.
To convert a value to an unsigned long integer, use CULng().
Floating-Point Numbers
Introduction
A real number is one that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel of computers of most regular users:

On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.
Practical Learning: Introducing Decimal Variables
A decimal number is said to have single precision if it can include a decimal part but the precision of the number is not important. In the Visual Basic language, such a number has a value that can range from -3.402823e38 and -1.401298e-45 if the number is negative, or 1.401298e-45 and 3.402823e38 if the number is positive.
To declare a variable that can hold small decimal numbers with no concern for precision, use the Single data type. Here is an example:
Module Exercise
Sub Main()
Dim Distance As Single
End Sub
End Module
Instead of the AS Single expression, you can use the ! symbol as the type character. Here is an example:
Module Exercise
Sub Main()
Dim Distance!
End Sub
End Module
The ! symbol can also be used in other scenarios in the Visual Basic language. Whenever you use it, make sure the word that comes to its right is not the name of a variable.
A Single variable is initialized with 0. After declaring a Single variable, you can declare it with the necessary value. Here is an example:
Module Exercise
Sub Main()
Dim Distance!
Distance! = 195.408
Console.WriteLine("Distance: " & Distance)
Console.WriteLine("=================")
End Sub
End Module
This would produce:
Distance: 195.408 ================= Press any key to close this window . . .
In some cases, the compiler may allocate more memory than necessary for the variable. For example, the above value is more suitable for another type as we will see in the next section. Otherwise, to indicate that the variable must be treated as a decimal number with single-precision, type f or F on the right side of the number. Here is an example:
Module Exercise
Sub Main()
Dim Distance!
Distance! = 195.408f
End Sub
End Module
To convert a string to a long integer, call CSng(). Enter the value or the expression in the parentheses of CSng(). If the conversion is successful, CSng() produces a Single value.
While the Single data type can allow large numbers, it offers less precision. For an even larger number, Visual Basic provides the Double data type. This is used for a variable that would hold numbers that range from 1.79769313486231e308 to 4.94065645841247e324 if the number is negative or from 1.79769313486231E308 to 4.94065645841247E324 if the number is positive.
To declare a variable that can store large decimal numbers with a good level of precision, use the Double keyword.
| In most circumstances, it is preferable to use Double instead of Single when declaring a variable that would hold a decimal number. Although the Double takes more memory spaces (computer memory is not expensive anymore(!)), it provides more precision. |
Here is an example of declaring a Double variable:
Module Exercise
Sub Main()
Dim TempFactor As Double
End Sub
End Module
If you want, you can omit the As Double expression but use the # symbol instead to declare a Double variable. This can be done as follows:
Module Exercise
Sub Main()
Dim TempFactor#
End Sub
End Module
A double-precision variable is initialized with a 0 value. After declaring a Double variable, you can initialize it with the needed value. Here is an example:
Module Exercise
Sub Main()
Dim TempFactor#
TempFactor# = 482
Console.WriteLine("Temperature: " & TempFactor & " Degrees")
Console.WriteLine("========================")
End Sub
End Module
This would produce:
Temperature: 482 Degrees ======================== Press any key to close this window . . .
To indicate that the variable being used must be treated with double precision, enter r or R on its right side. Here is an example:
Module Exercise
Sub Main()
Dim TempFactor#
TempFactor# = 482r
Console.WriteLine("Temperature: " & TempFactor & " Degrees")
End Sub
End Module
To convert a value to a double-precision number, call CDbl() by entering the value or the expression in the parentheses of CDbl(). If CDbl() succeeds, it produces a Double value.
Practical Learning: Using Double Precision Variables
Module YugoNationalBank
Sub Main()
Console.Write("Enter Customer Name: ")
Dim CustomerName = Console.ReadLine()
Console.Write("Enter Account #: ")
Dim AccountNumber = Console.ReadLine()
Console.Write("Enter Initial Deposit: ")
Dim strDeposit = Console.ReadLine()
Console.Write("Enter total withdrawals: ")
Dim strWithdrawals = Console.ReadLine()
Dim InitialDeposit = CDbl(strDeposit)
Dim Withdrawals = CDbl(strWithdrawals)
Dim CurrentBalance = InitialDeposit - Withdrawals
Console.WriteLine("======================================")
Console.WriteLine(" =-= Yugo National Bank =-=")
Console.WriteLine("--------------------------------------")
Console.WriteLine("Customer Name: {0}", CustomerName)
Console.WriteLine("Account Number: {0}", AccountNumber)
Console.WriteLine("Deposits: {0}", InitialDeposit)
Console.WriteLine("Withdrawals: {0}", Withdrawals)
Console.WriteLine("--------------------------------------")
Console.WriteLine("Current Balance: {0}", CurrentBalance)
Console.WriteLine("======================================")
End Sub
End ModuleEnter Customer Name: Jeanne Horn
Enter Account #: 204-858-296
Enter Initial Deposit: 3250
Enter total withdrawals: 1500
======================================
=-= Yugo National Bank =-=
--------------------------------------
Customer Name: Jeanne Horn
Account Number: 204-858-296
Deposits: 3250
Withdrawals: 1500
Current Balance: 1750
======================================
Press any key to close this window . . .The decimal data type can be used to declare a variable that would hold significantly large values that can be stored in a combination of 128 bits. You declare such a variable using the Decimal keyword. The values stored in a decimal variable can range from ą1.0x 10−28 to ą7.9 x 1028 with a precision of 28 to 29 digits. Because of this high level of precision, the Decimal data type is suitable for currency values.
Like those of the other numeric types, by default, a variable declared as Decimal is initialized with 0. After declaring a decimal variable, you can initialize it with a natural number. To indicate to the compiler to reserve space enough to store a decimal value, add a d or D to the right side of the value. Here is an example:
Module Exercise
Sub Main()
Dim DistanceBetweenPlanets As Decimal
DistanceBetweenPlanets = 592759797549D
End Sub
End Module
To convert a value or an expression to Decimal, you can call CDec().
Characters and Strings
A character can be a letter, a digit, any readable or non-readable symbol that can be represented. To declare a variable that would hold a character, use the Char data type. Here is an example:
Module Exercise
Sub Main()
Dim Letter As Char
End Sub
End Module
When declaring a Char variable, if you don't initialize it, the compiler does it with an empty character. Otherwise, after declaring a Char variable, you can initialize it with a single character included in double-quotes. Here is an example:
Module Exercise
Sub Main()
Dim Letter As Char
Letter = "W"
End Sub
End Module
To indicate that the value of the variable must be treated as Char, when initializing it, you can type c or C on the right side of the double-quoted value. Here is an example:
Module Exercise
Sub Main()
Dim Letter As Char
Letter = "W"c
End Sub
End Module
To convert a value to Char, you can call CChar().
A string is an empty text, a letter, a word or a group of words considered "as is". To declare a string variable, you can use the String data type. Here is an example:
Module Exercise
Sub Main()
Dim Sentence As String
End Sub
End Module
If you want, you can replace the AS String expression with the $ symbol when declaring a string variable. This can be done as follows:
Module Exercise
Sub Main()
Dim Sentence$
End Sub
End Module
After declaring a String variable, by default, the compiler initializes it with an empty string. Otherwise, you can initialize it with a string of your choice. To do this, include the string between double quotes. Here is an example:
Module Exercise
Sub Main()
Dim Sentence$
Sentence$ = "He called me"
End Sub
End Module
If you want to include a double-quote character in the string, you can double it. Here is an example:
Module Exercise
Sub Main()
Dim Sentence$
Sentence$ = "Then she said, ""I don't love you no more."" and I left"
Console.WriteLine(Sentence)
End Sub
End Module
This would produce:
Then she said, "I don't love you no more." And I left Press any key to close this window . . .
To convert a value to a string, call CStr() and enter the value or the expression in its parentheses. If the value is an appropriate date or time, CStr() would produces a string that represents that date or that time value.
Other Topics on Variables
An Object can be any type of data that you want to use in your program. In most cases, but sparingly, it can be used to declare a variable of any type. Here are examples:
Module Exercise
Sub Main()
Dim CountryName As Object
Dim NumberOfPages As Object
Dim UnitPrice As Object
CountryName = "Australia"
NumberOfPages = 744
UnitPrice = 248.95
Console.WriteLine("Country Name: " & CountryName)
Console.WriteLine("Number of Pages: " & NumberOfPages)
Console.WriteLine("Unit Price: " & UnitPrice)
End Sub
End Module
If you do not specify a data type or cannot figure out what data type you want to use, you can use the Object data type. As you can see from the result of the above program, the vbc compiler knows how to convert the value of any Object variable to the appropriate type. On the other hand, to convert a value or an expression to the Object type, you can use CObj().
So far, to initialize a variable, we were using a known value. Alternatively, you can use the Nothing constant to initialize a variable, simply indicating that it holds a value that is not (yet) defined. Here is an example:
Module Exercise
Sub Main()
Dim DateOfBirth As Date = Nothing
End Sub
End Module
If you use the Nothing keyword to initialize a variable, the variable is actually initialized to the default value of its type. For example, a number would be assigned 0, a date would be assigned January 1, 0001 at midnight.
Practical Learning: Ending the Lesson
|
|
|||
| Previous | Copyright © 2008-2026, FunctionX | Sunday 11 January 2026, 07:44 | Next |
|
|
|||