Visual Basic Variables
Visual Basic Variables
Variables
A
Every
Name - reference to the location - cannot be changed Value - the information that is stored - can be changed during program execution, hence the name variable Data Type - the type of information that can be stored - cannot be changed
You the programmer make up a name for the variable Visual Basic associates that name with a location in the computer's RAM The value currently associated with the variable is stored in that memory location You simply use the name you chose when you need to access the value
Usage of Variables
` ` ` ` `
Copy and store values entered by the user Perform arithmetic manipulation on values Test values to see if they meet a criteria Temporarily hold and manipulate the value of a control property Hold data/information so that it can be recalled for use at a later point in the code
Integer variables: Long, Integer, Short, Byte Floating-point variables: Single, Double Fixed decimal point variable: Decimal Boolean variables: True, False Character variable: Char Text variable: String The Object variable
` ` `
Default data type assigned by Visual Basic Can store many different types of data Less efficient than other data types
Prefix Size
byt shr int lng sng dbl dec chr bln str dtm obj 1 byte 2 byte 4 byte 8 byte
Values
positive integer value from 0 to 255 integer from 32,768 to +32,767 integer from +/- 2,147,483,647 integer from +/- 9,223,372,036,854,775,807
4 byte single-precision, floating-point number 8 byte double-precision, floating-point number 16 byte number with up to 28 significant digits 2 byte Any single character 2 byte True or False (4 byte) Text - Any number/combination of characters 8 byte 8 character date: #dd/mm/yyyy# (4 byte) An address that refers to an object
Variable Names
First character must be a letter or underscore Must contain only letters, numbers, and underscores (no spaces, periods, etc.) Can have up to 255 characters Cannot be a VB language keyword Naming Conventions
Should be meaningful Follow 3 char prefix style - 1st 3 letters in lowercase to indicate the data type After that, capitalize the first letter of each word Example: intTestScore
Declaring a Variable
` `
A variable declaration is a statement that creates a variable in memory Syntax: Dim VariableName As DataType
` ` ` `
Dim (short for Dimension) - keyword VariableName - name used to refer to variable As - keyword DataType - one of many possible keywords to indicate the type of value the variable will contain
A starting or initialization value may be specified with the Dim statement Good practice to set an initial value unless assigning a value prior to using the variable Syntax: Dim VariableName As DataType = Value
Just append " = value to the Dim statement = 5 assigning a beginning value to the variable
Variable MUST be declared prior to the code where they are used Variable should be declared first in the procedure (style convention) Declaring an initial value of the variable in the declaration statement is optional
`
Literal
` ` `
Actual value/data/information Similar to a variable, but can NOT change during the execution of a program. Examples of Literals:
` ` ` `
Numeric: 5 ; 157 ; 195.38256 String: Paul ; Hello!!! ; Jackson, AL 36545 Char: a ; 1 ; ? ; @ Boolean: True ; False
Named Constants
`
For example: decTotal *= 1.06 Adds 6% sales tax to an order total The reason for multiplying decTotal by 1.06 isnt always obvious If sales tax rate changes, must find and change every occurrence of .06 or 1.06
Use of named constants resolves both these issues Can declare a variable whose value is set at declaration and cannot be changed later: Syntax: Const CONST_NAME As DataType = Value
Looks like a normal declaration except: ` Const used instead of Dim ` An initialization value is required ` By convention, entire name capitalized with underscore characters to separate words
Can change all occurrences in the code simply by changing the initial value set in the declaration
` `
Scope of Variables
What Indicates the part of the program where the variable can be used When From the variable declaration until the end of the code block (procedure, method, etc.) where it is declared
Variable cannot be used before it is declared Variable declared within a code block is only visible to statements within that code block
Called Local Variable
Can be declared at the beginning of the class code window (General Declarations section) and be available to all blocks
Called Form Level Variable
Variables that share the same scope cannot have the same name (same name ok if different scope)
Lifetime of Variables
` `
What Indicates the part of the program where the variable exists in memory When From the beginning of the code block (procedure, method, etc.) where it is declared until the end of that code block
`
When the code block begins the space is created to hold the local variables
`
When the code block ends the local variables are destroyed
`
Assignment Statement
` `
Syntax: variablename = expression Assigns the value of the expression to the variable. (The variable must be on the left and the expression on the right.) Example:
` ` ` `
An implicit type conversion is an attempt to automatically convert to the receiving variables data type Converting an integer to a single Dim sngNumber as Single = 5 Converting a decimal to an integer Dim intCount = 12.2 intCount becomes 12
VB provides a set of functions that perform data type conversions These functions will accept a literal, variable name, or arithmetic expression The following narrowing conversions require an explicit type conversion
` ` `
Boolean, Date, Object, String, and numeric types represent different sorts of values and require conversion functions as well
The Val function is a more forgiving means of performing string to numeric conversions Uses the form Val(string) If the initial characters form a numeric value, the Val function will return that Otherwise, it will return a value of zero
Returns a string representation of the value in the variable calling the method Every VB data type has a ToString method Uses the form VariableName.ToString For example
Dim number as Integer = 123 lblNumber.text = number.ToString Assigns the string 123 to the text property of the lblNumber control
Arithmetic Operators
^ * / \ MOD + & Exponential Multiplication Floating Point Division Integer Division Modulus (remainder from division) Addition Subtraction String Concatenation (putting them together)
Examples of use:
` ` ` ` `
decTotal = decPrice + decTax decNetPrice = decPrice - decDiscount dblArea = dblLength * dblWidth sngAverage = sngTotal / intItems dblCube = dblSide ^ 3
The backslash (\) is used as an integer division operator The result is always an integer, created by discarding any remainder from the division Example
` ` `
intResult = 7 \ 2 result is 3 shrHundreds = 157 \ 100 result is 1 shrTens = (157 - 157 \ 100 * 100) \ 10 result is ?
This operator can be used in place of the backslash operator to give the remainder of a division operation
intRemainder = 17 MOD 3 result is 2 dblRemainder = 17.5 MOD 3 result is 2.5
Any attempt to use of the \ or MOD operator to perform integer division by zero causes a DivideByZeroException runtime error
Concatenating Strings
` ` ` ` `
Concatenate: connect strings together Concatenation operator: the ampersand (&) Include a space before and after the & operator Numbers after & operator are converted to strings How to concatenate character strings
` ` ` `
strFName = "Bob" strLName = "Smith" strName = strFName & " strName = strName & strLName
Bob Bob
Smith
` `
Often need to change the value in a variable and assign the result back to that variable For example: var = var 5 Subtracts 5 from the value stored in var
Operator Usage += -= *= /= \= &= x += 2 x -= 5 x *= 10 x /= y x \= y x &= . Equivalent to x=x+2 x=x5 x = x * 10 x=x/y x=x\y x = x & . Effect Add to Subtract from Multiply by Divide by Int Divide by Concatenate
Operator precedence tells us the order in which operations are performed From highest to lowest precedence:
` ` ` ` `
Exponentiation (^) Multiplicative (* and /) Integer Division (\) Modulus (MOD) Additive (+ and -)
` `
Parentheses override the order of precedence Where precedence is the same, operations occur from left to right
Parenthesis Exponential Multiplication / Division Integer Division MOD Addition / Subtraction String Concatenation Relational Operators (< , > , >= , <= , <>) Logical Operators (AND, OR, NOT)
Precedence Examples
` ` `
` ` ` ` ` `
6 * 2 ^ 3 + 4 / 2 = 50 7*4/26=8 5 * (4 + 3) 15 Mod 2 = 34
intX = 10 intY = 5 intResultA = intX + intY * 5 iResultB = (intX + intY) * 5 dResultA = intX - intY * 5 dResultB = (intX - intY) * 5
Programming Examples
` `
Redo the Calculate Gross Pay example from Lecture 4 using variables. Redo the Calculator from HW2 using variables.
Homework
`
Homework 3
` ` `
Visual Basic - Variables See handout for details and due date Questions?