Top Banner
Variables, Operators, and Constants After completing this chapter, you will be able to: • Understand variables. • Understand the types of variables. • Understand the Strict option. • Understand the data type conversion. • Understand the concept of operators. • Understand operator precedence. • Understand the concept of constants. • Format numbers. • Create group boxes. • Locate logic errors. Chapter 3 Learning Objectives
30

Learning VB.NET Programming Concepts

Jan 12, 2015

Download

Education

guest25d6e3

Learning VB.NET Programming Concepts is a textbook for software developers to familiarize them with the concept of Common Language Runtime (CLR). The textbook enables the reader to understand the basic features of VB.NET. The line-by-line explanation of the source code, a unique feature of the textbook, enables the students to gain a thorough and practical understanding of VB.NET. The chapters in this book are structured in a pedagogical sequence, which makes this textbook very effective in learning the features and capabilities of the software.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Learning VB.NET Programming Concepts

Variables, Operators,and Constants

After completing this chapter, you will be able to:• Understand variables.• Understand the types of variables.• Understand the Strict option.• Understand the data type conversion.• Understand the concept of operators.• Understand operator precedence.• Understand the concept of constants.• Format numbers.• Create group boxes.• Locate logic errors.

Chapter 3

Learning Objectives

Page 2: Learning VB.NET Programming Concepts

3-2 Learning VB.NET Programming Concepts

INTRODUCTIONIn this chapter, you will learn about variables, constants, and operators used in VB.NET. Thefollowing topics will also be covered in this chapter:

1. Formatting numbers2. Creating group boxes3. Formatting a form4. Locating logical errors

VARIABLESWhile executing a program, the computer needs to hold some information. This storagelocation in the computer is called a variable. This location is associated with a specific addresswhere a value can be stored and retrieved when required. Variables hold the data temporarily.The value stored in a variable can vary while the program is running. You can perform thefollowing operations with variables:

1. Copy and store the values in order to manipulate them.

2. Test values in order to determine that they meet some criterion.

3. Perform arithmetic operations on the values.

Variable Naming Rules and ConventionsA variable name has to conform to VB.NET’s naming rules. The rules are as follows:

1. Variable names cannot contain periods or spaces.

2. Keywords such as Dim, Sub, Private, and so on cannot be used as variablenames.

3. The first character of the variable name should be a letter or an underscore character.

4. After the first character, you can use numeric digits, letters, or numeric characters.

The naming convention for variables is discussed next.

1. Give the variables descriptive names that indicate their purpose. For example, if a variablehas to store the names of the customers, you may name it as customer_name.

2. Adopt a consistent style while naming a variable. For example, in a database namedorder, if the first column is named as customer_name, then the column for storing thequantity ordered by the customers should be quantity_order. Note that both the variablenames have two words beginning with small letters and separated by an underscore.

Page 3: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-3

Data TypesA data type specifies the type of data that a variable can hold and also the amount of memoryallocated to a particular variable. Table 3-1 lists the numeric data types used in VB.NET.

The explanation of the above mentioned data types are given next.

Integer TypeAn Integer data type is used to store only numeric values without any decimal point such asnatural numbers, whole numbers, and so on. Integers can be stored using three differenttypes of variables depending on their range. Integers can be of Long, Short, and Integertype. A Long type has a size of 8-bytes, so it can hold large values. A Short type has a size of2-bytes, so it can store only small values. An Integer has a size of 4-bytes and it can store thevalues that cannot to be stored by the Short integer.

Table 3-1 Fundamental data types with their size and ranges

10 bytes +(2 * string length)

Data Type Size Range

Integer

Short

Long

Single

Double

Decimal

4 byte

2 byte

8 byte

4 byte

8 byte

16 bytes

-2,147, 483, 648 to 2,147, 483, 647

-32,768 to 32,767

Large value

Negative numbers in the range of-340223E38 to -1.401298E-45 and positivein the range of 1.401298E-45 to 3.402823E38

Negative numbers in the rangeof -1.79769313486232E308 to-4.94065645841247E-324 and positive numbers in the range of4.94065645841247E-324 to1.79769313486232E308

These are integer and floating-point numbers and are scaled by a factor in the range of 0 to 28

String0 to approximately two billion Unicodecharacters

2 bytes 0 to 65535 (unsigned)Char

Boolean 4 bytes True or False

Page 4: Learning VB.NET Programming Concepts

3-4 Learning VB.NET Programming Concepts

Single and Double TypeDouble type variables are stored internally and have a greater accuracy and precision ascompared to single type variables. Consider the following example:

22/7 = 3.14285714...........

