Unit 2 BCA 5
Unit 2 BCA 5
Faculty E- Notes
1
TABLE OF CONTENTS
2
1. Data Types:
Data Types are useful to define a type of data the variable can hold, such
as integer, float, string, etc. Anything enclosed in single quotes represents
character data. Numbers without fractions represent integer data while
numbers with fractions represent real data. Anything enclosed in double
quotes represent the String.
Various data types used in Visual Basic are shown in the below figure:
3
8 Bytes (64 It holds double precision values. It
5. Double bits) allows upto 14 digits of precision.
8 Bytes (64 It is used to hold currency data. It
6. Currency bits) allows upto 4 digits of precision.
2 Bytes (16 It takes only two values: True or
7. Boolean bits) False.
It is used to hold date and time values.
8 Bytes (64 It can store dates in the range January
8. Date bits) 1,100 to December 31, 9999
String It is used to hold multiple characters.
(Fixed For fixed length string, range varies
9. Length) String Length from 1 to 65,400
String
Range for variable length string is
(Variable String Length
from 0 to 2 billion characters.
10. Length) + 10 bytes
It is used to hold and refer to objects
11. Object 4 Bytes like controls and forms.
It can hold data of any data types
except fixed length string or user-
defined data types. If it holds only
Variant numeric values, then, its size is 16
12. (Numeric) 16 Bytes bytes.
Variant Length + 22
It is same as variable length string.
13. (Text) bytes
2. Variables:
A named storage location whose contents can be varied is called variable.
4
A variable has two associated things with it: the name and its datatype.
The variable name is used to refer to the value stored in it and the data
type tells what kind of value is to be stored in this variable.
Rules for declaring the variable name are:
• Must begin with a letter.
• Cannot contain any special character other than @
• Maximum size is 255 characters.
• Must be unique within the same scope.
2.1 Declaration of Variables:
Syntax:
Where,
Dim and As are the keywords and v-name1 and v-name2 are the
variable names.
E.g.:
5
& Long
! Single
# Double
@ Currency
$ String
E.g.:
Dim num%
Dim name$
Dim phone&
Here, num is an Integer variable, name is a String variable and Phone is a
long variable.
2.3 Fixed Length and Variable Length String Declaration
Fixed Length String Declaration:
To declare the fixed length string, we need to specify its size. If a fixed
length string is assigned more characters than its size, then, the extra
characters are truncated without warning.
E.g.:
Dim name As String * 20
Dim address As String * 60
Here, name is a String of size 20 characters while address is a string of
size 60 characters.
Variable Length String Declaration:
The size of the string is not specified in the declaration of the variable
length string.
E.g.:
Dim Name As String
2.4 Forcing Variable Declaration
6
There are two types of variable declaration:
a) Implicit Declaration:
There are two ways to declare a variable implicitly:
I. Without DataType:
If a variable has been declared with Dim but its data type is
missing, then, VB assumes its datatype to be variant.
E.g.:
Dim A, B
II. Using Type Declaration Character:
E.g.:
Dim A%
Here, A is an integer data type.
Note: Use of variant data type should be avoided as it takes
larger memory compared to other datatypes.
b) Explicit Declaration:
To enforce explicit declaration in the existing project, you need to
type Option Explicit in the General Section of each module.
Steps to place the Option Explicit statement in each module are:
I. Click Options Item in the Tools Menu.
II. Option Dialog box appears.
III. Click the Editor tab.
IV. Check Require Variable Declaration Option.
V. Finally, click Ok.
2.5 Types of Variables:
a) Object Variable:
An object variable refers to one of Visual Basic’s Objects. An
object variable can be used to access the actual object. The object
variable takes 4 bytes of storage in memory.
7
E.g.:
In a program, suppose there are two command buttons with the
name: cmdbtn1 and cmdbtn2. We will create two object variables:
a and b which are going to store the objects: cmdbtn1 and cmdbtn2.
Dim a As Command Button
Dim b As Command Button
Set a = cmdbtn1
Set b = cmdbtn2.
Now we can make changes in the properties of these button using
the object variables: a and b.
a.Caption = ‘Hi!’
b.Text= ‘Submit’
b) Variant Variable:
This is the most flexible datatype as it can accommodate all other
types. A variable declared as variant in VB is handled by VB
according to the variable’s current contents.
E.g.:
Dim VarValue
VarValue = “100”
VarValue = VarValue – 70
VarValue = VarValue & “+”
In the first statement, VarValue contain a string value 100. In the
second statement, VarValue contains an Integer value 30 while in
the third statement, VarValue contains a String value 30+.
Variant Dataype can contain values that other datatypes cannot
handle. These values are:
I. The Null Value:
8
In database applications, Null is commonly used to indicate
the unknown value or missing value. If Null is assigned to
variable other than variant, a trappable error occurs.
E.g.: In an employee database, if the age of an employee is
not known, then,
Age = Null
II. The Error Value:
This is a peculiar value that allows you to write functions
that return Variant types or errors. If the function carries out
its operations successfully, the result is returned as usual. If
an error occurs, then, the function can return an ‘Error Value.
E.g.:
Result = myfunction(argument)
If IsError(Result) Then
[Handle Error]
Else
[Use Result]
EndIf
III. The Empty Value:
If a variable has been declared as Variant but has not been
initialized, then, its value is empty. The empty value is
different from a zero length string.
The empty value is used with numeric, string and date
variables.
c) Static Variables
These variables retain their values even after the parent procedure
is over and when the procedure gets executed again, the static
variable’s old value is accessible. However, the scope of a local
9
static variable remains unchanged, i.e., it remains private to the
procedure.
Static variables are useful for keeping track of state information
across multiple calls to a method.
E.g.:
Module Module1
Sub Main()
For i As Integer = 1 To 5
ShowStaticVar()
Next
End Sub
Sub ShowStaticVar()
Static counter As Integer = 0
counter += 1
Console.WriteLine("Counter: " & counter)
End Sub
End Module
In this code:
10
• Local or Private – A variable declared in a procedure is known as
local or private variable. The value of variable cannot be accessed
from another procedure.
E.g.:
Sub Example()
Dim Var As Integer = 10
Console.WriteLine(localVar)
End Sub
Here Var is a local variable and is accessible only within this
procedure Example().
• Module – A variable that is available inside a module, i.e., to all
the procedures in that module is said to have Module Scope.
E.g.:
Module ExampleModule
Dim moduleLevelVar As Integer = 30
Sub ShowVar()
Console.WriteLine(moduleLevelVar)
End Sub
End Module
Note: Dim or Private keywords if used inside the procedure for
variable declaration, they create local variables. If Dim or Private
keywords are used inside a module, i.e., outside all the procedures,
they create Module variables.
• Public – The Variables that are available to all the procedures and
modules in an application are said to have Public Scope. An
application can have may procedures and modules and they all can
share public variables.
11
Variable declared in General section using “public” keyword are
available throughout the project, in all the forms and modules.
Note: You cannot use public in procedure.
Lifetime of Variables
Local Variables:
o Lifetime is limited to the execution of the procedure.
o Memory is released once the procedure completes.
Module-Level Variables:
o Lifetime is tied to the lifetime of the module instance.
o Exists as long as the module instance is in use.
Public Variables:
o Lifetime is equal to the program-run or application run, i.e., as long as the
program is running.
3. Constants:
Constants are the quantities whose values don’t change during the
execution of the program. There are two types of constants:
a) Named Constants
The constants that are defined by the user are known as Named
Constants. Named constants are declared using the const keyword.
Syntax:
Const constant_name As Type = Expression
where,
constant_name should be a valid name and As type is the datatype.
Expression is the numeric or string value that has to be assigned to
the constant.
E.g.:
Const PI = 3.1415926
Scope of Named Constants:
12
By declaring a constant in the Declaration section of a form,
standard or class module rather than within a procedure, the
Constant will be available to all the procedures in the module.
By declaring a constant using public keyword, it is available
throughout the application.
Declaring a constant in the procedure will be available to that
procedure only.
b) Intrinsic Constants
Intrinsic Constants are system-defined constants. Several sets of
intrinsic constants are stored in the library files and available for
use in VB programs. Some examples of Intrinsic Constants are:
vbOkOnly, vbQuestion, vbInformation, vbExclamation, vbCritical,
etc
4. VB Operators
VB supports different types of operators that are helpful in performing a
variety of operations. All the operators have their own specified
precedence that determines which operation will be executed first in an
expression involving multiple operations. VB supports following types of
operators:
a) Arithmetic Operators
b) Concatenation Operators
c) Logical Operators
d) Relational Operators
4.1Arithmetic Operators
The below table presents a list of all the arithmetic operators supported by
Visual Basic.
13
4.2Concatenation Operators
The process of combining two strings into one is called string
concatenation and the operators that are used to perform string
concatenation are: (+) and & (ampersand).
E.g.:
Dim str1, str2 As String
str1 = “Visual” + “Basic”
str2 = “Visual” & “Basic”
4.3Relational Operators
Relational Operators are used to compare two expressions. A relational
operation results in a Boolean value.
14
4.4 Logical Operators
The logical operators are used to combine two or more conditions.
15
5. InputBox Function
The InputBox function is used to read data from the user. This function
displays a dialog box that asks the user to enter some data.
Syntax of InputBox function:
Memory_variable = InputBox(prompt, title, default, xpos, ypos)
where,
memory_variable: is a string or variant data type
prompt: is a string expression that is displayed as the message in the
dialog box
title: is a string expression that is displayed in the title bar of the dialog
box.
default: is a string expression that appears in the input box as the default
value if no other input is provided.
xpos and ypos are the coordinates of the InputBox
E.g.:
Data = InputBox(“Enter a number”, “Input Data”, “0”)
16
6. MsgBox Function
A MsgBox is used to display a message to the user. One can display a
message, an optional icon, a title bar caption and command button(s) in a
message box. The MsgBox function displays a message in a dialog box,
waits for the user to click a button and returns an integer indicating which
button the user clicked.
Syntax of MsgBox function is:
MsgBox(prompt, buttons, title, helpfile, context)
Where,
Prompt: String expression that is displayed as message in the dialog box.
Buttons: Numeric Expression that is the sum of values specifying the
number and type of buttons to display, the icon style to use and the
identity of default button
Title: String expression to be displayed in the title bar of the dialog box.
Helpfile and context are only applicable when a helpfile has been set up
to word with an application.
The Buttons Argument:
Following table shows the value and type of buttons displayed in the
dialog box. By default, the value is 0.
17
The Icons Style
Below table shows the various icon styles:
Return Values
When there are multiple buttons on the message box, then, to check
which button the user has clicked, there are return values associated with
each button.
18
Examples of MsgBox:
a) MsgBox(“VB is a fun”)
b) MsgBox(“The Roll No. field must not be blank”, vbExclamation)
c) MsgBox(“Is the result correct?”, vbYesNoCancel + vbQuestion,
“Result verification box”)
19
choice = MsgBox(“Are you sure you want to quit?”, vbYesNo +
vbQuestion)
If choice = vbYes Then
End
End If
7. Print Method
Print method is used to display text on a form, a picturebox, a printer and
the immediate (debug) window.
Syntax:
Object.Print [OutputList]
Where,
Object: can be either a Form, a PictureBox, Debug Window or a Printer
(Note: The object argument is optional; if omitted; the print method prints
on the current form)
OutPutList: A list of one or more numeric or string expressions. Items in
the output list may be separated with semicolons or commas.
E.g.:
Print “Hi!”;
Print “Visual Basic”
Output: Hi! Visual Basic
20