In cases like this, the value after the decimal will be infinite, and will exceed the range allowedfor double type variables. Therefore the result will be truncated. So, the fractional valuescannot always be represented accurately in the computer memory; more precision requiresmore memory.

Decimal TypeDecimal type variables are stored internally as integers in 16 bytes and are scaled by a powerof ten. The scaling power is any integer value from 0 to 28. It determines the number ofdecimals to the right of the floating-point. When the scaling power is 0, the value is multipliedby 100. When the scaling power is 28, the value is divided by 1028.

Boolean TypeThe boolean type variable stores true/false values. The boolean variables are integers thattake -1 for true and 0 for false. Boolean variables are also combined with the logical operatorsAND, OR, NOT, and XOR.

String TypeThese type of variables can only store text.

Char TypeA character variable stores a single character in two bytes.

Declaration of VariablesA statement that helps a language to create a variable in memory is called a variable declarationstatement. It is used to indicate the name given to a variable and the type of information itholds. The syntax of declaring a variable is as follows:

Dim VariableName As Data Type

For example,Dim Area As Integer

In the above example, the word Dim stands for dimension and it directs the compiler thata variable is being declared. The word Area is the name of the variable. The term As Integer isused to specify that the variable will hold an integer value.

Page 5: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-5

You can declare multiple variables in a single statement. A comma separates these variablesfrom one another. The syntax of declaring multiple variables in a single statement is asfollows:

Dim VariableName1, VariableName2, VariableNameN As Data Type

For example,Dim Area, Perimeter As Integer

In the above example, Area and Perimeter are declared as Integer type variables.

You can also declare multiple variables of the same or different types within a single statement.The syntax of declaring multiple variables of different types is as follows:

Dim VariableName1 As Integer, VariableName2 As String

For example,Dim Area As Integer, Name As String

In the above example, Area is declared as an Integer type variable and Name is declared asthe String type variable.

Initializing a VariableInitializing a variable means assigning an initial value to a variable while declaring it. Thesyntax of initializing a variable is as follows:

Dim Variable Name As Datatype = initial value

For example,Dim Area As Integer = 254

In the above example, an initial value 254 is assigned to the variable Area.

You can also initialize multiple variables of the same or different types within a single statement.The syntax is follows:

Dim Variable Name 1 As Datatype = initial value, Variable name 2 = initial value

For example,Dim Area As Integer = 254, Name As String = “Smith”

In the above example, 254 is assigned as the initial value to the integer variable Area andSmith is assigned as the initial value to the variable Name.

Page 6: Learning VB.NET Programming Concepts

3-6 Learning VB.NET Programming Concepts

The following application illustrates the use of variables.

Create an application to display a greeting message concatenated with the name entered bythe user.

This application will prompt the user to enter a greeting message and a name. The applicationwill concatenate them and display the complete message on the form.

The following steps are required for creating this application:

Step 1Start a new project and save it as ch03_application1.

Step 2Add four Label controls, three Button controls, and two TextBox controls to the form.

Step 3Change the values of the Text property of all controls as follows:

Form1 to Use of VariablesLabel1 to Enter your greetingsLabel2 to Enter the nameLabel3 to This is your complete messageButton1 to Show MessageButton2 to ClearButton3 to Exit, as shown in Figure 3-1.

Step 4Change the values of the Name propertyof the controls as follows:

Form1 to variablesLabel1 to lblgreetingsLabel2 to lblnameLabel3 to lblmessageLabel4 to lblDisplayButton1 to btnShowButton2 to btnClearButton3 to btnExitTextBox1 to txtgreetingsTextBox2 to txtname

Step 5The following is the source code for theShow Message button:

Application 1

Figure 3-1 The Use of Variables form

Page 7: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-7

Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles btnShow.ClickDim Message As StringMessage = txtgreetings.Text & “ ” & txtname.Textlblmessage.Text = MessageEnd Sub

The following is the source code for the Clear button:

Private Sub btnClear_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnClear.Clicktxtgreetings.Clear()txtname.Clear()Message.Text = “”txtgreetings.Focus()End Sub

The following is the source code for the Exit button:

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles btnExit.ClickEndEnd Sub

The source code for the application will be displayed on the screen as given next. The linenumbers on the right are not a part of the program and are for reference only.

Public Class variables 1Inherits System.Windows.Forms.Form 2Private Sub btnShow_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnShow.Click 3Dim Message As String 4Message = txtgreetings.Text & “ ” & txtname.Text 5lblmessage.Text = Message 6End Sub 7Private Sub btnClear_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnClear.Click 8txtgreetings.Clear() 9txtname.Clear() 10lblmessage.Text = “” 11txtgreetings.Focus() 12End Sub 13Private Sub btnExit_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnExit.Click 14End 15End Sub 16End Class 17

Page 8: Learning VB.NET Programming Concepts

3-8 Learning VB.NET Programming Concepts

Line 1 and Line 17Public Class variablesEnd ClassIn these lines, a class named variables is declared. The keyword Public specifies that thisclass can be accessed and used by any other class. The End Class specifies the end of the classvariables.

Line 2Inherits System.Windows.Forms.FormIn this line, the namespace System.Windows.Forms.Form is used to provide classes to createand install windows forms applications.

Line 3 and Line 7Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles btnShow.ClickEnd SubThe word Sub in Line 3 is the short form of subroutine. It means that the event proceduresare a type of subprocedures. The word Private before the word Sub means that the proceduredefined in a particular form is accessible throughout this form. The btnShow is the name ofthe Button control and the word Click is the event that the procedure has to handle. It workswhenever a user chooses the Show button control. In Line 7, End Sub marks the end of thisprocedure.

Line 4Dim Message As StringIn this line, the dimension for the variable Message is String. It means that the variableMessage is declared as a String data type.

Line 5Message = txtgreetings.Text & “ ” & txtname.TextIn this line, txtgreetings.Text specifies the text entered in the first textbox and txtname.Textspecifies the text entered in the last textbox. The & “ ” & operators are used to concatenatethe values of the first textbox with the last textbox. After concatenation, the resultant value isassigned to the variable Message with the help of the assignment operator (=).

Line 6lblmessage.Text = MessageIn this line, the value of the variable Message is assigned to the Label control namedlblmessage.

Line 8 and Line 13Private Sub btnClear_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnClear.ClickEnd SubIn these lines, btnClear is the name of the Button control and the word Click is the eventthat the procedure has to handle. It works whenever a user chooses the Clear button control.In Line 13, End Sub indicates the end of this procedure.

Page 9: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-9

Line 9txtgreetings.Clear()In this line, the Clear() function is used to clear the text within the textbox named txtgreetings.This function is used so that you can enter a new value in this textbox.

Line 10txtname.Clear()In this line, Clear() function is used to clear the text within the textbox named txtname.

Line 11lblmessage.Text = “”In this line, “” represent an empty string that is assigned to the Label control namedlblmessage. This helps to clear the text of the Label control.

Line 12txtgreetings.Focus()In this line, the Focus() method is used to bring the focus back to the textbox txtgreetings.

Line 14 and Line 16Private Sub btnExit_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnExit.ClickEnd SubIn this line, btnExit is the name of the Button control and the word Click is the event thatthe procedure has to handle. It works whenever a user chooses the Button control. In Line16, End Sub indicates the end of this procedure.

Line 15EndIn this line, End is used to exit from theform.

Step 6Press F5 on the keyboard to execute theapplication. After execution, the form willbe displayed as shown in Figure 3-2. Checkthe application by entering different valuesin the TextBox controls. For example, inthe first TextBox control, enter GoodMorning, and in the second, enter Smith.You will get the message Good MorningSmith in the Label control, as shown inFigure 3-2. You can change the values, ifrequired.

Strict OptionIn VB.NET, if a variable is not declared before being used in the code of an application, thenthe code editor will underline the variable’s name with a jagged blue line. This line is the

Figure 3-2 The Use of Variables form afterexecution

Page 10: Learning VB.NET Programming Concepts

3-10 Learning VB.NET Programming Concepts

indication of an error. If a user tries to use a variable that has not been declared earlier, thenIn such cases, VB.NET throws an exception by default. To change this behavior, the followingstatement must be inserted at the beginning of an application:

Option Explicit Off

The above statement specifies that the value of the Option Explicit option of the applicationis changed to Off.

The setting of the Strict and the Explicit options can be modified through the Property Pagesdialog box, as shown in Figure 3-3.

To display this dialog box, right-click on the project’s name in the Solution Explorer windowand select the Properties Page option from the context menu. Next, select the Build optionfrom the Common Properties node.

Notice that the default value of Option Explicit is On. If you change its value to Off, you canuse the variables without declaring them. The next option is the Option Strict which is Offby default. If you change its value to On, the compiler allows some of the implicit conversionsbetween data types.

Data Type ConversionYou can convert the data type of a variable from one type to another with the help of certainfunctions provided by VB.NET. The list of these functions is given in Table 3-2.

Figure 3-3 The Property Pages dialog box

Page 11: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-11

For example, if you want to convert an Integer type variable x to a Double type variable y,use the following source code:

Dim x As IntegerDim y As Doubley = CDbl (x)

The function CType can also be used to convert a variable from one type to another. Forexample, a variable x has been declared as an Integer type and a value 53 is assigned to it.The following statement is used to convert the value of variable x to Double:

Dim x As Integer = 53Dim y As Doubley = CType(x, Double)

VB.NET performs conversion of data types automatically, but it is not always the case. VB.NETprovides two methods for data type conversion and these are given next.

Table 3-2 Functions for data type conversion

CChar Character

CByte Byte

CBool Boolean

CDate Date

CDec Decimal

CInt Integer (4 byte)

CLng Long (8 byte)

CShort Short (2 byte)

CObj Object

CStr String

CDbl Double

CSng Single

Function Arguments converted to

Page 12: Learning VB.NET Programming Concepts

3-12 Learning VB.NET Programming Concepts

1. Widening or implicit2. Narrowing or explicit

The two methods are explained below:

Widening or ImplicitThe conversion of a data type with a smaller magnitude to a greater magnitude is known asWidening conversion. Suppose you have declared and initialized two variables, an Integerand a Decimal. Next, you want to convert the Integer variable to a Decimal variable. Thelines for declaration will be as follows:

Dim acc_no As Integer = 23Dim pi As Decimal = acc_no

In the above lines, an Integer variable storing the value 23 is assigned to a Decimal variableso that the value 23.0 is stored in the Decimal variable. This conversion is possible only if theStrict option is switched to Off.

In case, the Strict option is On and you want to assign the value of variable pi to the variableacc_no, you will get the following error message:

Option Strict disallows implicit conversion from Decimal to Integer

It means that a Decimal data type cannot be converted to an Integer data type because aDecimal data type has a greater magnitude than an Integer data type.

Narrowing or ExplicitTo convert a data type with a greater magnitude to a smaller magnitude, you can use theexplicit method of conversion. For example, if you want to assign the value of variable pi tothe variable acc_no, the statement for this conversion will be as follows:

acc_no = CInt(pi)

This type of conversion is called Narrowing conversion.

The list of widening conversions that the VB.NET performs automatically is shown in Table 3-3.

Scope and Lifetime of VariablesThere is a scope or visibility and lifetime of every variable. The scope of a variable is the partof the source code of an application where the variable is visible and can be accessed by otherprogramming statements. The time period for which a variable exists in the memory of acomputer is called its lifetime.

Page 13: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-13

Local ScopeWhen a variable is declared within a procedure, the variable is accessible only to that particularprocedure. If the scope of a variable is limited to a particular procedure, it is said to have alocal scope. For example, if you write a procedure in which you want to calculate the sum ofodd numbers in the range of 0 to 50 with the Click event of a button, the coding will be asfollows:

Private Sub btnSum_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnSum.ClickDim x As IntegerDim S As IntegerFor x = 0 To 50 Step 1S = S + xNextMsgBox(“ The sum is” & S)End Sub

In this example, the variables x and S are local to the above procedure because they aredeclared within the above procedure and cannot be accessed from outside this scope.

These type of variables exist until the procedure is executed. Once the procedure getsterminated, the memory allocated by these variables is immediately returned back to thesystem.

Global ScopeIf a variable can be accessed by the entire application, it is said to have a global scope. Thesetypes of variables can be declared only outside a procedure. These variables are common tothe entire application procedure. If you use the access specifier Public instead of the keyword

Table 3-3 Widening conversions

Data Type Wider Data Type

Integer Double, Single, Long, Decimal

Char String

Decimal Single, Double

Double No conversion

Single Double

Short Double, Single, Long, Decimal

Long Double, Single, Decimal

Page 14: Learning VB.NET Programming Concepts

3-14 Learning VB.NET Programming Concepts

Dim with the variable, the variable becomes accessible to the entire application as well as allprojects referencing the current project. This can be illustrated through an example usingthe code given below:

Public Login As New loginPublic Favorite As New EvaluationPrivate Sub btnLogin_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnLogin.ClickLogin.Show()Login.Activate()End SubPrivate Sub btnFavorite_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnFavorite.ClickFavorite.Show()Favorite.Activate()End Sub

In this source code, although the variables Login and Favorite are declared outside theprocedures, yet both the procedures btnLogin and btnFavorite can access these variables.

Lifetime of a VariableLifetime of a variable depends on the period for which a variable retains its value. For example,a global variable retains its value till the lifetime of an application, whereas a local variableretains its value as long as the particular procedure is running. Once the procedure getsterminated, the local variable loses its existence and the allocated memory is free. To call thatprocedure again, you need to initialize it once again and recreate the variable.

OPERATORSOperators are defined as the symbols that are used when an operation is performed on thevariables. In programming, some arithmetic operators are commonly used. The list of thecommon arithmetic operators used in VB.NET is given in Table 3-4.

These operators can be used to perform some arithmetic operations. For example, the

Operators Operations

+ Addition

- Subtraction

Table 3-4 List of operators

* Multiplication

/ Division

^ Exponentiation

Page 15: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-15

subtraction operator returns the result of the subtraction of two operands. As shown in thefollowing statement, the operand 4 is subtracted from the operand 6 and the resultant value2 is assigned to the variable Diff:

Diff = 6 - 4

You can also use variables as operands, as given below:

Volume = length * width * height

Square = side ^ 2

Average = points scored / Total

There are two other special operators provided by VB.NET. These are, integer division (\)and modulus (MOD).

\ OperatorThe integer division (\) operator is used to divide two integer values. The resultant value isalways an integer. If there is a fractional part in the output, it gets eliminated. For example,the following statement assigns the value 3 to the variable Div:

Div = 19 \ 5

In the above example, when 19 is divided by 5, the resultant value is 3.8. But the value 3 willbe assigned to the variable Div.

MOD OperatorThis operator is known as the modulus operator. It also performs the division but it returnsthe remainder and not the quotient. For example, the following statement assigns the value4 to the variable Var:

Var = 19 MOD 5

In the above example, the value 4 is assigned to the variable Var, because when 19 is dividedby 5, the quotient is 3 and the remainder is 4.

Operator PrecedenceThe operator precedence determines the order of execution of operators by the compiler. Itmeans that an operator with a high precedence is used before an operator with a lowprecedence. Several operators can be used in a single statement to create an expression. Thefollowing statement assigns the sum of z, 20, x, and 7 to the variable Sum:

Sum = z + 20 + x +7

Page 16: Learning VB.NET Programming Concepts

3-16 Learning VB.NET Programming Concepts

Different operators can also be used in an expression. Consider the following example:

Result = 15 + 5 * 2

There are two methods for solving this expression, addition before multiplication andmultiplication before addition.

Addition before multiplicationIf the addition takes place before multiplication, the value assigned to the variable Resultwill be 40 (15 + 5 = 20, 20 * 2 = 40).

Multiplication before additionIf the multiplication takes place before addition, the value assigned to the variable Resultwill be 25 (15 + 10 = 25).

And, the correct answer is 25 because the multiplication operator has a higher precedencethan the addition operator.

Arithmetic expressions are evaluated from the left to the right. If an operand is between twooperators, the operator with the higher precedence will be evaluated first. Division andmultiplication have a higher precedence than addition and subtraction.

The following is the list of precedence of arithmetic operators, from the lowest to the highest:

1. Addition (+) and Subtraction (-)

2. Modulus (MOD)

3. Integer division (\)

4. Multiplication (*) and division (/)

5. Exponentiation (^)

Note that the division and multiplication operators have the same precedence. Wheneverthere are two operators with the same precedence, the operator on the left will be evaluatedfirst. Some of the examples are shown in Table 3-5.

Table 3-5 Expressions with their output

5 ^ 2 + 1 26

Expression Output

2 + 5 - 3 * 2 1

20 / 2 * 10 1

6 MOD 4 * 2 4

Page 17: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-17

Grouping with ParenthesesThere are some operations that you may want to evaluate before other operations. You cangroup such operations within parentheses. For example, in the following statement, first thevalues a, b, and c are added, then the resultant value is divided by 5, and finally it is assignedto the variable Grade.

Grade = (a+b+c) / 5

If you remove the parentheses from the above statement, first the variable c will be dividedby 5 and the resultant value will be added to the sum of variables a and b. Some of theexamples are shown in Table 3-6.

Compound Assignment OperatorsIn programming, an operation is performed on the value stored in a variable and the modifiedvalue is then assigned to the same variable. For this purpose, some special operators are usedwhich are called the compound assignment operators. The list of these operators is given inTable 3-7.

For example,y+=5

In the above example, 5 is added to the value of y and then assigned to the variable y.

Table 3-6 Examples of grouping within parentheses

Expression

(7 + 4) * 2

18 / (8 - 2)

(5 - 2) / (2+1)

22

Output

3

1

Table 3-7 Compound assignment operators

Assignment operator Example Equivalent to

+=

-=

*=

/=

\=

y += 5

y -= 7

y *= 9

y /= 3

y \= 2

y = y + 5

y = y - 7

y = y * 9

y = y / 3

y = y \ 2

Page 18: Learning VB.NET Programming Concepts

3-18 Learning VB.NET Programming Concepts

CONSTANTSIn programming, there are some variables whose values are fixed and cannot vary duringexecution. These variables are called constants. The syntax of declaring a constant is as follows:

Const constantname As type = value

For example, your program is supposed to do some mathematical calculation and you haveto calculate the area and circumference of a circle as well as a cone with the same radius. Youcan declare the value of the radius once in the program, as follows:

Const radius As Integer = 2.8796

You can now use it anywhere in the program.

For example,area of a circle = 3.14159 * radius2

circumference of a circle =2 * 3.14159 * radius

In the above example, for calculating the area and circumference of a circle, there is no needto enter the value of the radius. Whenever you enter the constant radius, the compiler willreplace it by the value (2.8796) declared in the beginning of the program.

The constants are preferred in programming for the following three reasons:

1. You cannot change the value of a constant after its declaration. This is one of the safetycharacteristics of using constants.

2. The compiler processes the constants faster than the variables. The compiler replacesthe constant names by their values and thus the program executes faster.

3. If you want to change the value of a constant, it can be changed in its declaration part.There is no need to make changes in the entire program.

Constants can be Public or Private. For example, you may want to use the constant pi thatcan be accessed by any procedure. The following statement is used to declare the constant pias Public:

Public Const pi As single = 3.14159

There are many constants used in VB.NET. They are grouped on the basis of their propertiesand each possible value of a property forms an enumeration. An enumeration is a set ofuser-defined integral constants. It is used when you want a property to take one value from aset of fixed values. Whenever you type the name of a property, the enumeration list is displayedwith all possible values of the given property. The editor knows which enumeration is to beapplied and you can choose the required value. A list of possible values of the CheckAlignproperty of a radio button is shown in Figure 3-4.

Page 19: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-19

FORMATTING NUMBERSFormatting is a method of displaying a value in different ways. For example, a number 3570can be displayed in many ways, as follows:

3570

3570.00

3570.0

There are several intrinsic functions which are provided by VB.NET to format numbers. Thelist of these functions is given in Table 3-8.

FormatNumberThis function formats a number to two decimal places by default. For example, a number3570 can be formatted as 3,570.00. The following code illustrates the usage of theFormatNumber function:

Figure 3-4 The values of the CheckAlign property

Table 3-8 Functions for formatting numbers

Function Description

FormatNumber

FormatDateTime

FormatPercent

This function is used to format a specifiednumber upto decimal points.

This function is used to format date,time, or both the expressions.

This function is used to format a numberas a percent.

Page 20: Learning VB.NET Programming Concepts

3-20 Learning VB.NET Programming Concepts

Dim func As Singlefunc = 3570.876lblfunc.Text = FormatNumber (func)

The last statement assigns the value of variable func (3570.876) to the function FormatNumber.This function then returns the string “3570.88” to the Text property of lblfunc.

There is another way of using this function that will help you to format a number to morethan two decimal places. The code is as follows:

Label1.Text = FormatNumber (number, 3)

Consider a number 3570.8768768. If you want to format this number to three decimal places,the code will be as follows:

lblaverage.Text = FormatNumber (3570.8768768, 3)

where lblaverage is the value assigned to the Name property of the Label control. Thefunction returns the string 3,570.877 to the Label control. Note that all digits after .877 willbe truncated.

FormatDateTimeThis function is used to format the date expression. The syntax for FormatDateTime is asfollows:

FormatDateTime (DateExpression [, Format])

In the above syntax, the first argument DateExpression specifies the date that is to beformatted. And, the second argument within the square brackets is optional. It specifies themethod of formatting.

The following is the code for illustrating the usage of FormatDateTime function:

Dim day As Dateday = TodaylblDate.Text = FormatDateTime (day, DateFormat.LongDate)

In the second line, the keyword Today is used to retrieve the current date from the systemand save the value in the variable day. In the third line, the value of the variable day isformatted to a long date format such as, “Tuesday, July 4, 2006”, and then assigned to theText property of lblDate.

Whenever you write the third line, a list of values will be displayed as soon as you type commaafter the variable day, as shown in Figure 3-5.

Page 21: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-21

The list of these values with their description is as follows:

DateFormat.LongDateThis value is used to format a date in the Long format. It contains the day of the week,month, date, and year. For example, Saturday, May 12, 2007.

DateFormat.ShortDateThis value is used to format a date in the Short format. It contains the month, date, and year.For example, 5/12/2006.

DateFormat.GeneralDateThis value works in the same way as DateFormat.ShortDate.

DateFormat.LongTimeThis value is used to format a time in the Long format. It contains hour, minute, second, andthe indicators, AM or PM. For example, 07:20:12 AM.

DateFormat.ShortTimeThis value is used to format a time in the Short format. It contains two digits for the hour andtwo digits for the minute. It follows the 24 hours format. For example, 19:20.

FormatPercentThis function is used to format its numeric arguments to percent by multiplying the argumentby 100. Then, it rounds the argument to two decimal places and also adds a percentage sign(%). For example, to format .50 to 50.00%, the code will be as follows:

Dim x As Singlex = 0.5lblpercent.Text = FormatPercent(x)

In the last statement lblpercent.Text = FormatPercent(x), the variable x is passed as anargument to the function FormatPercent. This function returns the value 50.00% which isassigned to the text property of the Label control lblpercent.

As mentioned above, the function FormatPercent formats a number to two decimal places bydefault. But, you can also use this function to format a number to more than two decimalplaces. Fox example, to format .50 to four decimal places, the code will be as follows:

Figure 3-5 The values of FormatDateTime property

Page 22: Learning VB.NET Programming Concepts

3-22 Learning VB.NET Programming Concepts

Dim x As Singlex = 0.5lblpercent.Text = FormatPercent(x, 4)

The last statement will multiply the value of x (0.5) by 100 and then round the output to fourdecimal places (50.000%). The resultant value will be assigned to the Text property of theLabel control.

CREATING GROUP BOXA box with a rectangular border and an optional title, which appears in the upper-left corner,is called a group box. Other controls can be placed inside the GroupBox control. If youmove the GroupBox control, all controls, which are within it, will also move.

The following application illustrates the use of GroupBox control.

Create an application to display the Name, Address, and Phone number entered by theuser.

This application will prompt the user to enter the general details such as Name, Address,and Phone number.

The following steps are required for creating this application:

Step1Start a new project and save it as ch03_application2.

Step 2Add a GroupBox control to the form.

Step 3Drag the GroupBox control to the center of the form, as shown in Figure 3-6.

Application 2

Figure 3-6 The Form1 with GroupBox control

Page 23: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-23

Step 4Add three Label controls and three TextBox controls to the GroupBox control.

Step 5Change the value of the Text property of the controls as follows:

GroupBox1 to Personal DetailsLabel1 to NameLabel2 to AddressLabel3 to Phone Number, as shown in Figure 3-7.

Step 6Press F5 on the keyboard to execute the application. After execution, the form will be displayed,as shown in Figure 3-8.

Figure 3-7 The Form1 with Personal Detailsgroup box and other controls

Figure 3-8 The Personal Details group boxafter execution

Page 24: Learning VB.NET Programming Concepts

3-24 Learning VB.NET Programming Concepts

LOCATING LOGIC ERRORAn error that does not stop the execution of an application but generates incorrect results iscalled a logic error. For example, errors such as copying an incorrect value to variable,mathematical mistakes, and assigning a value to a wrong variable, result in a logic error.Although these errors are difficult to locate, but VB.NET provides some debugging methodsin order to easily locate these type of errors.

The debugging methods include setting breakpoints in your application. Breakpoint meansselecting a line in the source code where the code can break. During execution, if a breakpointis encountered, the application will pause and enter into a break state. While the applicationis in the break state, the lines of code will be executed one-by-one. After the execution of eachline, you can recheck the variable and its property contents. In this way, you can find the linesof code that are causing errors in the application.

The following application illustrates the concept of logic errors.

Create an application to calculate the average of the points scored by a student.

This application will prompt the user to enter the details of a student such as the name andthe points scored by him in Mathematics, English, and Science. It will also display theaverage of the points scored.

The following steps are required to create this application:

Step 1Start a new project and save it as ch03_application3.

Step2Add five Label controls, five TextBox controls, and three Button controls to the form.

Step 3Change the values of the Text property of the controls as follows:

Form1 to StudentLabel1 to Enter NameLabel2 to Points scored in MathematicsLabel3 to Points scored in EnglishLabel4 to Points scored in ScienceLabel5 to AverageButton1 to ShowButton2 to ClearButton3 to Exit

Step 4Change the value of the Name property of the Button control to btnShow.

Application 3

Page 25: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-25

The form will appear as shown in Figure 3-9.

Step 5Press F5 on the keyboard to execute theapplication.

Step 6In this step, you need to enter the name of astudent and also the points scored by him inthree subjects so as to calculate the average of thepoints scored. Enter the value 78 for all threesubjects.

Step 7Choose the Show button on the Student form tocalculate the average points scored in threesubjects. The value 182 will be displayed, which isan incorrect value. The correct value is 78.

Step 8Open the code window and locate the line of source code (Mathematics = TextBox2.Text)that is given to pause the execution of the application.

Step 9Right-click the mouse button at the location indicated in Figure 3-10. The line of code will behighlighted with a dot, as shown in Figure 3-11. This line now becomes a breakpoint. You canalso set a breakpoint by pressing F9 on the keyboard.

Step 10Execute the application again. Enter the value 78 for three subjects.

Figure 3-9 The Student form

Figure 3-10 Representation of the cursor position

Line to pause the execution

Page 26: Learning VB.NET Programming Concepts

3-26 Learning VB.NET Programming Concepts

Step 11Choose the Show button on the Student form. The line set as a breakpoint will be highlightedin yellow with a small arrow on its left margin, as shown in Figure 3-12. This happens becausewhen a breakpoint is encountered by VB.NET environment, it will go into the break stateand the code window will be displayed.

Step 12You can check the contents of a variable with the help of three windows: Autos, Locals, andWatch 1. Whenever you set a breakpoint in an application and execute it, you will see anAutos window, as shown in Figure 3-13. The Locals and Watch 1 tabs are located at thebottom of the screen.

Figure 3-11 The breakpoint code

Figure 3-12 The breakpoint in break state

Page 27: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-27

The description of these windows is as follows:

Autos windowThis window contains the list of variables in the current statement with their values and datatypes.

Locals windowThis window contains the list of the variables in the procedure with their values and datatypes, as shown in Figure 3-14.

Watch 1 windowIn this window, you can add the variables that you want to check. It will display only thevalues and data type of the added variables, as shown in Figure 3-15. There are four Watchwindows available in VB.NET.

Step 13Note that there is a blue colored line in the Watch 1 window. Click on this line; you will get ablank line. Now, type Mathematics and press ENTER on the keyboard and check its value.Next, type English and again, press ENTER. In the same way, type Science and Average inthe window. All variables have 0 as their current value, as shown in Figure 3-16.

Step 14Choose Debug > Step Into from the menu bar or press F11 on the keyboard. The highlightedstatement will be executed and 78 will be assigned as the value to the variable Mathematics.The next statement will be highlighted now. Press F11 on the keyboard two more times andthen notice the value of the variables English and Science. Their values will also be 78.

Figure 3-13 The Autos window

Figure 3-14 The Locals window

Page 28: Learning VB.NET Programming Concepts

3-28 Learning VB.NET Programming Concepts

Step 15The following is the next highlighted statement:

score = Mathematics + English + Science / 3

As all three variables have 78 as their current value, the variable Average must also have thesame value. But the Watch 1 window will display 182 as the average value. This means thatthere is an error in the statement. Recall the operator precedence, which has been discussedearlier in this chapter. The division (/) operator has a higher precedence than the addition(+) operator, so VB.NET first executes the division of the value of the variable Science by 3(78/3). The result 26 will be added to the values of the variables Mathematics and English(78+78+26=182).

Step 16Choose Debug > Stop Debugging from the menu bar to stop the application and insert apair of parentheses in the code as follows:

score = (Mathematics + English + Science) / 3

Step 17Next, remove the breakpoint from the code. To remove the breakpoint, position the cursorover the dot and click on it, or press CTRL + SHIFT + F9 on the keyboard.

Figure 3-16 The Watch 1 window with different variables

Figure 3-15 The Watch 1 window

Page 29: Learning VB.NET Programming Concepts

Variables, Operators, and Constants 3-29

Step 18Execute the application and enter 78 as the current value of the variables Mathematics,English, and Science. You will get the correct value (78) of the variable Average.

Answer the following questions and then compare them to the answers given at the end ofthis chapter:

1. The storage location used for holding some information in the computer’s memory iscalled a __________.

2. Variables are used to copy and store the values in order to __________ them.

3. The red line under a variable is the indication of an __________.

4. If the scope of the variable is limited to a procedure, it is called __________.

5. VB.NET executes the statements within a procedure in a __________ order.

Answer the following questions:

1. If a variable can be accessed by the entire application, it is called __________.

2. __________ of a variable depends on the period for which a variable retains its value.

3. Once the procedure is over, the __________ variable loses its existence and the allocatedmemory is free.

4. The variables that do not change values are called __________.

5. The compiler processes the constants faster than the __________.

Create an application that accepts points scored in five subjects from the user and calculatestheir percentage. The output of the application should be similar to Figure 3-17.

Self-Evaluation Test

Review Questions

Exercises

Exercise 1

Page 30: Learning VB.NET Programming Concepts

3-30 Learning VB.NET Programming Concepts

Figure 3-17 Output of Exercise 1

Create an application that displays the message God Bless You....... concatenated with Myson. The output of the application should be similar to Figure 3-18.

Answers to Self-Evaluation Test1. variable, 2. manipulate, 3. error, 4. local, 5. sequential

Exercise 2

Figure 3-18 Output of Exercise 2