Smartphones
Swift is a new programming language developed by Apple Inc for iOS and OS X development. Swift adopts the best of C and Objective-C, without the constraints of C compatibility.
Swift uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift programs to run on many existing iOS 6 and OS X 10.8 platforms.
Swift comes with playground feature where Swift programmers can write their code and execute it to see the results immediately.
The first public release of Swift was released in 2010. It took Chris Lattner almost 14 years to come up with the first official version, and later, it was supported by many other contributors. Swift has been included in Xcode 6 beta.
Swift designers took ideas from various other popular languages such as Objective-C, Rust, Haskell, Ruby, Python, C#, and CLU.
Swift provides a Playground platform for learning purpose and we are going to setup the same. You need xCode software to start your Swift coding in Playground. Once you are comfortable with the concepts of Swift, you can use xCode IDE for iSO/OS x application development.
To start with, we consider you already have an account at Apple Developer website. Once you are logged in, go to the following link − Download for Apple Developers
This will list down a number of software available as follows
Now select xCode and download it by clicking on the given link near to disc image. After downloading the dmg file, you can install it by simply double-clicking on it and following the given instructions. Finally, follow the given instructions and drop xCode icon into the Application folder.
Now you have xCode installed on your machine. Next, open Xcode from the Application folder and proceed after accepting the terms and conditions. If everything is fine, you will get the following screen −
Select Get started with a playground option and enter a name for playground and select iOS as platform. Finally, you will get the Playground window as follows −
If you create the same program for OS X program, then it will include import Cocoa and the program will look like as follows −
When the above program gets loaded, it should display the following result in Playground result area (Right Hand Side).
Hello, playground
Congratulations, you have your Swift programming environment ready and you can proceed with your learning vehicle "Tutorials Point".
We have already seen a piece of Swift program while setting up the environment. Let's start once again with the following Hello, World! program created for OS X playground, which includes import Cocoa as shown below
If you create the same program for iOS playground, then it will include import UIKit and the program will look as follows −
When we run the above program using an appropriate playground, we will get the following result −
Hello, World!
Let us now see the basic structure of a Swift program, so that it will be easy for you to understand the basic building blocks of the Swift programming language.
You can use the import statement to import any Objective-C framework (or C library) directly into your Swift program. For example, the above import cocoa statement makes all Cocoa libraries, APIs, and runtimes that form the development layer for all of OS X, available in Swift.
Cocoa is implemented in Objective-C, which is a superset of C, so it is easy to mix C and even C++ into your Swift applications.
A Swift program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Swift statement consists of three tokens
Comments are like helping texts in your Swift program. They are ignored by the compiler. Multi-line comments start with /* and terminate with the characters */ as shown below −
Multi-line comments can be nested in Swift. Following is a valid comment in Swift −
Single-line comments are written using // at the beginning of the comment.
Swift does not require you to type a semicolon (;) after each statement in your code, though it’s optional; and if you use a semicolon, then the compiler does not complain about it.
However, if you are using multiple statements in the same line, then it is required to use a semicolon as a delimiter, otherwise the compiler will raise a syntax error. You can write the above Hello, World! program as follows −
A Swift identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with an alphabet A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). Swift does not allow special characters such as @, $, and % within identifiers. Swift is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Swift. Here are some examples of acceptable identifiers −
To use a reserved word as an identifier, you will need to put a backtick (`) before and after it. For example, class is not a valid identifier, but `class` is valid.
class | deinit | enum | extension |
func | import | init | internal |
let | operator | private | protocol |
public | static | struct | subscript |
typealias | var |
break | case | continue | default |
do | else | fallthrough | for |
if | in | return | switch |
where | while |
associativity | convenience | dynamic | didSet |
final | get | infix | inout |
lazy | left | mutating | none |
nonmutating | optional | override | postfix |
precedence | prefix | Protocol | required |
right | set | Type | unowned |
weak | willSet |
A line containing only whitespace, possibly with a comment, is known as a blank line, and a Swift compiler totally ignores it.
Whitespace is the term used in Swift to describe blanks, tabs, newline characters, and comments. Whitespaces separate one part of a statement from another and enable the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
there must be at least one whitespace character (usually a space) between var and age for the compiler to be able to distinguish them. On the other hand, in the following statement −
no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some for better readability.
A literal is the source code representation of a value of an integer, floating-point number, or string type. The following are examples of literals −
While doing programming in any programming language, you need to use different types of variables to store information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory.
You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
Swift offers the programmer a rich assortment of built-in as well as user-defined data types. The following types of basic data types are most frequently when declaring variables −
We have listed here a few important points related to Integer types −
The following table shows the variable type, how much memory it takes to store the value in memory, and what is the maximum and minimum value which can be stored in such type of variables.
Type | Typical Bit Width | Typical Range |
---|---|---|
Int8 | 1byte | -127 to 127 |
UInt8 | 1byte | 0 to 255 |
Int32 | 4bytes | -2147483648 to 2147483647 |
UInt32 | 4bytes | 0 to 4294967295 |
Int64 | 8bytes | -9223372036854775808 to 9223372036854775807 |
UInt64 | 8bytes | 0 to 18446744073709551615 |
Float | 4bytes | 1.2E-38 to 3.4E+38 (~6 digits) |
Double | 8bytes | 2.3E-308 to 1.7E+308 (~15 digits) |
You can create a new name for an existing type using typealias. Here is the simple syntax to define a new type using typealias −
For example, the following line instructs the compiler that Feet is another name for Int −
Now, the following declaration is perfectly legal and creates an integer variable called distance −
When we run the above program using playground, we get the following result −
100
Swift is a type-safe language which means if a part of your code expects a String, you can't pass it an Int by mistake.
As Swift is type-safe, it performs type-checks when compiling your code and flags any mismatched types as errors.
When we compile the above program, it produces the following compile time error.
Playground execution failed: error: <EXPR>:6:6: error: cannot assign to 'let' value 'varA'
varA = "This is hello"
Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. Swift uses type inference to work out the appropriate type as follows.
When we run the above program using playground, we get the following result −
42
3.14159
3.14159
A variable provides us with named storage that our programs can manipulate. Each variable in Swift has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
Swift supports the following basic types of variables −
Swift also allows to define various other types of variables, which we will cover in subsequent chapters, such as Optional, Array, Dictionaries, Structures, and Classes.
The following section will cover how to declare and use various types of variables in Swift programming.
A variable declaration tells the compiler where and how much to create the storage for the variable. Before you use variables, you must declare them using var keyword as follows −
The following example shows how to declare a variable in Swift −
When we run the above program using playground, we get the following result −
42
You can provide a type annotation when you declare a variable, to be clear about the kind of values the variable can store. Here is the syntax −
The following example shows how to declare a variable in Swift using Annotation. Here it is important to note that if we are not using type annotation, then it becomes mandatory to provide an initial value for the variable, otherwise we can just declare our variable using type annotation.
When we run the above program using playground, we get the following result −
42
3.1415901184082
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Swift is a case-sensitive programming language.
You can use simple or Unicode characters to name your variables. The following examples shows how you can name the variables −
When we run the above program using playground, we get the following result −
Hello, Swift!
你好世界
You can print the current value of a constant or variable with the println function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are valid examples −
When we run the above program using playground, we get the following result −
Value of Godzilla is more than 1000.0 millions
Swift also introduces Optionals type, which handles the absence of a value. Optionals say either "there is a value, and it equals x" or "there isn't a value at all".
An Optional is a type on its own, actually one of Swift’s new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift.
Here’s an optional Integer declaration −
Here’s an optional String declaration −
The above declaration is equivalent to explicitly initializing it to nil which means no value −
Let's take the following example to understand how optionals work in Swift −
When we run the above program using playground, we get the following result −
myString has nil value
Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.
If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. This just means putting an exclamation mark at the end of the variable.
Let's take a simple example −
When we run the above program using playground, we get the following result −
Optional("Hello, Swift!")
Now let's apply unwrapping to get the correct value of the variable −
When we run the above program using playground, we get the following result −
Hello, Swift!
You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value. Let's take a simple example −
When we run the above program using playground, we get the following result −
Hello, Swift!
Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.
An optional binding for the if statement is as follows −
Let's take a simple example to understand the usage of optional binding −
When we run the above program using playground, we get the following result −
Your string has - Hello, Swift!
Constants refer to fixed values that a program may not alter during its execution. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except the fact that their values cannot be modified after their definition.
Before you use constants, you must declare them using let keyword as follows −
Following is a simple example to show how to declare a constant in Swift −
When we run the above program using playground, we get the following result −
42
You can provide a type annotation when you declare a constant, to be clear about the kind of values the constant can store. Following is the syntax −
The following example shows how to declare a constant in Swift using Annotation. Here it is important to note that it is mandatory to provide an initial value while creating a constant −
When we run the above program using playground, we get the following result −
42
3.1415901184082
The name of a constant can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Swift is a case-sensitive programming language. You can use simple or Unicode characters to name your variables. Following are valid examples −
When we run the above program using playground, we get the following result −
Hello, Swift!
你好世界
You can print the current value of a constant or variable using println function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are valid examples −
When we run the above program using playground, we get the following result −
Value of Godzilla is more than 1000.0 millions
A literal is the source code representation of a value of an integer, floating-point number, or string type. The following are examples of literals −
An integer literal can be a decimal, binary, octal, or hexadecimal constant. Binary literals begin with 0b, octal literals begin with 0o, and hexadecimal literals begin with 0x and nothing for decimal.
Here are some examples of integer literals −
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or hexadecimal form.
Decimal floating-point literals consist of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both.
Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent.
Here are some examples of floating-point literals −
A string literal is a sequence of characters surrounded by double quotes, with the following form −
String literals cannot contain an unescaped double quote ("), an unescaped backslash (\), a carriage return, or a line feed. Special characters can be included in string literals using the following escape sequences −
Escape sequence | Meaning |
---|---|
\0 | Null Character |
\\ | \character |
\b | Backspace |
\f | Form feed |
\n | Newline |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\' | Single Quote |
\" | Double Quote |
\000 | Octal number of one to three digits |
\xhh... | Hexadecimal number of one or more digits |
The following example shows how to use a few string literals −
When we run the above program using playground, we get the following result −
Hello World
Hello'Swift'
There are three Boolean literals and they are part of standard Swift keywords −
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Objective-C is rich in built-in operators and provides the following types of operators −
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.
The following table shows all the arithmetic operators supported by Swift language. Assume variable A holds 10 and variable B holds 20, then −
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B will give 30 |
− | Subtracts second operand from the first | A − B will give -10 |
* | Multiplies both operands | A * B will give 200 |
/ | Divides numerator by denominator | B / A will give 2 |
% | Modulus Operator and remainder of after an integer/float division | B % A will give 0 |
++ | Increment operator increases integer value by one | A++ will give 11 |
-- | Decrement operator decreases integer value by one | A-- will give 9 |
The following table shows all the relational operators supported by Swift language. Assume variable A holds 10 and variable B holds 20, then −
Operator | Description | Example |
---|---|---|
== | Checks if the values of two operands are equal or not; if yes, then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not; if values are not equal, then the condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. | (A <= B) is true. |
The following table shows all the logical operators supported by Swift language. Assume variable A holds 1 and variable B holds 0, then −
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. | !(A && B) is true. |
p | q | p & q | p | q | p ^ q |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A & B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Bitwise operators supported by Swift language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Operator | Description | Example |
---|---|---|
& | Binary AND Operator copies a bit to the result, if it exists in both operands. | (A & B) will give 12, which is 0000 1100 |
| | Binary OR Operator copies a bit, if it exists in either operand. | (A | B) will give 61, which is 0011 1101 |
^ | Binary XOR Operator copies the bit, if it is set in one operand but not both. | (A ^ B) will give 49, which is 0011 0001 |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) will give -61, which is 1100 0011 in 2's complement form. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 will give 240, which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 will give 15, which is 0000 1111 |
Swift supports the following assignment operators −
Operator | Description | Example |
---|---|---|
= | Simple assignment operator, Assigns values from right side operands to left side operand | C = A + B will assign value of A + B into C |
+= | Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assigns the result to left operand | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator, It takes modulus using two operands and assigns the result to left operand | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator | C &= 2 is same as C = C & 2 |
^= | bitwise exclusive OR and assignment operator | C ^= 2 is same as C = C ^ 2 |
|= | bitwise inclusive OR and assignment operator | C |= 2 is same as C = C | 2 |
Swift includes two range operators, which are shortcuts for expressing a range of values. The following table explains these two operators.
Operator | Description | Example |
---|---|---|
Closed Range | (a...b) defines a range that runs from a to b, and includes the values a and b. | 1...5 gives 1, 2, 3, 4 and 5 |
Half-Open Range | (a..< b) defines a range that runs from a to b, but does not include b. | 1..< 5 gives 1, 2, 3, and 4 |
Swift supports a few other important operators including range and ? : which are explained in the following table.
Operator | Description | Example |
---|---|---|
Unary Minus | The sign of a numeric value can be toggled using a prefixed - | -3 or -4 |
Unary Plus | Returns the value it operates on, without any change. | +6 gives 6 |
Ternary Conditional | Condition ? X : Y | If Condition is true ? Then value X : Otherwise value Y |
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Operator Type | Operator | Associativity |
---|---|---|
Primary Expression Operators | () [] . expr++ expr-- | left-to-right |
Unary Operators | * & + - ! ~ ++expr --expr * / % + - >> << < > <= >= == != |
right-to-left |
Binary Operators | & ^ | && || |
left-to-right |
Ternary Operator | ?: | right-to-left |
Assignment Operators | = += -= *= /= %= >>= <<= &= ^= |= | right-to-left |
Comma | , | left-to-right |
Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most of the programming languages −
Swift provides the following types of decision making statements. Click the following links to check their detail.
S.No | Statement & Description |
---|---|
1 | if statement
An if statement consists of a Boolean expression followed by one or more statements. |
2 | if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. |
3 | if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. |
4 | nested if statements
You can use one if or else if statement inside another if or else if statement(s). |
5 | switch statement
A switch statement allows a variable to be tested for equality against a list of values. |
We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
There may be a situation when you need to execute a block of code several number of times. In general statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Following is the general from of a loop statement in most of the programming languages −
Swift programming language provides the following kinds of loop to handle looping requirements. Click the following links to check their detail.
S.No | Loop Type & Description |
---|---|
1 | for-in
This loop performs a set of statements for each item in a range, sequence, collection, or progression. |
2 | for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
3 | while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
4 | do...while loop
Like a while statement, except that it tests the condition at the end of the loop body. |
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Swift supports the following control statements. Click the following links to check their detail.
S.No | Control Statement & Description |
---|---|
1 | continue statement
This statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop. |
2 | break statement Terminates the loop statement and transfers execution to the statement immediately following the loop. |
3 | fallthrough statement
The fallthrough statement simulates the behavior of swift switch to C-style switch. |
Strings in Swift are an ordered collection of characters, such as "Hello, World!" and they are represented by the Swift data type String, which in turn represents a collection of values of Character type.
You can create a String either by using a string literal or creating an instance of a String class as follows −
When the above code is compiled and executed, it produces the following result −
Hello, Swift!
Hello, Swift!
You can create an empty String either by using an empty string literal or creating an instance of String class as shown below. You can also check whether a string is empty or not using the Boolean property isEmpty.
When the above code is compiled and executed, it produces the following result −
stringA is empty
stringB is empty
You can specify whether your String can be modified (or mutated) by assigning it to a variable, or it will be constant by assigning it to a constant using let keyword as shown below −
When the above code is compiled and executed, it produces the following result −
Playground execution failed: error: <EXPR>:10:1: error: 'String' is not convertible to '@lvalue UInt8'
stringB + = "--Readers--"
String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.
Each item (variable or constant) that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash. Here is a simple example −
When the above code is compiled and executed, it produces the following result −
20 times 100 is equal to 2000.0
You can use the + operator to concatenate two strings or a string and a character, or two characters. Here is a simple example −
When the above code is compiled and executed, it produces the following result −
Hello,World!
Swift strings do not have a length property, but you can use the global count() function to count the number of characters in a string. Here is a simple example −
When the above code is compiled and executed, it produces the following result −
Hello, Swift!, length is 13
You can use the == operator to compare two strings variables or constants. Here is a simple example −
When the above code is compiled and executed, it produces the following result −
Hello, Swift! and Hello, World! are not equal
You can access a UTF-8 and UTF-16 representation of a String by iterating over its utf8 and utf16 properties as demonstrated in the following example −
When the above code is compiled and executed, it produces the following result −
UTF-8 Codes:
68 111 103 226 128 188 240 159 144 182
UTF-16 Codes:
68 111 103 8252 55357 56374
Swift supports a wide range of methods and operators related to Strings −
S.No | Functions/Operators & Purpose |
---|---|
1 | isEmpty A Boolean value that determines whether a string is empty or not. |
2 | hasPrefix(prefix: String) Function to check whether a given parameter string exists as a prefix of the string or not. |
3 | hasSuffix(suffix: String) Function to check whether a given parameter string exists as a prefix of the string or not. |
4 | toInt() Function to convert numeric String value into Integer. |
5 | count() Global function to count the number of Characters in a string. |
6 | utf8 Property to return a UTF-8 representation of a string. |
7 | utf16 Property to return a UTF-16 representation of a string. |
8 | unicodeScalars Property to return a Unicode Scalar representation of a string. |
9 | + Operator to concatenate two strings, or a string and a character, or two characters. |
10 | += Operator to append a string or character to an existing string. |
11 | == Operator to determine the equality of two strings. |
12 | < Operator to perform a lexicographical comparison to determine whether one string evaluates as less than another. |
13 | == Operator to determine the equality of two strings. |
A character in Swift is a single character String literal, addressed by the data type character. Take a look at the following example. It uses two Character constants −
When the above code is compiled and executed, it produces the following result −
Value of char1 A
Value of char2 B
If you try to store more than one character in a Character type variable or constant, then Swift will not allow that. Try to type the following example in Swift Playground and you will get an error even before compilation.
It is not possible to create an empty Character variable or constant which will have an empty value. The following syntax is not possible −
As explained while discussing Swift's Strings, String represents a collection of Character values in a specified order. So we can access individual characters from the given String by iterating over that string with a for-in loop −
When the above code is compiled and executed, it produces the following result −
H
e
l
l
o
The following example demonstrates how a Swift's Character can be concatenated with Swift's String.
When the above code is compiled and executed, it produces the following result −
Value of varC Hello G
Swift arrays are used to store ordered lists of values of the same type. Swift puts strict checking which does not allow you to enter a wrong type in an array even by mistake.
If you assign a created array to a variable then its always mutable which means you can change it by adding, removing, or changing its items but if you assign an array to a constant then that array is immutable, and its size and contents cannot be changed.
You can create an empty array of a certain type using the following initializer syntax −
Here is the syntax to create an array of a given size a* and initialize it with a value −
You can use the following statement to create an empty array of Int type having 3 elements and the initial value as zero −
var someInts = [Int](count: 3, repeatedValue: 0)
Following is one more example to create an array of three elements and assign three values to that array −
You can retrieve a value from an array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array as follows −
Here, the index starts from 0 which means the first element can be accessed using the index as 0, the second element can be accessed using the index as 1 and so on. The following example shows how to create, initialize, and access arrays −
When the above code is compiled and executed, it produces the following result −
Value of first element is 10
Value of second element is 10
Value of third element is 10
You can use append() method or addition assignment operator (+=) to add a new item at the end of an array. Take a look at the following example. Here, initially, we create an empty array and then add new elements into the same array −
When the above code is compiled and executed, it produces the following result −
Value of first element is 20
Value of second element is 30
Value of third element is 40
You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example −
When the above code is compiled and executed, it produces the following result −
Value of first element is 20
Value of second element is 30
Value of third element is 50
You can use for-in loop to iterate over the entire set of values in an array as shown in the following example −
When the above code is compiled and executed, it produces the following result −
Apple
Amazon
Google
You can use enumerate() function which returns the index of an item along with its value as shown below in the following example −
When the above code is compiled and executed, it produces the following result −
Value at index = 0 is Apple
Value at index = 1 is Amazon
Value at index = 2 is Google
You can use the addition operator (+) to add two arrays of the same type which will yield a new array with a combination of values from the two arrays as follows −
When the above code is compiled and executed, it produces the following result −
2
2
1
1
1
You can use the read-only count property of an array to find out the number of items in an array shown below −
When the above code is compiled and executed, it produces the following result −
Total items in intsA = 2
Total items in intsB = 3
Total items in intsC = 5
You can use the read-only empty property of an array to find out whether an array is empty or not as shown below −
When the above code is compiled and executed, it produces the following result −
intsA.isEmpty = false
intsB.isEmpty = false
intsC.isEmpty = true
Swift dictionaries are used to store unordered lists of values of the same type. Swift puts strict checking which does not allow you to enter a wrong type in a dictionary even by mistake.
Swift dictionaries use unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike items in an array, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers.
A dictionary key can be either an integer or a string without a restriction, but it should be unique within a dictionary.
If you assign a created dictionary to a variable, then it is always mutable which means you can change it by adding, removing, or changing its items. But if you assign a dictionary to a constant, then that dictionary is immutable, and its size and contents cannot be changed.
You can create an empty dictionary of a certain type using the following initializer syntax −
You can use the following simple syntax to create an empty dictionary whose key will be of Int type and the associated values will be strings −
Here is an example to create a dictionary from a set of given values −
You can retrieve a value from a dictionary by using subscript syntax, passing the key of the value you want to retrieve within square brackets immediately after the name of the dictionary as follows −
Let's check the following example to create, initialize, and access values from a dictionary −
When the above code is compiled and executed, it produces the following result −
Value of key = 1 is Optional("One") Value of key = 2 is Optional("Two") Value of key = 3 is Optional("Three")
You can use updateValue(forKey:) method to add an existing value to a given key of the dictionary. This method returns an optional value of the dictionary's value type. Here is a simple example −
import Cocoa var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"] var oldVal = someDict.updateValue("New value of one", forKey: 1) var someVar = someDict[1] println( "Old value of key = 1 is \(oldVal)" ) println( "Value of key = 1 is \(someVar)" ) println( "Value of key = 2 is \(someDict[2])" ) println( "Value of key = 3 is \(someDict[3])" )
When the above code is compiled and executed, it produces the following result −
Old value of key = 1 is Optional("One")
Value of key = 1 is Optional("New value of one")
Value of key = 2 is Optional("Two")
Value of key = 3 is Optional("Three")
You can modify an existing element of a dictionary by assigning new value at a given key as shown in the following example −
When the above code is compiled and executed, it produces the following result −
Old value of key = 1 is Optional("One") Value of key = 1 is Optional("New value of one") Value of key = 2 is Optional("Two") Value of key = 3 is Optional("Three")
You can use removeValueForKey() method to remove a key-value pair from a dictionary. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed. Here is a simple example −
When the above code is compiled and executed, it produces the following result −
Value of key = 1 is Optional("One")
Value of key = 2 is nil
Value of key = 3 is Optional("Three")
You can also use subscript syntax to remove a key-value pair from a dictionary by assigning a value of nil for that key. Here is a simple example −
When the above code is compiled and executed, it produces the following result −
Value of key = 1 is Optional("One")
Value of key = 2 is nil
Value of key = 3 is Optional("Three")
You can use a for-in loop to iterate over the entire set of key-value pairs in a Dictionary as shown in the following example −
When the above code is compiled and executed, it produces the following result −
Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
You can use enumerate() function which returns the index of the item along with its (key, value) pair as shown below in the example −
When the above code is compiled and executed, it produces the following result −
Dictionary key 0 - Dictionary value (2, Two)
Dictionary key 1 - Dictionary value (3, Three)
Dictionary key 2 - Dictionary value (1, One)
You can extract a list of key-value pairs from a given dictionary to build separate arrays for both keys and values. Here is an example −
When the above code is compiled and executed, it produces the following result −
Print Dictionary Keys
2
3
1
Print Dictionary Values
Two
Three
One
You can use the read-only count property of a dictionary to find out the number of items in a dictionary as shown below −
When the above code is compiled and executed, it produces the following result −
Total items in someDict1 = 3
Total items in someDict2 = 2
You can use read-only empty property of a dictionary to find out whether a dictionary is empty or not, as shown below −
When the above code is compiled and executed, it produces the following result −
someDict1 = false
someDict2 = false
someDict3 = true
A function is a set of statements organized together to perform a specific task. A Swift function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls.
Swift functions contain parameter type and its return types.
In Swift, a function is defined by the "func" keyword. When a function is newly defined, it may take one or several values as input 'parameters' to the function and it will process the functions in the main body and pass back the values to the functions as output 'return types'.
Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass input values (known as arguments) that match the types of the function's parameters. Function parameters are also called as 'tuples'.
A function's arguments must always be provided in the same order as the function's parameter list and the return values are followed by →.
Take a look at the following code. The student’s name is declared as string datatype declared inside the function 'student' and when the function is called, it will return student’s name.
When we run the above program using playground, we get the following result −
First Program
About Functions
Let us suppose we defined a function called 'display' to Consider for example to display the numbers a function with function name 'display' is initialized first with argument 'no1' which holds integer data type. Then the argument 'no1' is assigned to argument 'a' which hereafter will point to the same data type integer. Now the argument 'a' is returned to the function. Here display() function will hold the integer value and return the integer values when each and every time the function is invoked.
When we run above program using playground, we get the following result −
100
200
Swift provides flexible function parameters and its return values from simple to complex values. Similar to that of C and Objective C, functions in Swift may also take several forms.
A function is accessed by passing its parameter values to the body of the function. We can pass single to multiple parameter values as tuples inside the function.
When we run above program using playground, we get the following result −
40
45
120
We may also have functions without any parameters.
Following is an example having a function without a parameter −
When we run the above program using playground, we get the following result −
Alice
Functions are also used to return string, integer, and float data type values as return types. To find out the largest and smallest number in a given array function 'ls' is declared with large and small integer datatypes.
An array is initialized to hold integer values. Then the array is processed and each and every value in the array is read and compared for its previous value. When the value is lesser than the previous one it is stored in 'small' argument, otherwise it is stored in 'large' argument and the values are returned by calling the function.
When we run the above program using playground, we get the following result −
Largest number is: 98 and smallest number is: -5
Some functions may have arguments declared inside the function without any return values. The following program declares a and b as arguments to the sum() function. inside the function itself the values for arguments a and b are passed by invoking the function call sum() and its values are printed thereby eliminating return values.
When we run the above program using playground, we get the following result −
(30, 20)
(50, 40)
(30, 24)
Swift introduces 'optional' feature to get rid of problems by introducing a safety measure. Consider for example we are declaring function values return type as integer but what will happen when the function returns a string value or either a nil value. In that case compiler will return an error value. 'optional' are introduced to get rid of these problems.
Optional functions will take two forms 'value' and a 'nil'. We will mention 'Optionals' with the key reserved character '?' to check whether the tuple is returning a value or a nil value.
When we run the above program using playground, we get the following result −
min is -6 and max is 109
'Optionals' are used to check 'nil' or garbage values thereby consuming lot of time in debugging and make the code efficient and readable for the user.
Local parameter names are accessed inside the function alone.
Here, the func sample argument number is declared as internal variable since it is accessed internally by the function sample(). Here the 'number' is declared as local variable but the reference to the variable is made outside the function with the following statement −
When we run the above program using playground, we get the following result −
1
2
3
External parameter names allow us to name a function parameters to make their purpose more clear. For example below you can name two function parameters and then call that function as follows −
When we run the above program using playground, we get the following result −
125
When we want to define function with multiple number of arguments, then we can declare the members as 'variadic' parameters. Parameters can be specified as variadic by (···) after the parameter name.
When we run the above program using playground, we get the following result −
4
3
5
4.5
3.1
5.6
Swift
Enumerations
Closures
Functions by default consider the parameters as 'constant', whereas the user can declare the arguments to the functions as variables also. We already discussed that 'let' keyword is used to declare constant parameters and variable parameters is defined with 'var' keyword.
I/O parameters in Swift provide functionality to retain the parameter values even though its values are modified after the function call. At the beginning of the function parameter definition, 'inout' keyword is declared to retain the member values.
It derives the keyword 'inout' since its values are passed 'in' to the function and its values are accessed and modified by its function body and it is returned back 'out' of the function to modify the original argument.
Variables are only passed as an argument for in-out parameter since its values alone are modified inside and outside the function. Hence no need to declare strings and literals as in-out parameters. '&' before a variable name refers that we are passing the argument to the in-out parameter.
When we run the above program using playground, we get the following result −
Swapped values are 10, 2
Each and every function follows the specific function by considering the input parameters and outputs the desired result.
Following is an example −
When we run the above program using playground, we get the following result −
2
6
Here the function is initialized with two arguments no1 and no2 as integer data types and its return type is also declared as 'int'.
Here the function is declared as string datatype.
Functions may also have void data types and such functions won't return anything.
When we run the above program using playground, we get the following result −
Swift Functions
Types and its Usage
The above function is declared as a void function with no arguments and no return values.
Functions are first passed with integer, float or string type arguments and then it is passed as constants or variables to the function as mentioned below.
Here sum is a function name having 'a' and 'b' integer variables which is now declared as a variable to the function name addition. Hereafter both addition and sum function both have same number of arguments declared as integer datatype and also return integer values as references.
When we run the above program using playground, we get the following result −
Result: 129
We can also pass the function itself as parameter types to another function.
When we run the above program using playground, we get the following result −
Result: 129
Result: 30
A nested function provides the facility to call the outer function by invoking the inside function.
When we run the above program using playground, we get the following result −
-30
Closures in Swift are similar to that of self-contained functions organized as blocks and called anywhere like C and Objective C languages. Constants and variable references defined inside the functions are captured and stored in closures. Functions are considered as special cases of closures and it takes the following three forms −
Global Functions | Nested Functions | Closure Expressions |
---|---|---|
Have a name. Do not capture any values | Have a name. Capture values from enclosing function | Unnamed Closures capture values from the adjacent blocks |
Closure expressions in Swift language follow crisp, optimization and lightweight syntax styles which includes.
Following is a generic syntax to define closure which accepts parameters and returns a data type −
Following is a simple example −
When we run the above program using playground, we get the following result −
The following closure accepts two parameters and returns a Bool value −
Following is a simple example −
When we run the above program using playground, we get the following result −
10
Nested functions provide a convenient way of naming and defining blocks of code. Instead of representing the whole function declaration and name constructs are used to denote shorter functions. Representing the function in a clear brief statement with focused syntax is achieved through closure expressions.
Sorting a string is achieved by the Swifts key reserved function "sorted" which is already available in the standard library. The function will sort the given strings in the ascending order and returns the elements in a new array with same size and data type mentioned in the old array. The old array remains the same.
Two arguments are represented inside the sorted function −
A normal function with input string is written and passed to the sorted function to get the strings sorted to new array which is shown below −
When we run the above program using playground, we get the following result −
true
The initial array to be sorted for icecream is given as "Swift" and "great". Function to sort the array is declared as string datatype and its return type is mentioned as Boolean. Both the strings are compared and sorted in ascending order and stored in a new array. If the sorting is performed successful the function will return a true value else it will return false.
Closure expression syntax uses −
Closure expression did not support default values. Variadic parameters and Tuples can also be used as parameter types and return types.
When we run the above program using playground, we get the following result −
30
The parameters and return type declarations mentioned in the function statement can also be represented by the inline closure expression function with 'in' keyword. Once declaring parameter and return types 'in' keyword is used to denote that the body of the closure.
Here, the function type of the sorted function's second argument makes it clear that a Bool value must be returned by the closure. Because the closure's body contains a single expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return keyword can be omitted.
To return a Single expression statement in expression closures 'return' keyword is omitted in its declaration part.
When we run the above program using playground, we get the following result −
[75, 20, 10, 5, -6]
[-6, 5, 10, 20, 75]
The statement itself clearly defines that when string1 is greater than string 2 return true otherwise false hence return statement is omitted here.
Consider the addition of two numbers. We know that addition will return the integer datatype. Hence known type closures are declared as −
When we run the above program using playground, we get the following result −
-10
Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure's arguments by the names $0, $1, $2, and so on.
Here, $0 and $1 refer to the closure's first and second String arguments.
When we run the above program using playground, we get the following result −
200
Swift facilitates the user to represent Inline closures as shorthand argument names by representing $0, $1, $2 --- $n.
Closures argument list is omitted in definition section when we represent shorthand argument names inside closure expressions. Based on the function type the shorthand argument names will be derived. Since the shorthand argument is defined in expression body the 'in' keyword is omitted.
Swift provides an easy way to access the members by just providing operator functions as closures. In the previous examples keyword 'Bool' is used to return either 'true' when the strings are equal otherwise it returns 'false'.
The expression is made even simpler by operator function in closure as −
When we run the above program using playground, we get the following result −
[-30, -20, 18, 35, 42, 98]
Passing the function's final argument to a closure expression is declared with the help of 'Trailing Closures'. It is written outside the function () with {}. Its usage is needed when it is not possible to write the function inline on a single line.
where {$0 > $1} are represented as trailing closures declared outside (names).
When we run the above program using playground, we get the following result −
[NO, EA, WE, SO]
In Swift, capturing constants and variables values is done with the help of closures. It further refers and modify the values for those constants and variables inside the closure body even though the variables no longer exists.
Capturing constant and variable values is achieved by using nested function by writing function with in the body of other function.
A nested function captures −
In Swift, when a constant or a variable is declared inside a function, reference to that variables are also automatically created by the closure. It also provides the facility to refer more than two variables as the same closure as follows −
Here oneDecrement and Decrement variables will both point the same memory block as closure reference.
When we run the above program using playground, we get the following result −
82
64
46
When each and every time the outer function calcDecrement is called it invokes the decrementer() function and decrements the value by 18 and returns the result with the help of outer function calcDecrement. Here calcDecrement acts as a closure.
Even though the function decrementer() does not have any arguments closure by default refers to variables 'overallDecrement' and 'total' by capturing its existing values. The copy of the values for the specified variables are stored with the new decrementer() function. Swift handles memory management functions by allocating and deallocating memory spaces when the variables are not in use.
An enumeration is a user-defined data type which consists of set of related values. Keyword enum is used to defined enumerated data type.
Enumeration in swift also resembles the structure of C and Objective C.
Enumerations are introduced with the enum keyword and place their entire definition within a pair of braces −
For example, you can define an enumeration for days of week as follows −
When we run the above program using playground, we get the following result −
Welcome to Closures
Swift enumeration does not assign its members default value like C and Objective C. Instead the members are explicitly defined by their enumeration names. Enumeration name should start with a capital letter (Ex: enum DaysofaWeek).
Here the Enumeration name 'DaysofaWeek' is assigned to a variable weekday.Sunday. It informs the compiler that the datatype belongs to Sunday will be assigned to subsequent enum members of that particular class. Once the enum member datatype is defined, the members can be accessed by passing values and further computations.
Swift 'Switch' statement also follows the multi way selection. Only one variable is accessed at a particular time based on the specified condition. Default case in switch statement is used to trap unspecified cases.
When we run the above program using playground, we get the following result −
Climte is Cold
The program first defines Climate as the enumeration name. Then its members like 'India', 'America', 'Africa' and 'Australia' are declared belonging to class 'Climate'. Now the member America is assigned to a Season Variable. Further, Switch case will see the values corresponding to .America and it will branch to that particular statement. The output will be displayed as "Climate is Cold". Likewise all the members can be accessed through switch statements. When the condition is not satisfied it prints by default 'Climate is not predictable'.
Enumeration can be further classified in to associated values and raw values.
Associated Values | Raw Values |
Different Datatypes | Same Datatypes |
Ex: enum {10,0.8,"Hello"} | Ex: enum {10,35,50} |
Values are created based on constant or variable | Prepopulated Values |
Varies when declared each time | Value for member is same |
When we run the above program using playground, we get the following result −
Swift
98
97
95
Consider for example to access the students name and marks secured in three subjects enumeration name is declared as student and the members present in enum class are name which belongs to string datatype, marks are represented as mark1, mark2 and mark3 of datatype Integer. To access either the student name or marks they have scored.
Now, the switch case will print student name if that case block is executed otherwise it will print the marks secured by the student. If both the conditions fail, the default block will be executed.
Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration. When integers are used for raw values, they auto-increment if no value is specified for some of the enumeration members.
When we run the above program using playground, we get the following result −
Value of the Month is: 5.
Swift provides a flexible building block of making use of constructs as Structures. By making use of these structures once can define constructs methods and properties.
In Structure the variable values are copied and passed in subsequent codes by returning a copy of the old values so that the values cannot be altered.
Consider for example, suppose we have to access students record containing marks of three subjects and to find out the total of three subjects. Here markStruct is used to initialize a structure with three marks as datatype 'Int'.
The members of the structure are accessed by its structure name. The instances of the structure are initialized by the 'let' keyword.
When we run the above program using playground, we get the following result −
Mark1 is 100
Mark2 is 200
Mark3 is 300
Students marks are accessed by the structure name 'studentMarks'. The structure members are initialized as mark1, mark2, mark3 with integer type values. Then the structure studentMarks() is passed to the 'marks' with 'let' keyword. Hereafter 'marks' will contain the structure member values. Now the values are printed by accessing the structure member values by '.' with its initialized names.
When we run the above program using playground, we get the following result −
98
97
Swift language provides the functionality to define structures as custom data types for building the function blocks. The instances of structure are passed by its value to the defined blocks for further manipulations.
Need for having structures
Structures in swift pass their members with their values rather than by its references.
When we run the above program using playground, we get the following result −
98
96
100
When we run the above program using playground, we get the following result −
34
42
13
The structure 'markStruct' is defined first with its members mark1, mark2 and mark3. Now the variables of member classes are initialized to hold integer values. Then the copy of the structure members are created with 'self' Keyword. Once the copy of the structure members are created structure block with its parameter marks are passed to 'marks' variable which will now hold the students marks. Then the marks are printed as 98, 96, 100. Next step for the same structure members another instance named 'fail' is used to point the same structure members with different marks. Then the results are now printed as 34, 42, 13. This clearly explains that structures will have a copy of the member variables then pass the members to their upcoming function blocks.
Classes in Swift are building blocks of flexible constructs. Similar to constants, variables and functions the user can define class properties and methods. Swift provides us the functionality that while declaring classes the users need not create interfaces or implementation files. Swift allows us to create classes as a single file and the external interfaces will be created by default once the classes are initialized.
The syntax for creating instances
When we run the above program using playground, we get the following result −
Mark is 300
Class properties can be accessed by the '.' syntax. Property name is separated by a '.' after the instance name.
When we run the above program using playground, we get the following result −
Mark1 is 300
Mark2 is 400
Mark3 is 900
Classes in Swift refers multiple constants and variables pointing to a single instance. To know about the constants and variables pointing to a particular class instance identity operators are used. Class instances are always passed by reference. In Classes NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy.
Identical to Operators | Not Identical to Operators |
---|---|
Operator used is (===) | Operator used is (!==) |
Returns true when two constants or variables pointing to a same instance | Returns true when two constants or variables pointing to a different instance |
When we run the above program using playground, we get the following result −
main.SampleClass
main.SampleClass
Swift language provides properties for class, enumeration or structure to associate values. Properties can be further classified into Stored properties and Computed properties.
Difference between Stored Properties and Computed Properties.
Stored Property | Computed Property |
---|---|
Store constant and variable values as instance. | Calculate a value rather than storing the value. |
Provided by classes and structures. | Provided by classes, enumerations and structures. |
Both Stored and Computed properties are associated with instances type. When the properties are associated with its type values then it is defined as 'Type Properties'. Stored and computed properties are usually associated with instances of a particular type. However, properties can also be associated with the type itself. Such properties are known as type properties. Property observers are also used.
Swift introduces Stored Property concept to store the instances of constants and variables. Stored properties of constants are defined by the 'let' keyword and Stored properties of variables are defined by the 'var' keyword.
When we run the above program using playground, we get the following result −
67
3.1415
Consider the following line in the above code −
let pi = 3.1415
Here, the variable pi is initialized as a stored property value with the instance pi = 3.1415. So, whenever the instance is referred it will hold the value 3.1415 alone.
Another method to have stored property is to have as constant structures. So the whole instance of the structures will be considered as 'Stored Properties of Constants'.
When we run the above program using playground, we get the following result −
error: cannot assign to 'numbers' in 'n'
n.numbers = 8.7
Instead of reinitializing the 'number' to 8.7 it will return an error message indicating that the 'number' is declared as constant.
Swift provides a flexible property called 'Lazy Stored Property' where it won't calculate the initial values when the variable is initialized for the first time. 'lazy' modifier is used before the variable declaration to have it as a lazy stored property.
Lazy Properties are used −
When we run the above program using playground, we get the following result −
Swift
In Objective C, Stored properties also have instance variables for back up purposes to store the values declared in stored property.
Swift integrates both these concepts into a single 'stored property' declaration. Instead of having a corresponding instance variable and back up value 'stored property' contains all integrated information defined in a single location about the variables property by variable name, data type and memory management functionalities.
Rather than storing the values computed properties provide a getter and an optional setter to retrieve and set other properties and values indirectly.
When we run the above program using playground, we get the following result −
(150.0, 75.0)
-150.0
-65.0
When a computed property left the new value as undefined, the default value will be set for that particular variable.
A read-only property in computed property is defined as a property with getter but no setter. It is always used to return a value. The variables are further accessed through a '.' Syntax but cannot be set to another value.
When we run the above program using playground, we get the following result −
Swift Properties
3.09
In Swift to observe and respond to property values Property Observers are used. Each and every time when property values are set property observers are called. Except lazy stored properties we can add property observers to 'inherited' property by method 'overriding'.
Property Observers can be defined by either.
When we run the above program using playground, we get the following result −
Total Counter is: 100
Newly Added Counter 100
Total Counter is: 800
Newly Added Counter 700
Local and global variable are declared for computing and observing the properties.
Local Variables | Global Variables |
---|---|
Variables that are defined within a function, method, or closure context. | Variables that are defined outside function, method, closure, or type context. |
Used to store and retrieve values. | Used to store and retrieve values. |
Stored properties is used to get and set the values. | Stored properties is used to get and set the values. |
Computed properties are also used. | Computed properties are also used. |
Properties are defined in the Type definition section with curly braces {} and scope of the variables are also defined previously. For defining type properties for value types 'static' keyword is used and for class types 'class' keyword is used.
Just like instance properties Type properties are queried and set with '.' Syntax just on the type alone instead of pointing to the instance.
When we run the above program using playground, we get the following result −
97
87
In Swift language Functions associated with particular types are referred to as Methods. In Objective C Classes are used to define methods, whereas Swift language provides the user flexibility to have methods for Classes, Structures and Enumerations.
In Swift language, Classes, Structures and Enumeration instances are accessed through the instance methods.
Instance methods provide functionality.
When we run the above program using playground, we get the following result −
Result is: 880
Result is: 850
Class Calculations defines two instance methods −
Finally, to print the calculations methods with values for a and b is called. Instance methods are accessed with '.' dot syntax
Swift Functions describe both local and global declarations for their variables. Similarly, Swift Methods naming conventions also resembles as that of Objective C. But the characteristics of local and global parameter name declarations are different for functions and methods. The first parameter in swift are referred by preposition names as 'with', 'for' and 'by' for easy to access naming conventions.
Swift provides the flexibility in methods by declaring first parameter name as local parameter names and the remaining parameter names to be of global parameter names. Here 'no1' is declared by swift methods as local parameter names. 'no2' is used for global declarations and accessed through out the program.
When we run the above program using playground, we get the following result −
600
320
3666
Even though Swift methods provide first parameter names for local declarations, the user has the provision to modify the parameter names from local to global declarations. This can be done by prefixing '#' symbol with the first parameter name. By doing so, the first parameter can be accessed globally throughout the modules.
When the user needs to access the subsequent parameter names with an external name, the methods name is overridden with the help of '_' symbol.
When we run the above program using playground, we get the following result −
2400
500
45000
Methods have an implicit property known as 'self' for all its defined type instances. 'Self' property is used to refer the current instances for its defined methods.
When we run the above program using playground, we get the following result −
Inside Self Block: 900
Inside Self Block: 1500
Result is: 880
Result is: 850
Result is: 1480
Result is: 1450
In Swift language structures and enumerations belong to value types which cannot be altered by its instance methods. However, swift language provides flexibility to modify the value types by 'mutating' behavior. Mutate will make any changes in the instance methods and will return back to the original form after the execution of the method. Also, by the 'self' property new instance is created for its implicit function and will replace the existing method after its execution
When we run the above program using playground, we get the following result −
9
15
270
450
81000
135000
Mutating methods combined with 'self' property assigns a new instance to the defined method.
When we run the above program using playground, we get the following result −
39
65
When a particular instance of a method is called, it is called as an Instance method; and when the method calls a particular type of a method, it is called as 'Type Methods'. Type methods for 'classes' are defined by the 'func' keyword and structures and enumerations type methods are defined with the 'static' keyword before the 'func' keyword.
Type methods are called and accessed by '.' syntax where instead of calling a particular instance the whole method is invoked.
When we run the above program using playground, we get the following result −
35
5
Accessing the element members of a collection, sequence and a list in Classes, Structures and Enumerations are carried out with the help of subscripts. These subscripts are used to store and retrieve the values with the help of index. Array elements are accessed with the help of someArray[index] and its subsequent member elements in a Dictionary instance can be accessed as someDicitonary[key].
For a single type, subscripts can range from single to multiple declarations. We can use the appropriate subscript to overload the type of index value passed to the subscript. Subscripts also ranges from single dimension to multiple dimension according to the users requirements for their input data type declarations.
Let's have a recap to the computed properties. Subscripts too follow the same syntax as that of computed properties. For querying type instances, subscripts are written inside a square bracket followed with the instance name. Subscript syntax follows the same syntax structure as that of 'instance method' and 'computed property' syntax. 'subscript' keyword is used for defining subscripts and the user can specify single or multiple parameters with their return types. Subscripts can have read-write or read-only properties and the instances are stored and retrieved with the help of 'getter' and 'setter' properties as that of computed properties.
When we run the above program using playground, we get the following result −
The number is divisible by 11 times
The number is divisible by 50 times
The number is divisible by 33 times
The number is divisible by 20 times
The number is divisible by 14 times
When we run the above program using playground, we get the following result −
Sunday
Monday
Tuesday
Wednesday
Subscripts takes single to multiple input parameters and these input parameters also belong to any datatype. They can also use variable and variadic parameters. Subscripts cannot provide default parameter values or use any in-out parameters.
Defining multiple subscripts are termed as 'subscript overloading' where a class or structure can provide multiple subscript definitions as required. These multiple subscripts are inferred based on the types of values that are declared within the subscript braces.
When we run the above program using playground, we get the following result −
1.0
2.0
3.0
5.0
Swift subscript supports single parameter to multiple parameter declarations for appropriate data types. The program declares 'Matrix' structure as a 2 * 2 dimensional array matrix to store 'Double' data types. The Matrix parameter is inputted with Integer data types for declaring rows and columns.
New instance for the Matrix is created by passing row and column count to the initialize as shown below.
var mat = Matrix(rows: 3, columns: 3)
Matrix values can be defined by passing row and column values into the subscript, separated by a comma as shown below.
The ability to take than more form is defined as Inheritance. Generally a class can inherit methods, properties and functionalities from another class. Classes can be further categorized in to sub class and super class.
Swift classes contain superclass which calls and access methods, properties, functions and overriding methods. Also, property observers are also used to add a property and modify the stored or computed property methods.
A Class that does not inherit methods, properties or functions from another class is called as 'Base Class'.
When we run the above program using playground, we get the following result −
swift
98
89
76
Class with classname StudDetails are defined as a base class here which is used to contain students name, and three subjects mark as mark1, mark2 and mark3. 'let' keyword is used to initialize the value for the base class and base class value is displayed in the playground with the help of 'println' function.
The act of basing a new class on an existing class is defined as 'Subclass'. The subclass inherits the properties, methods and functions of its base class. To define a subclass ':' is used before the base class name.
When we run the above program using playground, we get the following result −
Mark1:93, Mark2:89
Class 'StudDetails' is defined as super class where student marks are declared and the subclass 'display' is used to inherit the marks from its super class. Sub class defines students marks and calls the print() method to display the students mark.
Accessing the super class instance, type methods, instance, type properties and subscripts subclass provides the concept of overriding. 'override' keyword is used to override the methods declared in the superclass.
'super' keyword is used as a prefix to access the methods, properties and subscripts declared in the super class.
Overriding | Access to methods, properties and subscripts |
Methods | super.somemethod() |
Properties | super.someProperty() |
Subscripts | super[someIndex] |
Inherited instance and type methods can be overridden by the 'override' keyword to our methods defined in our subclass. Here print() is overridden in subclass to access the type property mentioned in the super class print(). Also new instance of cricket() super class is created as 'cricinstance'.
When we run the above program using playground, we get the following result −
Welcome to Swift Super Class
Welcome to Swift Sub Class
You can override an inherited instance or class property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.
Swift allows the user to provide custom getter and setter to override the inherited property whether it is a stored or computed property. The subclass does not know the inherited property name and type. Therefore it is essential that the user needs to specify in subclass, the name and type of the overriding property specified in super class.
This can be done in two ways −
When we run the above program using playground, we get the following result −
Radius of rectangle for 25.0 is now overridden as 3
When a new property needs to be added for an inherited property, 'property overriding' concept is introduced in Swift. This notifies the user when the inherited property value is altered. But overriding is not applicable for inherited constant stored properties and inherited read-only computed properties.
When we run the above program using playground, we get the following result −
Radius of rectangle for 25.0 is now overridden as 3
Radius of rectangle for 100.0 is now overridden as 21
When the user need not want others to access super class methods, properties or subscripts swift introduces 'final' property to prevent overriding. Once 'final' property is declared the subscripts won't allow the super class methods, properties and its subscripts to be overridden. There is no provision to have 'final' property in 'super class'. When 'final' property is declared the user is restricted to create further sub classes.
When we run the above program using playground, we get the following result −
<stdin>:14:18: error: var overrides a 'final' var
override var area: String {
^
<stdin>:7:9: note: overridden declaration is here
var area: String {
^
<stdin>:12:11: error: inheritance from a final class 'Circle'
class Rectangle: Circle {
^
<stdin>:25:14: error: var overrides a 'final' var
override var radius: Double {
^
<stdin>:6:14: note: overridden declaration is here
final var radius = 12.5
Since the super class is declared as 'final' and its data types are also declared as 'final' the program won't allow to create subclasses further and it will throw errors.
Classes, structures and enumerations once declared in Swift are initialized for preparing instance of a class. Initial value is initialized for stored property and also for new instances too the values are initialized to proceed further. The keyword to create initialization function is carried out by 'init()' method. Swift initializer differs from Objective-C that it does not return any values. Its function is to check for initialization of newly created instances before its processing. Swift also provides 'deinitialization' process for performing memory management operations once the instances are deallocated.
Stored property have to initialize the instances for its classes and structures before processing the instances. Stored properties use initializer to assign and initialize values thereby eradicating the need to call property observers. Initializer is used in stored property.
area of rectangle is 72.0
area of rectangle is 72.0
Here the structure 'rectangle' is initialized with members length and breadth as 'Double' datatypes. Init() method is used to initialize the values for the newly created members length and double. Area of rectangle is calculated and returned by calling the rectangle function.
Swift language provides Init() function to initialize the stored property values. Also, the user has provision to initialize the property values by default while declaring the class or structure members. When the property takes the same value alone throughout the program we can declare it in the declaration section alone rather than initializing it in init(). Setting property values by default enables the user when inheritance is defined for classes or structures.
When we run the above program using playground, we get the following result −
area of rectangle is 72.0
Here instead of declaring length and breadth in init() the values are initialized in declaration itself.
In Swift language the user has the provision to initialize parameters as part of the initializer's definition using init().
When we run the above program using playground, we get the following result −
area is: 72.0
area is: 432.0
Initialization parameters have both local and global parameter names similar to that of function and method parameters. Local parameter declaration is used to access within the initialize body and external parameter declaration is used to call the initializer. Swift initializers differ from function and method initializer that they do not identify which initializer are used to call which functions.
To overcome this, Swift introduces an automatic external name for each and every parameter in init(). This automatic external name is as equivalent as local name written before every initialization parameter.
When we run the above program using playground, we get the following result −
Days of a Week is: 1
Days of a Week is: 2
Days of a Week is: 3
Days of a Week is: 4
Days of a Week is: 4
Days of a Week is: 4
When an external name is not needed for an initialize underscore '_' is used to override the default behavior.
When we run the above program using playground, we get the following result −
area is: 180.0
area is: 370.0
area is: 110.0
When the stored property at some instance does not return any value that property is declared with an 'optional' type indicating that 'no value' is returned for that particular type. When the stored property is declared as 'optional' it automatically initializes the value to be 'nil' during initialization itself.
When we run the above program using playground, we get the following result −
area is: Optional(180.0)
area is: Optional(370.0)
area is: Optional(110.0)
Initialization also allows the user to modify the value of constant property too. During initialization, class property allows its class instances to be modified by the super class and not by the subclass. Consider for example in the previous program 'length' is declared as 'variable' in the main class. The below program variable 'length' is modified as 'constant' variable.
When we run the above program using playground, we get the following result −
area is: Optional(180.0)
area is: Optional(370.0)
area is: Optional(110.0)
Default initializers provide a new instance to all its declared properties of base class or structure with default values.
When we run the above program using playground, we get the following result −
result is: nil
result is: 98
result is: true
The above program is defined with class name as 'defaultexample'. Three member functions are initialized by default as 'studname?' to store 'nil' values, 'stmark' as 98 and 'pass' as Boolean value 'true'. Likewise the member values in the class can be initialized as default before processing the class member types.
When the custom initializers are not provided by the user, Structure types in Swift will automatically receive the 'memberwise initializer'. Its main function is to initialize the new structure instances with the default memberwise initialize and then the new instance properties are passed to the memberwise initialize by name.
When we run the above program using playground, we get the following result −
Area of rectangle is: 24.0
Area of rectangle is: 32.0
Structures are initialized by default for their membership functions during initialization for 'length' as '100.0' and 'breadth' as '200.0'. But the values are overridden during the processing of variables length and breadth as 24.0 and 32.0.
Initializer Delegation is defined as calling initializers from other initializers. Its main function is to act as reusability to avoid code duplication across multiple initializers.
When we run the above program using playground, we get the following result −
student result is: (0.0, 0.0) (0.0, 0.0)
student result is: (2.0, 2.0) (5.0, 5.0)
student result is: (2.5, 2.5) (3.0, 3.0)
Value Types | Class Types |
---|---|
Inheritance is not supported for value types like structures and enumerations. Referring other initializers is done through self.init. | Inheritance is supported. Checks all stored property values are initialized. |
Class types have two kinds of initializers to check whether defined stored properties receive an initial value namely designated initializers and convenience initializers.
Designated Initializer | Convenience Initializer |
---|---|
Considered as primary initializes for a class. | Considered as supporting initialize for a class. |
All class properties are initialized and appropriate superclass initializer are called for further initialization. | Designated initializer is called with convenience initializer to create class instance for a specific use case or input value type. |
At least one designated initializer is defined for every class. | No need to have convenience initializers compulsory defined when the class does not require initializers. |
Init(parameters) { statements } | convenience init(parameters) { statements } |
res is: 10
res is: 10
res is: 20
When we run the above program using playground, we get the following result −
res is: 20
res is: 30
res is: 50
Swift does not allow its subclasses to inherit its superclass initializers for their member types by default. Inheritance is applicable to Super class initializers only to some extent which will be discussed in Automatic Initializer Inheritance.
When the user needs to have initializers defined in super class, subclass with initializers has to be defined by the user as custom implementation. When overriding has to be taken place by the sub class to the super class 'override' keyword has to be declared.
When we run the above program using playground, we get the following result −
Rectangle: 4 sides
Pentagon: 5 sides
When we run the above program using playground, we get the following result −
Planet name is: Mercury
No Planets like that: [No Planets]
The user has to be notified when there are any initializer failures while defining a class, structure or enumeration values. Initialization of variables sometimes become a failure one due to −
To catch exceptions thrown by initialization method, swift produces a flexible initialize called 'failable initializer' to notify the user that something is left unnoticed while initializing the structure, class or enumeration members. Keyword to catch the failable initializer is 'init?'. Also, failable and non failable initializers cannot be defined with same parameter types and names.
When we run the above program using playground, we get the following result −
Student name is specified
Student name is left blank
Swift language provides the flexibility to have Failable initializers for enumerations too to notify the user when the enumeration members are left from initializing values.
When we run the above program using playground, we get the following result −
With In Block Two
Block Does Not Exist
A failable initializer when declared with enumerations and structures alerts an initialization failure at any circumstance within its implementation. However, failable initializer in classes will alert the failure only after the stored properties have been set to an initial value.
When we run the above program using playground, we get the following result −
Module is Failable Initializers
Like that of initialize the user also has the provision to override a superclass failable initializer inside the sub class. Super class failable initialize can also be overridden with in a sub class non-failable initializer.
Subclass initializer cannot delegate up to the superclass initializer when overriding a failable superclass initializer with a non-failable subclass initialize.
A non-failable initializer can never delegate to a failable initializer.
The program given below describes the failable and non-failable initializers.
When we run the above program using playground, we get the following result −
Planet name is: Mercury
No Planets like that: [No Planets]
Swift provides 'init?' to define an optional instance failable initializer. To define an implicitly unwrapped optional instance of the specific type 'init!' is specified.
When we run the above program using playground, we get the following result −
Student name is specified
Student name is left blank
To declare each and every subclass of the initialize 'required' keyword needs to be defined before the init() function.
When we run the above program using playground, we get the following result −
10
30
10
Before a class instance needs to be deallocated 'deinitializer' has to be called to deallocate the memory space. The keyword 'deinit' is used to deallocate the memory spaces occupied by the system resources. Deinitialization is available only on class types.
Swift automatically deallocates your instances when they are no longer needed, to free up resources. Swift handles the memory management of instances through automatic reference counting (ARC), as described in Automatic Reference Counting. Typically you don't need to perform manual clean-up when your instances are deallocated. However, when you are working with your own resources, you might need to perform some additional clean-up yourself. For example, if you create a custom class to open a file and write some data to it, you might need to close the file before the class instance is deallocated.
When we run the above program using playground, we get the following result −
1
0
When print = nil statement is omitted the values of the counter retains the same since it is not deinitialized.
When we run the above program using playground, we get the following result −
1
1
Memory management functions and its usage are handled in Swift language through Automatic reference counting (ARC). ARC is used to initialize and deinitialize the system resources thereby releasing memory spaces used by the class instances when the instances are no longer needed. ARC keeps track of information about the relationships between our code instances to manage the memory resources effectively.
When we run the above program using playground, we get the following result −
swift
98
When we run the above program using playground, we get the following result −
Initializing: Swift
Initializing: ARC
Class type properties has two ways to resolve strong reference cycles −
These references are used to enable one instance to refer other instances in a reference cycle. Then the instances may refer to each and every instances instead of caring about strong reference cycle. When the user knows that some instance may return 'nil' values we may point that using weak reference. When the instance going to return something rather than nil then declare it with unowned reference.
When we run the above program using playground, we get the following result −
ARC Is The Main Module
Sub Module with its topic number is 4
When we run the above program using playground, we get the following result −
ARC
Marks Obtained by the student is 98
When we assign a closure to the class instance property and to the body of the closure to capture particular instance strong reference cycle can occur. Strong reference to the closure is defined by 'self.someProperty' or 'self.someMethod()'. Strong reference cycles are used as reference types for the closures.
When we run the above program using playground, we get the following result −
<p>Welcome to Closure SRC</p>
When the closure and the instance refer to each other the user may define the capture in a closure as an unowned reference. Then it would not allow the user to deallocate the instance at the same time. When the instance sometime return a 'nil' value define the closure with the weak instance.
When we run the above program using playground, we get the following result −
<Inside>ARC Weak References</Inside>
Inside the deinit()
The process of querying, calling properties, subscripts and methods on an optional that may be 'nil' is defined as optional chaining. Optional chaining return two values −
Since multiple queries to methods, properties and subscripts are grouped together failure to one chain will affect the entire chain and results in 'nil' value.
Optional chaining is specified after the optional value with '?' to call a property, method or subscript when the optional value returns some values.
Optional Chaining '?' | Access to methods,properties and subscriptsOptional Chaining '!' to force Unwrapping |
? is placed after the optional value to call property, method or subscript | ! is placed after the optional value to call property, method or subscript to force unwrapping of value |
Fails gracefully when the optional is 'nil' | Forced unwrapping triggers a run time error when the optional is 'nil' |
When we run the above program using playground, we get the following result −
fatal error: unexpectedly found nil while unwrapping an Optional value 0 swift 0x0000000103410b68 llvm::sys::PrintStackTrace(__sFILE*) + 40 1 swift 0x0000000103411054 SignalHandler(int) + 452 2 libsystem_platform.dylib 0x00007fff9176af1a _sigtramp + 26 3 libsystem_platform.dylib 0x000000000000000b _sigtramp + 1854492939 4 libsystem_platform.dylib 0x00000001074a0214 _sigtramp + 1976783636 5 swift 0x0000000102a85c39 llvm::JIT::runFunction(llvm::Function*, std::__1::vector<llvm::GenericValue, std::__1::allocator<llvm::GenericValue> > const&) + 329 6 swift 0x0000000102d320b3 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 1523 7 swift 0x000000010296e6ba swift::RunImmediately(swift::CompilerInstance&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, swift::IRGenOptions&, swift::SILOptions const&) + 1066 8 swift 0x000000010275764b frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 5275 9 swift 0x0000000102754a6d main + 1677 10 libdyld.dylib 0x00007fff8bb9e5c9 start + 1 11 libdyld.dylib 0x000000000000000c start + 1950751300 Stack dump: 0. Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -interpret - -target x86_64-apple-darwin14.0.0 -target-cpu core2 -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -module-name main /bin/sh: line 47: 15672 Done cat <<'SWIFT' import Foundation
The above program declares 'election poll' as class name and contains 'candidate' as membership function. The subclass is declared as 'poll booth' and 'name' as its membership function which is initialized as 'MP'. The call to the super class is initialized by creating an instance 'cand' with optional '!'. Since the values are not declared in its base class, 'nil' value is stored thereby returning a fatal error by the force unwrapping procedure.
When we run the above program using playground, we get the following result −
Candidate name cannot be retreived
The program above declares 'election poll' as class name and contains 'candidate' as membership function. The subclass is declared as 'poll booth' and 'name' as its membership function which is initialized as 'MP'. The call to the super class is initialized by creating an instance 'cand' with optional '?'. Since the values are not declared in its base class 'nil' value is stored and printed in the console by the else handler block.
Swift language also provides the concept of optional chaining, to declare more than one subclasses as model classes. This concept will be very useful to define complex models and to access the properties, methods and subscripts sub properties.
When we run the above program using playground, we get the following result −
Rectangle Area is not specified
When we run the above program using playground, we get the following result −
Area of circle is not specified
The function circleprint() declared inside the circle() sub class is called by creating an instance named 'circname'. The function will return a value if it contains some value otherwise it will return some user defined print message by checking the statement 'if circname.print?.circleprint() != nil'.
Optional chaining is used to set and retrieve a subscript value to validate whether call to that subscript returns a value. '?' is placed before the subscript braces to access the optional value on the particular subscript.
When we run the above program using playground, we get the following result −
Radius is not specified.
In the above program the instance values for the membership function 'radiusName' is not specified. Hence program call to the function will return only else part whereas to return the values we have to define the values for the particular membership function.
When we run the above program using playground, we get the following result −
Radius is measured in Units.
In the above program, the instance values for the membership function 'radiusName' is specified. Hence program call to the function will now return values.
When we run the above program using playground, we get the following result −
Optional(35)
Optional(78)
Optional(78)
Optional(101)
Optional(90)
Optional(44)
Optional(56)
The optional values for subscripts can be accessed by referring their subscript values. It can be accessed as subscript[0], subscript[1] etc. The default subscript values for 'radius' are first assigned as [35, 45, 78, 101] and for 'Circle' [90, 45, 56]]. Then the subscript values are changed as Radius[0] to 78 and Circle[1] to 45.
Multiple sub classes can also be linked with its super class methods, properties and subscripts by optional chaining.
Multiple chaining of optional can be linked −
If retrieving type is not optional, optional chaining will return an optional value. For example if String through optional chaining it will return String? Value
When we run the above program using playground, we get the following result −
Radius is not specified.
In the above program, the instance values for the membership function 'radiusName' is not specified. Hence, the program call to the function will return only else part whereas to return the values we have to define the values for the particular membership function.
If the retrieving type is already optional, then optional chaining will also return an optional value. For example if String? Is accessed through optional chaining it will return String? Value.
When we run the above program using playground, we get the following result −
Radius is measured in Units.
In the above program, the instance values for the membership function 'radiusName' is specified. Hence, the program call to the function will now return values.
Optional chaining is used to access subclasses defined methods too.
When we run the above program using playground, we get the following result −
Area of circle is not specified
To validate the type of an instance 'Type Casting' comes into play in Swift language. It is used to check whether the instance type belongs to a particular super class or subclass or it is defined in its own hierarchy.
Swift type casting provides two operators 'is' to check the type of a value and 'as' and to cast the type value to a different type. Type casting also checks whether the instance type follows particular protocol conformance standard.
Type casting is used to check the type of instances to find out whether it belongs to particular class type. Also, it checks hierarchy of classes and its subclasses to check and cast those instances to make it as a same hierarchy.
When we run the above program using playground, we get the following result −
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Type checking is done with the 'is' operator. The 'is' type check operator checks whether the instance belongs to particular subclass type and returns 'true' if it belongs to that instance else it will return 'false'.
When we run the above program using playground, we get the following result −
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Subjects in chemistry contains 2 topics and maths contains 3 topics
Downcasting the subclass type can be done with two operators (as? and as!).'as?' returns an optional value when the value returns nil. It is used to check successful downcast.
'as!' returns force unwrapping as discussed in the optional chaining when the downcasting returns nil value. It is used to trigger runtime error in case of downcast failure
When we run the above program using playground, we get the following result −
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
The keyword 'Any' is used to represent an instance which belongs to any type including function types.
When we run the above program using playground, we get the following result −
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
Integer value is 12
Pi value is 3.14159
Example for Any
Topics 'solid physics', Hertz
To represent the instance of any class type, 'AnyObject' keyword is used.
When we run the above program using playground, we get the following result −
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
Integer value is 12
Pi value is 3.14159
Example for Any
Topics 'solid physics', Hertz
Functionality of an existing class, structure or enumeration type can be added with the help of extensions. Type functionality can be added with extensions but overriding the functionality is not possible with extensions.
Extensions are declared with the keyword 'extension'.
Existing type can also be added with extensions to make it as a protocol standard and its syntax is similar to that of classes or structures.
Computed 'instance' and 'type' properties can also be extended with the help of extensions.
When we run the above program using playground, we get the following result −
Addition is 103
Subtraction is 110
Multiplication is 390
Division is 11
Mixed Type is 154
Swift provides the flexibility to add new initializers to an existing type by extensions. The user can add their own custom types to extend the types already defined and additional initialization options are also possible. Extensions supports only init(). deinit() is not supported by the extensions.
When we run the above program using playground, we get the following result −
Inside mult block (100, 200)
Inside mult block (200, 100)
Inside mult block (300, 500)
Inside mult block (300, 100)
Inside Sum Block:(100, 200)
Inside Diff Block: (200, 100)
New instance methods and type methods can be added further to the subclass with the help of extensions.
When we run the above program using playground, we get the following result −
Inside Extensions Block
Inside Extensions Block
Inside Extensions Block
Inside Extensions Block
Inside Type Casting Block
Inside Type Casting Block
Inside Type Casting Block
topics() function takes argument of type '(summation: () → ())' to indicate the function does not take any arguments and it won't return any values. To call that function multiple number of times, for block is initialized and call to the method with topic() is initialized.
Instance methods can also be mutated when declared as extensions.
Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation.
When we run the above program using playground, we get the following result −
Area of circle is: 34.210935
Area of circle is: 105.68006
Area of circle is: 45464.070735
Adding new subscripts to already declared instances can also be possible with extensions.
When we run the above program using playground, we get the following result −
2
6
5
Nested types for class, structure and enumeration instances can also be extended with the help of extensions.
When we run the above program using playground, we get the following result −
20
30
40
50
50
Protocols provide a blueprint for Methods, properties and other requirements functionality. It is just described as a methods or properties skeleton instead of implementation. Methods and properties implementation can further be done by defining classes, functions and enumerations. Conformance of a protocol is defined as the methods or properties satisfying the requirements of the protocol.
Protocols also follow the similar syntax as that of classes, structures, and enumerations −
Protocols are declared after the class, structure or enumeration type names. Single and Multiple protocol declarations are also possible. If multiple protocols are defined they have to be separated by commas.
When a protocol has to be defined for super class, the protocol name should follow the super class name with a comma.
Protocol is used to specify particular class type property or instance property. It just specifies the type or instance property alone rather than specifying whether it is a stored or computed property. Also, it is used to specify whether the property is 'gettable' or 'settable'.
Property requirements are declared by 'var' keyword as property variables. {get set} is used to declare gettable and settable properties after their type declaration. Gettable is mentioned by {get} property after their type declaration.
When we run the above program using playground, we get the following result −
98
true
false
Swift Protocols
Swift
When we run the above program using playground, we get the following result −
Wednesday
Swing allows the user to initialize protocols to follow type conformance similar to that of normal initializers.
Designated or convenience initializer allows the user to initialize a protocol to conform its standard by the reserved 'required' keyword.
Protocol conformance is ensured on all subclasses for explicit or inherited implementation by 'required' modifier.
When a subclass overrides its super class initialization requirement it is specified by the 'override' modifier keyword.
When we run the above program using playground, we get the following result −
res is: 20 res is: 30 res is: 50
Instead of implementing functionalities in a protocol they are used as types for functions, classes, methods etc.
Protocols can be accessed as types in −
When we run the above program using playground, we get the following result −
10
20
30
5
10
15
[100, 200, 300]
[10, 20, 30]
Existing type can be adopted and conformed to a new protocol by making use of extensions. New properties, methods and subscripts can be added to existing types with the help of extensions.
Swift allows protocols to inherit properties from its defined properties. It is similar to that of class inheritance, but with the choice of listing multiple inherited protocols separated by commas.
When we run the above program using playground, we get the following result −
Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 5 times to pass
Student attempted 5 times to pass
Student is absent for exam
Student attempted 5 times to pass
Student is absent for exam
When protocols are defined and the user wants to define protocol with classes it should be added by defining class first followed by protocol's inheritance list.
When we run the above program using playground, we get the following result −
res is: 20
res is: 30
res is: 50
Swift allows multiple protocols to be called at once with the help of protocol composition.
When we run the above program using playground, we get the following result −
Priya is 21 years old
Rehan is 29 years old
Roshan is 19 years old
Protocol conformance is tested by 'is' and 'as' operators similar to that of type casting.
When we run the above program using playground, we get the following result −
Area is 12.5663708
Area is 198.0
Rectangle area is not defined
Swift language provides 'Generic' features to write flexible and reusable functions and types. Generics are used to avoid duplication and to provide abstraction. Swift standard libraries are built with generics code. Swifts 'Arrays' and 'Dictionary' types belong to generic collections. With the help of arrays and dictionaries the arrays are defined to hold 'Int' values and 'String' values or any other types.
When we run the above program using playground, we get the following result −
Before Swapping values are: 100 and 200
After Swapping values are: 200 and 100
Generic functions can be used to access any data type like 'Int' or 'String'.
When we run the above program using playground, we get the following result −
Before Swapping Int values are: 100 and 200
After Swapping Int values are: 200 and 100
Before Swapping String values are: Generics and Functions
After Swapping String values are: Functions and Generics
The function exchange() is used to swap values which is described in the above program and <T> is used as a type parameter. For the first time, function exchange() is called to return 'Int' values and second call to the function exchange() will return 'String' values. Multiple parameter types can be included inside the angle brackets separated by commas.
Type parameters are named as user defined to know the purpose of the type parameter that it holds. Swift provides <T> as generic type parameter name. However type parameters like Arrays and Dictionaries can also be named as key, value to identify that they belong to type 'Dictionary'.
When we run the above program using playground, we get the following result −
[Swift]
[Swift, Generics]
[Swift, Generics, Type Parameters]
[Swift, Generics, Type Parameters, Naming Type Parameters]
Extending the stack property to know the top of the item is included with 'extension' keyword.
When we run the above program using playground, we get the following result −
[Swift]
[Swift, Generics]
[Swift, Generics, Type Parameters]
[Swift, Generics, Type Parameters, Naming Type Parameters]
The top item on the stack is Naming Type Parameters.
The top item on the stack is Naming Type Parameters.
Swift language allows 'type constraints' to specify whether the type parameter inherits from a specific class, or to ensure protocol conformance standard.
When we run the above program using playground, we get the following result −
Before Swapping Int values are: 100 and 200
After Swapping Int values are: 200 and 100
Before Swapping String values are: Generics and Functions
After Swapping String values are: Functions and Generics
Swift allows associated types to be declared inside the protocol definition by the keyword 'typealias'.
When we run the above program using playground, we get the following result −
[Swift]
[Swift, Generics]
[Swift, Generics, Type Parameters]
[Swift, Generics, Type Parameters, Naming Type Parameters]
Type constraints enable the user to define requirements on the type parameters associated with a generic function or type. For defining requirements for associated types 'where' clauses are declared as part of type parameter list. 'where' keyword is placed immediately after the list of type parameters followed by constraints of associated types, equality relationships between types and associated types.
When we run the above program using playground, we get the following result −
[Swift]
[Swift, Generics]
[Swift, Generics, Where Clause]
[Swift, Generics, Where Clause]
To restrict access to code blocks, modules and abstraction is done through access control. Classes, structures and enumerations can be accessed according to their properties, methods, initializers and subscripts by access control mechanisms. Constants, variables and functions in a protocol are restricted and allowed access as global and local through access control. Access control applied to properties, types and functions can be referred as 'entities'.
Access control model is based on modules and source files.
Module is defined as a single unit of code distribution and can be imported using the keyword 'import'. A source file is defined as a single source code file with in a module to access multiple types and functions.
Three different access levels are provided by Swift language. They are Public, Internal and Private access.
S.No | Access Levels & Definition |
---|---|
1 | Public Enables entities to be processed with in any source file from their defining module, a source file from another module that imports the defining module. |
2 | Internal Enables entities to be used within any source file from their defining module, but not in any source file outside of that module. |
3 | Private Restricts the use of an entity to its own defining source file. Private access plays role to hide the implementation details of a specific code functionality. |
Some functions may have arguments declared inside the function without any return values. The following program declares a and b as arguments to the sum() function. Inside the function itself the values for arguments a and b are passed by invoking the function call sum() and its values are printed thereby eliminating return values. To make the function's return type as private, declare the function's overall access level with the private modifier.
When we run the above program using playground, we get the following result −
(30, 20)
(50, 40)
(30, 24)
When we run the above program using playground, we get the following result −
Student Marks are: 98,97,95
Enumeration in Swift language automatically receive the same access level for individual cases of an enumeration. Consider for example to access the students name and marks secured in three subjects enumeration name is declared as student and the members present in enum class are name which belongs to string datatype, marks are represented as mark1, mark2 and mark3 of datatype Integer. To access either the student name or marks they have scored. Now, the switch case will print student name if that case block is executed otherwise it will print the marks secured by the student. If both condition fails the default block will be executed.
Swift allows the user to subclass any class that can be accessed in the current access context. A subclass cannot have a higher access level than its superclass. The user is restricted from writing a public subclass of an internal superclass.
When we run the above program using playground, we get the following result −
Welcome to Swift Super Class
Welcome to Swift Sub Class
Swift constant, variable, or property cannot be defined as public than its type. It is not valid to write a public property with a private type. Similarly, a subscript cannot be more public than its index or return type.
When a constant, variable, property, or subscript makes use of a private type, the constant, variable, property, or subscript must also be marked as private −
Getters and setters for constants, variables, properties, and subscripts automatically receive the same access level as the constant, variable, property, or subscript they belong to.
When we run the above program using playground, we get the following result −
Total Counter is: 100
Newly Added Counter 100
Total Counter is: 800
Newly Added Counter 700
Custom initializers can be assigned an access level less than or equal to the type that they initialize. A required initializer must have the same access level as the class it belongs to. The types of an initializer's parameters cannot be more private than the initializer's own access level.
To declare each and every subclass of the initialize 'required' keyword needs to be defined before the init() function.
When we run the above program using playground, we get the following result −
10
30
10
A default initializer has the same access level as the type it initializes, unless that type is defined as public. When default initialize is defined as public it is considered internal. When the user needs a public type to be initializable with a no-argument initializer in another module, provide explicitly a public no-argument initializer as part of the type's definition.
When we define a new protocol to inherit functionalities from an existing protocol, both has to be declared the same access levels to inherit the properties of each other. Swift access control won't allow the users to define a 'public' protocol that inherits from an 'internal' protocol.
When we run the above program using playground, we get the following result −
res is: 20
res is: 30
res is: 50
Swift does not allow the users to provide an explicit access level modifier for an extension when the user uses that extension to add protocol conformance. The default access level for each protocol requirement implementation within the extension is provided with its own protocol access level.
Generics allow the user to specify minimum access levels to access the type constraints on its type parameters.
When we run the above program using playground, we get the following result −
[Swift]
[Swift, Generics]
[Swift, Generics, Type Parameters]
[Swift, Generics, Type Parameters, Naming Type Parameters]
The user can define type aliases to treat distinct access control types. Same access level or different access levels can be defined by the user. When type alias is 'private' its associated members can be declared as 'private, internal of public type'. When type alias is public the members cannot be alias as an 'internal' or 'private' name
Any type aliases you define are treated as distinct types for the purposes of access control. A type alias can have an access level less than or equal to the access level of the type it aliases. For example, a private type alias can alias a private, internal, or public type, but a public type alias cannot alias an internal or private type.
When we run the above program using playground, we get the following result −
[Swift]
[Swift, Generics]
[Swift, Generics, Where Clause]
[Swift, Generics, Where Clause]
Objective-C is general-purpose language that is developed on top of C Programming language by adding features of Small Talk programming language making it an object-oriented language. It is primarily used in developing iOS and Mac OS X operating systems as well as its applications.
Initially, Objective-C was developed by NeXT for its NeXTSTEP OS from whom it was taken over by Apple for its iOS and Mac OS X.
Fully supports object-oriented programming, including the four pillars of object-oriented development:
Foundation Framework provides large set of features and they are listed below.
The most important thing to do when learning Objective-C is to focus on concepts and not get lost in language technical details.
The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones.
Objective-C, as mentioned earlier, is used in iOS and Mac OS X. It has large base of iOS users and largely increasing Mac OS X users. And since Apple focuses on quality first and its wonderful for those who started learning Objective-C.
You really do not need to set up your own environment to start learning Objective-C programming language. Reason is very simple, we already have set up Objective-C Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.
Try the following example using Try it option available at the top right corner of the below sample code box:
For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.
If you are still willing to set up your environment for Objective-C programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The GCC Compiler.
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.
The files you create with your editor are called source files and contain program source code. The source files for Objective-C programs are typically named with the extension ".m".
Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it.
The source code written in source file is the human readable source for your program. It needs to be "compiled" to turn into machine language, so that your CPU can actually execute the program as per instructions given.
This GCC compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler.
GCC compiler is available for free on various platforms and the procedure to set up on various platforms is explained below.
The initial step is install gcc along with gcc Objective-C package. This is done by:
The next step is to set up package dependencies using following command:
In order to get full features of Objective-C, download and install GNUStep. This can be done by downloading the package from
Now, we need to switch to the downloaded folder and unpack the file by:
Now, we need to switch to the folder gnustep-startup that gets created using:
Next, we need to configure the build process:
Then, we can build by:
We need to finally set up the environment by:
We have a helloWorld.m Objective-C as follows:
Now, we can compile and run a Objective-C file say helloWorld.m by switching to folder containing the file using cd and then using the following steps:
We can see the following output:
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode set up, you will be able to use GNU compiler for C/C++.
Xcode is currently available at developer.apple.com/technologies/tools/.
In order to run Objective-C program on windows, we need to install MinGW and GNUStep Core. Both are available at
First, we need to install the MSYS/MinGW System package. Then, we need to install the GNUstep Core package. Both of which provide a windows installer, which is self-explanatory.
Then to use Objective-C and GNUstep by selecting Start -> All Programs -> GNUstep -> Shell
Switch to the folder containing helloWorld.m
We can compile the program by using:
We can run the program by using:
We get the following output:
2013-09-07 10:48:39.772 tutorialsPoint[1200] hello world
Before we study basic building blocks of the Objective-C programming language, let us look a bare minimum Objective-C program structure so that we can take it as a reference in upcoming chapters.
A Objective-C program basically consists of the following parts:
Let us look at a simple code that would print the words "Hello World":
Let us look various parts of the above program:
Now when we compile and run the program, we will get the following result.
2013-09-07 22:38:27.932 demo[28001] Hello, World!
You have seen a basic structure of Objective-C program, so it will be easy to understand other basic building blocks of the Objective-C programming language.
A Objective-C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Objective-C statement consists of six tokens:
The individual tokens are:
In Objective-C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
For example, following are two different statements:
Comments are like helping text in your Objective-C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below:
You can not have comments with in comments and they do not occur within a string or character literals.
An Objective-C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).
Objective-C does not allow punctuation characters such as @, $, and % within identifiers. Objective-C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Objective-C. Here are some examples of acceptable identifiers:
A line containing only whitespace, possibly with a comment, is known as a blank line, and an Objective-C compiler totally ignores it.
Whitespace is the term used in Objective-C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement:
There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement,
no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.
In the Objective-C programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
The types in Objective-C can be classified as follows:
S.N. | Types and Description |
---|---|
1 | Basic Types:
They are arithmetic types and consist of the two types: (a) integer types and (b) floating-point types. |
2 | Enumerated types:
They are again arithmetic types and they are used to define variables that can only be assigned certain discrete integer values throughout the program. |
3 | The type void:
The type specifier void indicates that no value is available. |
4 | Derived types:
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types. |
To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:
When you compile and execute the above program, it produces the following result on Linux:
2013-09-07 22:21:39.155 demo[1340] Storage size for int : 4
Following table gives you details about standard float-point types with storage sizes and value ranges and their precision:
Type | Storage size | Value range | Precision |
---|---|---|---|
float | 4 byte | 1.2E-38 to 3.4E+38 | 6 decimal places |
double | 8 byte | 2.3E-308 to 1.7E+308 | 15 decimal places |
long double | 10 byte | 3.4E-4932 to 1.1E+4932 | 19 decimal places |
The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. Following example will print storage space taken by a float type and its range values:
When you compile and execute the above program, it produces the following result on Linux:
2013-09-07 22:22:21.729 demo[3927] Storage size for float : 4
The void type specifies that no value is available. It is used in three kinds of situations:
S.N. | Types and Description |
---|---|
1 | Function returns as void
There are various functions in Objective-C which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); |
2 | Function arguments as void
There are various functions in Objective-C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void); |
The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters.
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Objective-C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Objective-C is case-sensitive. Based on the basic types explained in previous chapter, there will be the following basic variable types:
Type | Description |
---|---|
char | Typically a single octet (one byte). This is an integer type. |
int | The most natural size of integer for the machine. |
float | A single-precision floating point value. |
double | A double-precision floating point value. |
void | Represents the absence of type. |
Objective-C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types.
A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows:
type variable_list;
Here, type must be a valid Objective-C data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here:
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:
type variable_name = value;
Some examples are:
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.
A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files, which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your Objective-C program but it can be defined only once in a file, a function or a block of code.
Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function:
When the above code is compiled and executed, it produces the following result:
2013-09-07 22:43:31.695 demo[14019] value of c : 30
2013-09-07 22:43:31.695 demo[14019] value of f : 23.333334
Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. In the following example, it's explained using C function and as you know Objective-C supports C style functions also:
There are two kinds of expressions in Objective-C:
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
10 = 20;
The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals:
Following are other examples of various types of Integer literals:
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals:
Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
There are certain characters in C when they are proceeded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes:
Escape sequence | Meaning |
---|---|
\\ | \ character |
\' | ' character |
\" | " character |
\? | ? character |
\a | Alert or bell |
\b | Backspace |
\f | Form feed |
\n | Newline |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\ooo | Octal number of one to three digits |
\xhh . . . | Hexadecimal number of one or more digits |
Following is the example to show few escape sequence characters:
When the above code is compiled and executed, it produces the following result:
2013-09-07 22:17:17.923 demo[17871] Hello World
String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
There are two simple ways in C to define constants:
Following is the form to use #define preprocessor to define a constant:
Following example explains it in detail:
When the above code is compiled and executed, it produces the following result:
2013-09-07 22:18:16.637 demo[21460] value of area : 50
2013-09-07 22:18:16.638 demo[21460]
You can use const prefix to declare constants with a specific type as follows:
Following example explains it in detail:
When the above code is compiled and executed, it produces the following result:
2013-09-07 22:19:24.780 demo[25621] value of area : 50
2013-09-07 22:19:24.781 demo[25621]
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Objective-C language is rich in built-in operators and provides following types of operators:
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.
Following table shows all the arithmetic operators supported by Objective-C language. Assume variable A holds 10 and variable B holds 20, then:
Show Examples
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B will give 30 |
- | Subtracts second operand from the first | A - B will give -10 |
* | Multiplies both operands | A * B will give 200 |
/ | Divides numerator by denominator | B / A will give 2 |
% | Modulus Operator and remainder of after an integer division | B % A will give 0 |
++ | Increment operator increases integer value by one | A++ will give 11 |
-- | Decrement operator decreases integer value by one | A-- will give 9 |
Following table shows all the relational operators supported by Objective-C language. Assume variable A holds 10 and variable B holds 20, then:
Show Examples
Operator | Description | Example |
---|---|---|
== | Checks if the values of two operands are equal or not; if yes, then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not; if values are not equal, then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand; if yes, then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand; if yes, then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand; if yes, then condition becomes true. | (A <= B) is true. |
Following table shows all the logical operators supported by Objective-C language. Assume variable A holds 1 and variable B holds 0, then:
Show Examples
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. | !(A && B) is true. |
Following table shows all the logical operators supported by Objective-C language. Assume variable A holds 1 and variable B holds 0, then:
Show Examples
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. | !(A && B) is true. |
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows:
p | q | p & q | p | q | p ^ q |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by Objective-C language are listed in the following table. Assume variable A holds 60 and variable B holds 13 then:
Show Examples
Operator | Description | Example |
---|---|---|
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) will give 12, which is 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) will give 61, which is 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) will give 49, which is 0011 0001 |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) will give -61, which is 1100 0011 in 2's complement form. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 will give 240, which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 will give 15, which is 0000 1111 |
There are following assignment operators supported by Objective-C language:
Show Examples
Operator | Description | Example |
---|---|---|
= | Simple assignment operator, Assigns values from right side operands to left side operand | C = A + B will assign value of A + B into C |
+= | Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assigns the result to left operand | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator, It takes modulus using two operands and assigns the result to left operand | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator | C &= 2 is same as C = C & 2 |
^= | bitwise exclusive OR and assignment operator | C ^= 2 is same as C = C ^ 2 |
|= | bitwise inclusive OR and assignment operator | C |= 2 is same as C = C | 2 |
There are few other important operators including sizeof and ? : supported by Objective-C Language.
Show Examples
Operator | Description | Example |
---|---|---|
sizeof() | Returns the size of an variable. | sizeof(a), where a is integer, will return 4. |
& | Returns the address of an variable. | &a; will give actual address of the variable. |
* | Pointer to a variable. | *a; will pointer to a variable. |
? : | Conditional Expression | If Condition is true ? Then value X : Otherwise value Y |
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
Category | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
Objective-C programming language provides the following types of loop to handle looping requirements. Click the following links to check their details.
Loop Type | Description |
---|---|
while loop | Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
for loop | Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
do...while loop | Like a while statement, except that it tests the condition at the end of the loop body. |
nested loops | You can use one or more loops inside any another while, for or do..while loop. |
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Objective-C supports the following control statements. Click the following links to check their details.
Control Statement | Description |
---|---|
break statement | Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. |
continue statement | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but Objective-C programmers more commonly use the for(;;) construct to signify an infinite loop.
Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages:Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages:
Objective-C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
Objective-C programming language provides following types of decision making statements. Click the following links to check their details:
Statement | Description |
---|---|
if statement | An if statement consists of a boolean expression followed by one or more statements. |
if...else statement | An if statement can be followed by an optional else statement, which executes when the boolean expression is false. |
nested if statements | You can use one if or else if statement inside another if or else if statement(s). |
switch statement | A switch statement allows a variable to be tested for equality against a list of values. |
nested switch statements | You can use one switch statement inside another switch statement(s). |
We have covered conditional operator ? : in previous chapter which can be used to replace if...else statements. It has the following general form:
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
A function is a group of statements that together perform a task. Every Objective-C program has one C function, which is main(), and all of the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
Basically in Objective-C, we call the function as method.
The Objective-C foundation framework provides numerous built-in methods that your program can call. For example, method appendString() to append string to another string.
A method is known with various names like a function or a sub-routine or a procedure, etc.
The general form of a method definition in Objective-C programming language is as follows:
A method definition in Objective-C programming language consists of a method header and a method body. Here are all the parts of a method:
Following is the source code for a method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two:
A method declaration tells the compiler about a function name and how to call the method. The actual body of the function can be defined separately.
A method declaration has the following parts:
For the above-defined function max(), following is the method declaration:
-(int) max:(int)num1 andNum2:(int)num2;
Method declaration is required when you define a method in one source file and you call that method in another file. In such case you should declare the function at the top of the file calling the function.
While creating a Objective-C method, you give a definition of what the function has to do. To use a method, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called method. A called method performs defined task, and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a method, you simply need to pass the required parameters along with method name, and if method returns a value, then you can store returned value. For example:
I kept max() function along with main() function and complied the source code. While running final executable, it would produce the following result:
2013-09-07 22:28:45.912 demo[26080] Max value is : 200
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type | Description |
---|---|
Call by value | This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. |
Call by reference | This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. |
An Objective-C class defines an object that combines data with related behavior. Sometimes, it makes sense just to represent a single task or unit of behavior, rather than a collection of methods.
Blocks are a language-level feature added to C, Objective-C and C++ which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages
Simple block implementation
Blocks can also take arguments and return values just like methods and functions.
Here is a simple example to implement and invoke a block with arguments and return values.
Here is a simple example using typedef in block. Please note this sample doesn't work on the online compiler for now. Use XCode to run the same.
Let us compile and execute it, it will produce the following result:
2013-09-10 08:13:57.155 demo[284:303] Action Performed
2013-09-10 08:13:57.157 demo[284:303] Completion is called to intimate action is performed.
Blocks are used more in iOS applications and Mac OS X. So its more important to understand the usage of blocks.
In Objective-C programming language, in order to save the basic data types like int, float, bool in object form,
Objective-C provides a range of methods to work with NSNumber and important ones are listed in following table.
S.N. | Method and Description |
---|---|
1 | + (NSNumber *)numberWithBool:(BOOL)value
Creates and returns an NSNumber object containing a given value, treating it as a BOOL. |
2 | + (NSNumber *)numberWithChar:(char)value
Creates and returns an NSNumber object containing a given value, treating it as a signed char. |
3 | + (NSNumber *)numberWithDouble:(double)value
Creates and returns an NSNumber object containing a given value, treating it as a double. |
4 | + (NSNumber *)numberWithFloat:(float)value
Creates and returns an NSNumber object containing a given value, treating it as a float. |
5 | + (NSNumber *)numberWithInt:(int)value
Creates and returns an NSNumber object containing a given value, treating it as a signed int. |
6 | + (NSNumber *)numberWithInteger:(NSInteger)value
Creates and returns an NSNumber object containing a given value, treating it as an NSInteger. |
7 | - (BOOL)boolValue
Returns the receiver's value as a BOOL. |
8 | - (char)charValue
Returns the receiver's value as a char. |
9 | - (double)doubleValue
Returns the receiver's value as a double. |
10 | - (float)floatValue
Returns the receiver's value as a float. |
11 | - (NSInteger)integerValue
Returns the receiver's value as an NSInteger. |
12 | - (int)intValue
Returns the receiver's value as an int. |
13 | - (NSString *)stringValue
Returns the receiver's value as a human-readable string. |
Here is a simple example for using NSNumber which multiplies two numbers and returns the product.
Now when we compile and run the program, we will get the following result.
2013-09-14 18:53:40.575 demo[16787] The product is 105
Objective-C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To declare an array in Objective-C, a programmer specifies the type of the elements and the number of elements required by an array as follows:
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Objective-C data type. For example, to declare a 10-element array called balance of type double, use this statement:
Now, balance is a variable array, which is sufficient to hold up to 10 double numbers.
You can initialize an array in Objective-C either one by one or using a single statement as follows:
The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:
You will create exactly the same array as you did in the previous example.
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above:
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:
The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays:
When the above code is compiled and executed, it produces the following result:
2013-09-14 01:24:06.669 demo[16508] Element[0] = 100
2013-09-14 01:24:06.669 demo[16508] Element[1] = 101
2013-09-14 01:24:06.669 demo[16508] Element[2] = 102
2013-09-14 01:24:06.669 demo[16508] Element[3] = 103
2013-09-14 01:24:06.669 demo[16508] Element[4] = 104
2013-09-14 01:24:06.669 demo[16508] Element[5] = 105
2013-09-14 01:24:06.669 demo[16508] Element[6] = 106
2013-09-14 01:24:06.669 demo[16508] Element[7] = 107
2013-09-14 01:24:06.669 demo[16508] Element[8] = 108
2013-09-14 01:24:06.669 demo[16508] Element[9] = 109
Arrays are important to Objective-C and need lots of more details. There are following few important concepts related to array which should be clear to a Objective-C programmer:
Concept | Description |
---|---|
Multi-dimensional arrays | Objective-C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. |
Passing arrays to functions | You can pass to the function a pointer to an array by specifying the array's name without an index. |
Return array from a function | Objective-C allows a function to return an array. |
Pointer to an array | You can generate a pointer to the first element of an array by simply specifying the array name, without any index. |
Pointers in Objective-C are easy and fun to learn. Some Objective-C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Objective-C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined:
When the above code is compiled and executed, it produces the result something as follows:
2013-09-13 03:18:45.727 demo[17552] Address of var1 variable: 1c0843fc
2013-09-13 03:18:45.728 demo[17552] Address of var2 variable: 1c0843f0
So, you understood what is memory address and how to access it, so base of the concept is over. Now let us see what is a pointer.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is:
Here, type is the pointer's base type; it must be a valid Objective-C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable, (b) assign the address of a variable to a pointer, and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations:
When the above code is compiled and executed, it produces the result something as follows:
2013-09-13 03:20:21.873 demo[24179] Address of var variable: 337ed41c
2013-09-13 03:20:21.873 demo[24179] Address stored in ip variable: 337ed41c
2013-09-13 03:20:21.874 demo[24179] Value of *ip variable: 20
It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program:
When the above code is compiled and executed, it produces the following result:
2013-09-13 03:21:19.447 demo[28027] The value of ptr is : 0
On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an if statement as follows:
Pointers have many but easy concepts and they are very important to Objective-C programming. There are following few important pointer concepts, which should be clear to a Objective-C programmer:
Concept | Description |
---|---|
Objective-C - Pointer arithmetic | There are four arithmetic operators that can be used on pointers: ++, --, +, - |
Objective-C - Array of pointers | You can define arrays to hold a number of pointers. |
Objective-C - Pointer to pointer | Objective-C allows you to have pointer on a pointer and so on. |
Passing pointers to functions in Objective-C | Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. |
Return pointer from functions in Objective-C | Objective-C allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well. |
The string in Objective-C programming language is represented using NSString and its subclass NSMutableString provides several ways for creating string objects. The simplest way to create a string object is to use the Objective-C @"..." construct:
A simple example for creating and printing a string is shown below.
When the above code is compiled and executed, it produces result something as follows:
2013-09-11 01:21:39.922 demo[23926] Greeting message: Hello
Objective-C supports a wide range of methods for manipulate strings:
S.N. | Method & Purpose |
---|---|
1 | - (NSString *)capitalizedString;
Returns a capitalized representation of the receiver. |
2 | - (unichar)characterAtIndex:(NSUInteger)index;
Returns the character at a given array position. |
3 | - (double)doubleValue;
Returns the floating-point value of the receiver’s text as a double. |
4 | - (float)floatValue;
Returns the floating-point value of the receiver’s text as a float. |
5 | - (BOOL)hasPrefix:(NSString *)aString;
Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver. |
6 | - (BOOL)hasSuffix:(NSString *)aString;
Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver. |
7 | - (id)initWithFormat:(NSString *)format ...;
Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted. |
8 | - (NSInteger)integerValue;
Returns the NSInteger value of the receiver’s text. |
9 | - (BOOL)isEqualToString:(NSString *)aString;
Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison. |
10 | - (NSUInteger)length;
Returns the number of Unicode characters in the receiver. |
11 | - (NSString *)lowercaseString;
Returns lowercased representation of the receiver. |
12 | - (NSRange)rangeOfString:(NSString *)aString;
Finds and returns the range of the first occurrence of a given string within the receiver. |
13 | - (NSString *)stringByAppendingFormat:(NSString *)format ...;
Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments. |
14 | - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
Returns a new string made by removing from both ends of the receiver characters contained in a given character set. |
15 | - (NSString *)substringFromIndex:(NSUInteger)anIndex;
Returns a new string containing the characters of the receiver from the one at a given index to the end. |
Following example makes use of few of the above-mentioned functions:
When the above code is compiled and executed, it produces result something as follows:
2013-09-11 01:15:45.069 demo[30378] Uppercase String : WORLD
2013-09-11 01:15:45.070 demo[30378] Concatenated string: HelloWorld
2013-09-11 01:15:45.070 demo[30378] Length of Str3 : 10
2013-09-11 01:15:45.070 demo[30378] Using initWithFormat: Hello World
You can find a complete list of Objective-C NSString related methods in NSString Class Reference.
Objective-C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user-defined data type available in Objective-C programming which allows you to combine data items of different kinds.
Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this:
The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure:
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure:
When the above code is compiled and executed, it produces the following result:
2013-09-14 04:20:07.947 demo[20591] Book 1 title : Objective-C Programming
2013-09-14 04:20:07.947 demo[20591] Book 1 author : Nuha Ali
2013-09-14 04:20:07.947 demo[20591] Book 1 subject : Objective-C Programming Tutorial
2013-09-14 04:20:07.947 demo[20591] Book 1 book_id : 6495407
2013-09-14 04:20:07.947 demo[20591] Book 2 title : Telecom Billing
2013-09-14 04:20:07.947 demo[20591] Book 2 author : Zara Ali
2013-09-14 04:20:07.947 demo[20591] Book 2 subject : Telecom Billing Tutorial
2013-09-14 04:20:07.947 demo[20591] Book 2 book_id : 6495700
You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example:
When the above code is compiled and executed, it produces the following result:
2013-09-14 04:34:45.725 demo[8060] Book title : Objective-C Programming
2013-09-14 04:34:45.725 demo[8060] Book author : Nuha Ali
2013-09-14 04:34:45.725 demo[8060] Book subject : Objective-C Programming Tutorial
2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495407
2013-09-14 04:34:45.725 demo[8060] Book title : Telecom Billing
2013-09-14 04:34:45.725 demo[8060] Book author : Zara Ali
2013-09-14 04:34:45.725 demo[8060] Book subject : Telecom Billing Tutorial
2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495700
You can define pointers to structures in very similar way as you define pointer to any other variable as follows:
Now, you can store the address of a structure variable in the above-defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows:
To access the members of a structure using a pointer to that structure, you must use the -> operator as follows:
Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept:
When the above code is compiled and executed, it produces the following result:
2013-09-14 04:38:13.942 demo[20745] Book title : Objective-C Programming
2013-09-14 04:38:13.942 demo[20745] Book author : Nuha Ali
2013-09-14 04:38:13.942 demo[20745] Book subject : Objective-C Programming Tutorial
2013-09-14 04:38:13.942 demo[20745] Book book_id : 6495407
2013-09-14 04:38:13.942 demo[20745] Book title : Telecom Billing
2013-09-14 04:38:13.942 demo[20745] Book author : Zara Ali
2013-09-14 04:38:13.942 demo[20745] Book subject : Telecom Billing Tutorial
2013-09-14 04:38:13.942 demo[20745] Book book_id : 6495700
Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples:
Objective-C allows us do this in a structure definition by putting :bit length after the variable. For example:
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type and a 9 bit my_int.
Objective-C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word.
The Objective-C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, an Objective-C Preprocessor is just a text substitution tool and it instructs compiler to do required pre-processing before actual compilation. We'll refer to the Objective-C Preprocessor as the OCPP.
All preprocessor commands begin with a pound symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in first column. Following section lists down all important preprocessor directives:
Directive | Description |
---|---|
#define | Substitutes a preprocessor macro |
#include | Inserts a particular header from another file |
#undef | Undefines a preprocessor macro |
#ifdef | Returns true if this macro is defined |
#ifndef | Returns true if this macro is not defined |
#if | Tests if a compile time condition is true |
#else | The alternative for #if |
#elif | #else an #if in one statement |
#endif | Ends preprocessor conditional |
#error | Prints error message on stderr |
#pragma | Issues special commands to the compiler using a standardized method |
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the OCPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.
These directives tell the OCPP to get foundation.h from Foundation Framework and add the text to the current source file. The next line tells OCPP to get myheader.h from the local directory and add the content to the current source file.
This tells the OCPP to undefine existing FILE_SIZE and define it as 42.
This tells the OCPP to define MESSAGE only if MESSAGE isn't already defined.
This tells the OCPP to do the process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.
ANSI C defines a number of macros. Although each one is available for your use in programming, the predefined macros should not be directly modified.
Macro | Description |
---|---|
__DATE__ | The current date as a character literal in "MMM DD YYYY" format |
__TIME__ | The current time as a character literal in "HH:MM:SS" format |
__FILE__ | This contains the current filename as a string literal. |
__LINE__ | This contains the current line number as a decimal constant. |
__STDC__ | Defined as 1 when the compiler complies with the ANSI standard. |
Let's try the following example:
When the above code in a file main.m is compiled and executed, it produces the following result:
2013-09-14 04:46:14.859 demo[20683] File :main.m
2013-09-14 04:46:14.859 demo[20683] Date :Sep 14 2013
2013-09-14 04:46:14.859 demo[20683] Time :04:46:14
2013-09-14 04:46:14.859 demo[20683] Line :8
2013-09-14 04:46:14.859 demo[20683] ANSI :1
The Objective-C preprocessor offers following operators to help you in creating macros:
A macro usually must be contained on a single line. The macro continuation operator is used to continue a macro that is too long for a single line. For example:
The stringize or number-sign operator ('#'), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro that has a specified argument or parameter list. For example:
When the above code is compiled and executed, it produces the following result:
2013-09-14 05:46:14.859 demo[20683] Carole and Debra: We love you!
The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example:
When the above code is compiled and executed, it produces the following result:
2013-09-14 05:48:14.859 demo[20683] token34 = 40
How it happened, because this example results in the following actual output from the preprocessor:
This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting.
The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows:
When the above code is compiled and executed, it produces the following result:
2013-09-14 05:48:19.859 demo[20683] Here is the message: You wish!
One of the powerful functions of the OCPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows:
We can rewrite above code using a macro as follows:
Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between macro name and open parenthesis. For example:
When the above code is compiled and executed, it produces the following result:
2013-09-14 05:52:15.859 demo[20683] Max between 20 and 10 is 20
The Objective-C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers:
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:.
BYTE b1, b2;
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows:
You can use typedef to give a name to user-defined data type as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows:
When the above code is compiled and executed, it produces the following result:
2013-09-12 12:21:53.745 demo[31183] Book title : Objective-C Programming 2013-09-12 12:21:53.745 demo[31183] Book author : TutorialsPoint 2013-09-12 12:21:53.745 demo[31183] Book subject : Programming tutorial 2013-09-12 12:21:53.745 demo[31183] Book Id : 100
The #define is a Objective-C directive, which is also used to define the aliases for various data types similar to typedef but with following differences:
Following is a simplest usage of #define:
When the above code is compiled and executed, it produces the following result:
2013-09-12 12:23:37.993 demo[5160] Value of TRUE : 1
2013-09-12 12:23:37.994 demo[5160] Value of FALSE : 0
Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows:
In Objective-C, we generally use CGFloat for doing floating point operation, which is derived from basic type of float in case of 32-bit and double in case of 64-bit. Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation:
When the above code is compiled and executed, it produces the following result:
2013-09-11 01:35:40.047 demo[20634] Value of mean : 3.400000
It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary.
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character in an int:
When the above code is compiled and executed, it produces the following result:
2013-09-11 01:38:28.492 demo[980] Value of sum : 116
Here, value of sum is coming as 116 because compiler is doing integer promotion and converting the value of 'c' to ascii before performing actual addition operation.
The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the following hierarchy:
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us take following example to understand the concept:
When the above code is compiled and executed, it produces the following result:
2013-09-11 01:41:39.192 demo[15351] Value of sum : 116.000000
Here, it is simple to understand that first c gets converted to integer but because final value is float, so usual arithmetic conversion applies and compiler converts i and c into float and add them yielding a float result.
In order to print logs, we use the NSLog method in Objective-C programming language which we have used right from the Hello World example.
Let us look at a simple code that would print the words "Hello World":
Now, when we compile and run the program, we will get the following result.
2013-09-16 00:32:50.888 demo[16669] Hello, World!
Since the NSLogs we use in our application, it will be printed in logs of device and it is not good to print logs in a live build. Hence, we use a type definition for printing logs and we can use them as shown below.
Now, when we compile and run the program in debug mode, we will get the following result.
2013-09-11 02:47:07.723 demo[618] Debug log, our custom addition gets printed during debug only 2013-09-11 02:47:07.723 demo[618] NSLog gets printed always
Now, when we compile and run the program in release mode, we will get the following result.
2013-09-11 02:47:45.248 demo[3158] NSLog gets printed always
In Objective-C programming, error handling is provided with NSError class available in Foundation framework.
An NSError object encapsulates richer and more extensible error information than is possible using only an error code or error string. The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information.
Objective-C programs use NSError objects to convey information about runtime errors that users need to be informed about. In most cases, a program displays this error information in a dialog or sheet. But it may also interpret the information and either ask the user to attempt to recover from the error or attempt to correct the error on its own
NSError Object consists of:
Domain: The error domain can be one of the predefined NSError domains or an arbitrary string describing a custom domain and domain must not be nil.
Code: The error code for the error.
User Info: The userInfo dictionary for the error and userInfo may be nil.
The following example shows how to create a custom error
Here is complete code of the above error sample passed as reference to an pointer
In the above example, we return a name if the id is 1, otherwise we set the user-defined error object.
When the above code is compiled and executed, it produces the following result:
2013-09-14 18:01:00.809 demo[27632] Name1: Employee Test Name
2013-09-14 18:01:00.809 demo[27632] Error finding Name2: Unable to complete the process
t is possible to pass some values from the command line to your Objective-C programs when they are executed. These values are called command line arguments and many times they are important for your program, especially when you want to control your program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array, which points to each argument passed to the program. Following is a simple example, which checks if there is any argument supplied from the command line and take action accordingly:
#import <Foundation/Foundation.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { NSLog(@"The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { NSLog(@"Too many arguments supplied.\n"); } else { NSLog(@"One argument expected.\n"); } }
When the above code is compiled and executed with a single argument, say "testing", it produces the following result.
2013-09-13 03:01:17.333 demo[7640] The argument supplied is testing
When the above code is compiled and executed with two arguments, say testing1 and testing2, it produces the following result.
2013-09-13 03:01:18.333 demo[7640] Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the following result.
2013-09-13 03:01:18.333 demo[7640] One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command-line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, otherwise if you pass one argument, then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space, then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command-line argument by putting inside double quotes:
When the above code is compiled and executed with a single argument separated by space but inside double quotes say "Testing1 Testing2", it produces the following result.
2013-09-14 04:07:57.305 demo[8534] Program name demo
2013-09-14 04:07:57.305 demo[8534] The argument supplied is Testing1 Testing 2
Code is listed in a monospace font, both for code examples and for Java keywords mentioned in the text.
The standard Java convention for names is used:
For syntax definitions:
access
|
An access word from: public , protected , private , or it can be omitted |
modifiers
|
one or more terms that modify a declaration; these include the access terms as well as terms like: static , transient , or volatile |
dataType
|
A data type word; this can be a primitive, such as int , or the name of a class, such as Object ; variants of this include: returnType and paramType |
variableName
|
The name of a variable; variants on this include paramName and functionName |
ClassName
|
The name of a class; there will be variants of this used for different types of examples, such as: BaseClassName , DerivedClassName , InterfaceName , and ExceptionClassName |
code
|
Executable code goes here |
. . .
|
In an example, omitted code not related to the topic |
A Java program is run differently than a traditional executable program.
Traditional programs are invoked through the operating system.
Traditional programs are compiled from source code into a machine and OS-specific binary executable file.
When you run a Java program, the OS is actually running the Java Runtime Engine, or JRE, as an executable program; it processes your compiled code through the Java Virtual Machine (usually referred to as the JVM).
A Java source code file is compiled into a bytecode file.
A Java program is run differently than a traditional executable program.
Traditional programs are invoked through the operating system.
Traditional programs are compiled from source code into a machine and OS-specific binary executable file.
When you run a Java program, the OS is actually running the Java Runtime Engine, or JRE, as an executable program; it processes your compiled code through the Java Virtual Machine (usually referred to as the JVM).
A Java source code file is compiled into a bytecode file.
Java source code is written in plain text, using a text editor.
The javac compiler is then used to compile the source code into bytecode.
You then run the java runtime engine, which will then interpret the bytecode to execute the program.
You can download the SDK (software development kit) including the compiler and runtime engine from Oracle at: . Look for the download of JavaSE 1.6.0.10 (or the latest release of that version).
You can also download the API documentation and even the source code. Note that:
Java programs are compiled and run from an operating system prompt, unless you have installed an IDE that will do this for you directly. If you create an applet, this would run inside a web page in a browser.
After you have installed the JDK, you will need to set at least one environment variable in order to be able to compile and run Java programs.
For more complex projects that pull together elements from different sources, you must set an additional environment variable or two. Note that:
The procedure to permanently set the environment variables varies slightly from one version of Windows to another; the following will work in many, including Windows XP. The process for Vista is similar, but slightly different:
7. for PATH, again select either Add or Edit.
If you set the variables from a command prompt, they will only hold for that session, but you could create a batch file that you could run each time you open a command prompt window.
To set the PATH from a command prompt or batch file:
If you need to set the CLASSPATH:
In order to run as a program, a class must contain a method named main, with a particular argument list. This is similar to the C and C++ languages.
The definition goes inside your class definition, and looks like:
For example, if we had an executable class called Hello, in a file called Hello.java that compiled to Hello.class, you could run it with:
In order to see something happen, we need to be able to print to the screen.
There is a System class that is automatically available when your program runs (everything in it is static).
it contains, among other things, input and output streams that match stdin, stdout, and stderr (standard output, standard input, and standard error).
System.out is a static reference to the standard output stream.
As an object, System.out contains a println(String) method that accepts a String object, and prints that text to the screen, ending with a newline (linefeed).
There is also a print(String) method that does not place a newline at the end.
You can print a String directly, or you can build one from pieces.
Duration: 30 to 40 minutes.
Integrated Development Environments, or IDEs, can greatly facilitate the task of creating applications. Mid-level code editors, such as Crimson Editor, TextPad, or Edit-Plus, provide syntax highlighting, automatic indenting, parentheses and curly-brace matching, and may have tools to compile and execute programs.
High-end environments, such as Eclipse, NetBeans, or JDeveloper, offer many additional features, such as project management, automatic deployment for web applications, code refactoring, code assist, etc. But, these additional capabilities come with the price of additional complexity in the environment, particularly because they force you to create projects for even the simplest applications.
To use the class files in these environments, we must first have a workspace, which is a collection of projects. Workspaces have various configuration settings that will cut across all projects within all projects they contain, such as which version of Java is in use, any added libraries, etc. (a project is usually one application).
Both Eclipse and NetBeans use the workspace concept, but you can start with any empty directory - the IDE will add its own special files as you create projects.
In the Windows Explorer, navigate to your ClassFiles directory. If it does not contain a Workspace subdirectory, create it.
To use Eclipse with the class files, you can direct it to the workspace (ClassFiles/Workspace) when it opens (if it asks), or use File, Switch Workspace if Eclipse is already running. Each chapter's demo folder should be treated as a project, as should each Solution folder.
One limitation of these environments is that no project can contain the same Java class twice, so our progressive versions of the Payroll application solution require their own individual project. Also, due to the way Java's package structures work, each Demo folder must be a separate project, as with each subdirectory under Solutions.
To use the Exercises folder as an Eclipse project:
As we encounter each chapter, we can create a project using the Demos directory for that chapter the same way we just created the Exercises project..
To create a Java class within a project, use File, New , and then Class if that is available, or Other... and then Class . Provide a name and then OK .
In general, with the several applications that we will build upon progressively (Game and Payroll), you can continue to work with the same files, and add to them as we cover additional topics. If you want to check the solutions, you can either open those files in a separate editor, like Notepad, or create a project for that Solutions subdirectory. If you wish to save a particular stage of the application for future reference, you can just make a copy of the Exercises directory.
The examples and instructions provided use a more basic text editor (Chrimson) and an OS console for clarity. You are free to choose which tool to use. If Eclipse becomes a problem, move to a simple editor. The focus of this course is on the Java Programming Language and not a particular tool.
Duration: 5 to 15 minutes.
1.Create a file called Hello.java.
2.Enter the following code:
3.Save the file.
4.In a command prompt window, change to the directory where Hello.java is stored and type the following:
A prompt on the next line without any error messages indicates success.
5.Type:
6.Press Enter.
You should see the message Hello World print in the window.
Sun provides extensive documentation of the API (library of available classes). The documentation for version 6 is available at
If you view that page, you will see a list of classes on the left as hyperlinks. Clicking a class name will bring up the documentation for that class on the right.
For example, click on System. The page on the right contains documentation on the elements of the class, categorized by type of element (there are links at the top for fields, constructors, methods, etc.).
Try to locate the out field - note that the field types, parameter types and return types are hyperlinked, and that out is a PrintStream. Click that, and find the println methods in a table with short descriptions. Select one to see the detailed description. The multiple versions are an example of method overloading, which we will cover in an upcoming lesson. Another lesson will cover documenting your own classes with the same tool that created this documentation.
In this lesson, you have learned:
ava is case-sensitive. main(), Main(), and MAIN() would all be different methods.
There are a limited number of reserved words that have a special meaning within Java. You cannot use these words for your own variables or methods.
Some examples of reserved words are:
Most keyboard symbol characters (the set of characters other than alphabetic or numeric) have a special meaning.
Names may contain alphabetic characters, numeric characters, currency characters, and connecting characters such as the underscore ( _ ) character:
The compiler parses your code by separating it into individual entities called tokens or symbols in computer science jargon:
Tokens may be separated by spaces, tabs, carriage returns, or by use of an operator (such as +, -, etc.).
Since names may not contain spaces, tabs, carriage returns, or operator characters, these characters imply a separation of what came before them from what comes after them.
Extra whitespace is ignored. Once the compiler knows that two items are separate, it ignores any additional separating whitespace characters (spaces, tabs, or carriage returns).
A block of code:
A complete method is a single block of code, most likely with nested blocks.
The diagram below illustrates how blocks of code can be nested:
If you want, go ahead and modify your Hello World program to match this example.
A comment:
Block comments are preceded by /* and followed by */.
Some rules for block comments:
A single line can be commented by preceding the comment with two forward slashes: //. Note that:
Java specifies a third type of comment, the javadoc comment:
Variables store data that your code can use.
There are two fundamental categories of variables, primitive data and references:
In the diagram below, the boxes are areas in memory:
Variables must be declared before they are used.
A declaration informs the compiler that you wish to:
Java uses many specific data types; each has different properties in terms of size required and handling by the compiler:
Code
|
Effect
|
---|---|
int a;
|
declares the name |
int a = 0;
|
same as above, and also assigns an initial value of 0 |
int a = 0, b, c = 3;
|
declares three integer variables and initializes two of them |
Note that different languages have different rules regarding variables that have not been initialized:
Local variables, fields, methods, and classes may be given additional modifiers; keywords that determine special characteristics.
Any modifiers must appear first in any declaration, but multiple modifiers may appear in any order.
Keyword
|
Usage
|
Comments
|
---|---|---|
final
|
local variables, fields, methods, classes |
The name refers to a fixed item that cannot be changed. For a variable, that means that the value cannot be changed. For a method, the method cannot be overridden when extending the class. A |
static
|
fields, methods, inner classes |
Only for fields and methods of objects. One copy of the element exists regardless of how many instances are created. The element is created when the class is loaded. |
transient
|
fields |
The value of this element will not be saved with this object when serialization is used (for example, to save a binary object to a file, or send one across a network connection). |
volatile
|
fields |
The value of this element may change due to outside influences (other threads), so the compiler should not perform any caching optimizations. |
public, protected, private
|
fields, methods classes |
Specifies the level of access from other classes to this element - covered in depth later. |
abstract
|
methods, classes |
Specifies that a method is required for a concrete extension of this class, but that the method will not be created at this level of inheritance - the class must be extended to realize the method. For a class, specifies that the class itself may not be instantiated; only an extending class that is not |
native
|
methods |
The method is realized in native code (as opposed to Java code) - there is an external tool in the JDK for mapping functions from a DLL to these methods. |
strictfp
|
methods, classes |
For a method, it should perform all calculations in strict floating point (some processors have the ability to perform floating point more accurately by storing intermediate results in a larger number of bits than the final result will have; while more accurate, this means that the results might differ across platforms). For a class, this means that all methods are |
synchronized
|
methods, code blocks |
No |
Primitive Type
|
Storage Size
|
Comments
|
---|---|---|
boolean
|
1 bit
|
not usable mathematically, but can be used with logical and bitwise operators |
char
|
16 bits
|
unsigned, not usable for math without converting to int |
byte
|
8 bits
|
signed |
short
|
16 bits
|
signed |
int
|
32 bits
|
signed |
long
|
64 bits
|
signed |
float
|
32 bits
|
signed |
double
|
64 bits
|
signed |
void
|
None
|
not really a primitive, but worth including here |
Objects can be data, which can be stored in variables, passed to methods, or returned from methods.
ReferencesAs we will see later, objects are stored differently than primitives. An object variable stores a reference to the object (the object is located at some other memory location, and the reference is something like a memory address).
Text StringsA sequence of text, such as a name, an error message, etc., is known as a string.
n Java, the String class is used to hold a sequence of text characters.
A String object:
A value typed into your code is called a literal value.
The compiler makes certain assumptions about literals:
Code
|
Effect
|
---|---|
char e = 'X';
|
Creates a 16-bit variable to hold the Unicode value for the uppercase X character. |
You can add modifiers to values to instruct the compiler what type of value to create (note that all the modifiers described below can use either uppercase or lowercase letters).
Modifying prefixes enable you to use a different number base:
Prefix
|
Effect
|
---|---|
0X or 0x
|
A base 16 value; the extra digits can be either uppercase or lowercase, as in char c = 0x1b; |
0
|
A base 8 value, as in int i = 0765; |
Modifying suffixes create a value of a different type than the default:
L or l
|
a long value (uses 64 bits of storage), as in long l = 1234567890123456L; |
---|---|
Note: An int value will always implicitly be promoted to a long when required, but the reverse is not true; the above notation is necessary because the literal value is larger than 32 bits |
|
F or f
|
A float value, as in float f = 3.7F; |
There are a number of escape sequences that are used for special characters:
Escape Sequence |
Resulting Character
|
---|---|
\b
|
Backspace |
\f
|
Form feed |
\n
|
Linefeed character - note that it produces exactly one character, Unicode 10 (\u000A in hex) |
\r
|
Carriage return |
\t
|
Tab |
\"
|
Quote mark |
\'
|
Apostrophe |
\\
|
Backslash |
\uNNNN
|
Unicode value, where N is a base 16 digit from 0 through F; valid values are \u0000 through \uFFFF |
\NNN
|
Value expressed in octal; ranging from \000 to \377 |
The escape sequences can either be used for single characters or within strings of text:
Java has a means for defining contants, which are like variables in that they have names, but are not changeable once set.
If a variable is declared as final, it cannot be changed:
Even though the variable's value is not changeable once a value has been established, you are allowed to set a unique value once.
Local variables within methods may be declared as final.
Constants' values may be set in an explicit initialization, in a separate line of code, or, as method parameters passed when the method is called.
Fields within a class may be declared as final.
Contants' values may be set in an explicit initialization, in a separate line of code within an initialization block, or in a constructor.
Fields of a class may be declared as public static final - that way they are available to other classes, but cannot be changed by those other classes. An example is Math.PI.
Classes and methods may also be marked as final. We will cover this later.
Java-Basics/Demos/FinalValues.java
The class has two final fields, scale and answer. The scale is fixed at 100, while the answer is initialized dynamically, but, once established, the value cannot be changed. Try removing the comment from the line that attempts to set it to 44, and you will see the compiler error message that results.
Looks and behaves like algebra, using variable names and math symbols:
Operator | Purpose (Operation Performed) |
---|---|
+ |
for addition |
- |
for subtraction |
* |
for multiplication |
/ |
for division |
% |
for modulus (remainder after division) |
( and ) |
for enclosing a calculation |
An expression is anything that can be evaluated to produce a value. Every expression yields a value.
Examples (note that the first few of these are not complete statements):Two simple expressions:
An expression that contains another expression inside, the (5/c) part:
A statement is an expression; this one that contains another expression inside - the b + (5/c) part, which itself contains an expression inside it (the 5/c part):
Since an assignment statement (using the = sign) is an expression, it also yields a value (the value stored is considered the result of the expression), which allows things like this:
Here is a moderately complicated expression; let's say that a, b, and c are all double variables, and that a is 5.0, b is 10.0, and c is 20.0:
1.Since the c + 5 is in parentheses, the compiler creates code to evaluate that first, but to perform the c + 5 operation, both elements must be the same type of data, so the thing the compiler creates is a conversion for the 5 to 5.0 as a double.
2.Then the compiler creates code to evaluate 20.0 + 5.0 (at runtime it would become 25.0), reducing the expression to:
3.Next, the compiler adds code to call the Math.sqrt method to evaluate its result, which will be 5.0, so the expression reduces to:
4.Note that the evaluated result of a method is known as the return value, or value returned. 5.Multiplication gets done before addition, the compiler creates that code next, to reduce the expression to:
6.Then the code will perform the addition, yielding:
7.And finally, the assignment is performed so that 55.0 is stored in d.
As implied by the examples we have seen so far, the order of evaluation of a complex expression is not necessarily from left to right. There is a concept called operator precedence that defines the order of operations.
Operator precedence specifies the order of evaluation of an expression.
Every language has a "table of operator precedence" that is fairly long and complex, but most languages follow the same general rules:
The basic rule programmers follow is: when in doubt about the order of precedence, use parentheses.
Try the following program:
Java-Basics/Demos/ExpressionExample.java
Every expression has a value. For an assignment expression, the value assigned is the expression's overall value. This enables chaining of assignments:
x = y = z + 1; is the same as y = z + 1; x = y;
i = (j = k + 1)/2; is the same as j = k + 1; i = j/2;
Quite often, you may need to calculate a value involved in a test, but also store the value for later use:
You might wonder why not just generate the random number when we declare x? In this case, that would make sense, but in a loop the approach shown above might be easier such that:
It is usually not necessary to code this way, but you will see it often.
The order of operand evaluation is always left to right, regardless of the precedence of the operators involved.
Java-Basics/Demos/EvaluationOrder.java
The operands are first evaluated in left to right order, so that the functions are called in the order getA(), then getB(), and, lastly, getC()
But, the returned values are combined together by multiplying the results of getB() and getC(), and then adding the result from getA()
Java has a number of operators for working with the individual bits within a value.
& |
Bitwise AND, combines individual bits with an AND operation, so that in the resulting value, a bit position is only 1 if that position had a 1 for both operands. | ||
---|---|---|---|
int a = 2; |
has the 2 bit set | 0...00000010 |
|
int b = 6; |
has the 2 and 4 bits set | 0...00000110 |
|
int c = a & b; |
results in 2 | 0...00000010 |
|
| |
Bitwise OR, combines individual bits with an OR operation, so that in the resulting value, a bit position is 1 if that position had a 1 for either operand. | ||
int a = 2; |
has the 2 bit set | 0...00000010 |
|
int b = 4; |
has the 4 bit set | 0...00000100 |
|
int c = a | b; |
results in 6 | 0...00000110 |
|
^ |
Bitwise exclusive OR (XOR), combines individual bits so that any position that is the same in both operands yields a 0, any bits that differ yield a 1 in that position; this is often used in encryption, since repeating the operation on the result yields the original value again | ||
int a = 3; |
has the 1 and 2 bits set | 0...00000011 |
|
int b = 6; |
has the 2 and 4 bits set | 0...00000110 |
|
int c = a ^ b; |
results in 5 | 0...00000101 |
|
int d = c ^ b; |
results in 3 again | 0...00000011 |
|
~ |
Bitwise complement. Reverses the state of all bits. | ||
int a = 0; |
has no bits set | 0...00000000 |
|
int b = ~a; |
has all bits set | 1...11111111 |
These operators shift the bits left or right within a 32-bit int value (they do not work with any other type).
<< |
left shift the bits by the second operand | ||
---|---|---|---|
int a = 4; |
has the 4 bit set | 0...00000010 |
|
int b = a << 2; |
now has the 16 bit set | 0...00001000 |
|
>> |
right shift the bits by the second operand with sign-extension (if the first bit is a 1, new bits introduced to fill in on the left come in as 1 bits) | ||
int a = -126; |
has all bits except the rightmost set to 1 | 10...0000010 |
|
int b = a >> 1; |
now has all bits set to 1 (the 0 rolled off the right end, and a 1 was added on the left to match the original leftmost bit; the resulting value is 63) | 110...000001 |
|
>>> |
right shift the bits by the second operand without sign-extension (bits added on the left always come in as 0) | ||
int a = -1; |
has all bits set to 1 | 11...1111111 |
|
int b = a >>> 31; |
now has all bits set to 0 except the rightmost (all bits except the first rolled off the right end, and 0's were added on the left | 0000000...01 |
Combine multiple effects in one operation: calculation and storage into memory
Operator |
Purpose (Operation Performed) |
---|---|
++ |
increment a variable |
-- |
decrement a variable; note that ++ and -- can precede or follow a variable |
if preceding (called prefix), apply the operator and then use the resulting value | |
if following (called postfix), retrieve the value of the variable first, use it as the result of the expression, and then apply the operator | |
+= |
add an amount to a variable |
-= |
subtract an amount from a variable |
*= |
multiply a variable by an amount |
/= |
divide a variable by an amount |
%= |
set variable equal to remainder after division by an amount |
&= |
perform bitwise AND between left and right, store result into left operand |
|= |
perform bitwise OR between left and right, store result into left operand |
^= |
perform bitwise XOR between left and right, store result into left operand |
>>= |
shift the variable's bits to the right by an amount with sign-extension |
>>>= |
shift the variable's bits to the right by an amount without sign-extension |
<<= |
shift the variable's bits to the left by an amount |
Statement |
Result |
---|---|
i++; |
increment i |
i--; |
decrement i |
j = i++; |
retrieve current value of i, hold it as the result of the expression, assign its value to j , then increment i |
j = ++i; |
increment i , then j = i; |
x *= 3; |
x = x * 3; |
y -= z + 5; |
y = y - (z + 5); |
It is inevitable that a certification exam will ask a question that requires understanding the steps involved in a postfix increment or decrement: try the following program:
Java-Basics/Demos/IncrementTest.java
Expressions will often mix different types of data, for example:
The compiler must choose a specific type of data (either integer or floating-point, and the specific size) for each individual expression it evaluates within a statement.
The process of changing the data type of a value is known a typecasting (or casting):
The allowable sequence of implicit casts is shown below:
One aspect of Java that is important to understand is the result of expressions involving the small integral types: byte, char, and short any expression involving these types, other than the compound assignment expressions, is done with int values, so that the result will always be an int.
Try the following (it is the same as the earlier postfix increment example, using byte instead of int):
Note that the increment expression is accepted by the compiler; it is the simple addition in the third line that causes an error.
The Java Language Specification states the promotion rules as follows (note that this concept does not apply to all operators; again, the operators that include assignment do not use it):
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversions to convert operands as necessary:
The method is the basic complete unit of code to perform one task within an object:
Using a method in your code, causing it to run, is known as calling the method.
A method call is an expression, so it may result in a value (the method call is evaluated like any other expression).
Methods must be called with arguments that matching their specified form, known as the function signature:
All methods in Java must be defined within a class definition. They have complete access to all other elements of the class (fields and other methods, regardless of the access modifier used for that element).
Java-Basics/Demos/UseMethodsExample.java
This class calls two methods from the Math class: sqrt and sin, both of which expect one parameter which is a double.
When we call sqrt and pass an integer, the compiler converts that to a double to provide the type of data that sqrt expects
Note that even if your program does not call any methods, it has one method that will be called: main(). Things to note:
There are three things you need to decide for any method:
showNumber(5); from within the class
x.showNumber(5); from outside the class, for an instance x of this class
int value = calculateSum(4, 6); from within the class
int value = x.calculateSum(4, 6); from outside the class, for an instance x of this class
Note that the listing of a data type word in front of a name is something we have seen before, in declaring variables. The purpose is the same - to state what type of data this element provides when used in an expression.
The first statement below states that the value of a is an int, so that the compiler knows what memory size to allocate and what type of processing to use with it when it evaluates the second statement.
The effect is no different using a method; recall the function signature (the first line) of our calculateSum method:
It states that the result of evaluating calculateSum is an int, so that the compiler knows what memory size to allocate for the result, and what type of processing to use with it when it evaluates a statement like:
When this statement gets processed, the calculateSum method will run and return its result (which will be the value 10 as an int).
Thus the statement in effect is reduced to:
Method parameters are also declarations. They declare a type of data received by the method, and also provide a name for each value so it can be used within the method.
Back to our method:
The variable scope rules are similar to those in C++.
Variables can be declared at any point in your code, not just at the top of a block:
Variables declared within a set of curly braces cease to exist after the closing brace has been reached (it is said that they go out of scope); therefore, local variables exist only within that method.
Variables can be declared in the control portion of a for loop, and will exist for the duration of the loop
Parameters to a method are local variables within that method
It is legal to use the same variable name in different scopes, as long as the two scopes have no irresolvable conflicts. Some explanation:
Java-Basics/Demos/MethodExample.java
We will cover the concept of static elements later, but, for now, since main is static, the methods it calls must be static as well
Java has a data type called boolean. Note the following:
The result of a conditional expression (such as a comparison operation) is a boolean value. Note that:
Conditional expressions are used for program control. That means they provide the ability for a program to branch based on the runtime condition or iterate through a block of code until the condition is false.
This chart shows the comparison operators and the types of data they can be applied to.
Operator |
Purpose (Operation Performed) |
Types of Data |
||
---|---|---|---|---|
boolean |
Numeric Primitives and char |
Object References |
||
== |
is equal to (note the two equals signs!) | X | X | X |
!= |
is not equal to | X | X | X |
> |
is greater than | X | ||
< |
is less than | X | ||
>= |
is greater than or equal to | X | ||
<= |
is less than or equal to | X |
Note that it is unwise to use == or != with floating-point data types, as they can be imprecise.
The operators == and != test if two references point to exactly the same object in memory – they test that the numeric values of the two references are the same. The equals(Object o) method compares the contents of two objects to see if they are the same (you can override this method for your classes to perform any test you want).
The following are conditional expression examples.
s == t will evaluate to false
s != t will evaluate to true (they are not the same object - they are two different objects that have the same contents)
s.equals(t) will evaluate to true
s == t will evaluate to true
s != t will evaluate to false (they are the same object)
s.equals(t) will evaluate to true
Note: Java will intern a literal String that is used more than once in your code; that is, it will use the same location for all occurrences of that String
s == t will evaluate to true, because the String object storing "Hello" is stored only once, and both s and t reference that location
s != t will evaluate to false (they are the same object)
s.equals(t) will evaluate to true
Java has operators for combining boolean values with AND and OR logic, and for negating a value (a NOT operation). Note that:
Logical | Bitwise | ||
---|---|---|---|
&&
|
logical AND |
&
|
bitwise AND |
||
|
logical OR |
|
|
bitwise OR |
!
|
logical NOT |
~
|
bitwise NOT (inversion) |
Code | Effect |
---|---|
Testing if a value falls within a range | |
|
is |
Testing if a value falls outside a range | |
|
is |
|
inverts the test for |
The && and || operations are called short-circuiting, because if the first condition determines the final outcome, the second condition is not evaluated.
To force both conditions to be evaluated, use & and | for AND and OR, respectively.
Example: to test if a reference is null before calling a boolean valued method on it.
equalsIgnoreCase will be called only if the reference is not null.
or
Causes "one thing" to occur when a specified condition is met.
The one thing may be a single statement or a block of statements in curly braces. The remainder of the code (following the if and the statement or block it owns) is then executed regardless of the result of the condition.
The conditional expression is placed within parentheses.
The following flowchart shows the path of execution:
If we needed the absolute value of a number (a number that would always be positive):
Java-Control/Demos/If1.java
Task: write a brief program which generates a random number between 0 and 1. Print out that the value is in the low, middle, or high third of that range (Math.random() will produce a double value from 0.0 up to but not including 1.0).
Java-Control/Demos/If2.java
Duration: 15 to 20 minutes. Write a program called Game that will ask the user to guess a number and compare their guess to a stored integer value between 1 and 100.
Solutions/Game01/Game.java
Each of the the three possible cases is tested individually as shown below. All three tests will always be performed. In the next version, we will make the tests mutually exclusive, so that processing stops when one is true. we will use a more efficient approach.
Duration: 10 to 15 minutes. We will modify our payroll program to check the pay rate and department values.
Solutions/Payroll-Control01/employees/Employee.java
The Employee class should protect itself from bad incoming data, so the setPayRate method simply ignores a value less than 0. A better practice, which we will add later, would be to throw an exception when an illegal value is passed in. Note the benefit of coding the constructors to use the setPayRate method; we do not have to go back and revise their code as well. (setDept has similar changes.)
Solutions/Payroll-Control01/Payroll.java
Even though Employee now protects itself from illegal incoming values, it should really be the responsibility of the progmmers for the classes using Employee to avoid sending it bad values. So, the payRate value is tested here as well. While this may seem to decrease efficiency (since, presumably, a non-object-oriented program might be able to avoid testing the value twice in a row), the maintainability aspects of OOP are still considered to outweigh the loss in efficiency.
The if ... else Statement does "one thing" if a condition is true, and a different thing if it is false.
It is never the case that both things are done. The "one thing" may be a single statement or a block of statements in curly braces.
A statement executed in a branch may be any statement, including another if or if ... else statement.
This program tells you that you are a winner on average once out of every four tries.
Java-Control/Demos/IfElse1.java
You can nestif ... else statements, so that an if or else clause contains another test. Both the if and the else clause can contain any type of statement, including another if or if ... else.
You can test individual values or ranges of values. Once an if condition is true, the rest of the branches will be skipped. You could also use a sequence of if statements without the else clauses (but this doesn't by itself force the branches to be mutually exclusive).
Here is the low/middle/high example rewritten using if ... else
Java-Control/Demos/IfElse2.java
Similarly, we do not test the high third at all. The original version worked because there was no chance that more than one message would print; that approach is slightly less efficient because all three tests will always be made. In the if ... else version, comparing stops once a match has been made.
Duration: 10 to 15 minutes.
1.At the top:
2.Add a private field for a random number generator:
1.Then, you can initialize the answer field:
the nextInt(int n) method generates a number greater than or equal to 0 and less than n, so r.nextInt(100) would range from 0 through 99; we need to add 1 to raise both ends of the range.
4.You might want to print the expected correct answer to aid debugging.
Note that until we cover looping, there will be no way to truly "play" the game, since we have no way to preserve the value between runs.Solutions/Game02/Game.java
A switch expression (usually a variable) is compared against a number of possible values. It is used when the options are each a single, constant value that is exactly comparable (called a case).
The switch expression must be a byte, char, short, or int. Cases may only be byte, char, short, or int values; in addition, their magnitude must be within the range of the switch expression data type and cannot be used with floating-point datatypes or long and cannot compare an option that is a range of values, unless it can be stated as a list of possible values, each treated as a separate case.
Cases are listed under the switch control statement, within curly braces, using the case keyword. Once a match is found, all executable statements below that point are executed, including those belonging to later cases; this allows stacking of multiple cases that use the same code.
The break; statement is used to jump out of the switch block, thus skipping executable steps that are not desired. The default case keyword catches all cases not matched above - note that the default case does not need to be the last thing in the switch. Note that technically speaking, the cases are labeled lines; the switch jumps to the first label whose value matches the switch expression.
Usage
Java-Control/Demos/Switch1.java
Three points to note:
Here is a revised version that moves the default to the top, so that a bad entry is flagged with an error message, but then treated as an 'A' - note that there is no break below the default case.
Java-Control/Demos/Switch2.java
Another example is taking advantage of the "fall-though" behavior without a break statement.
Code Sample:
Java-Control/Demos/Christmas.java
Duration: 15 to 30 minutes. What if we want to offer gamers multiple levels of difficulty in our game? We could make the random number multiplier a property of the Game class, and set a value into it with a constructor, after asking the user what level they'd like to play.
Solutions/Game03/Game.java
The switch tests for the three letters, stacking cases for uppercase and lowercase values. The default catches all other responses and falls through to the Beginner logic.
The operators == and != test if two references point to exactly the same object in memory; they test that the numeric values of the two references are the same.
The equals(Object o) method compares the contents of two objects to see if they are the same (you can override this method for your classes to perform any test you want).
When comparing two objects, the == operator compares the references and not the values of the objects. Similarly, != tests to see if the references point to two different objects (even if they happen to have the same internal values).
The Object class defines an equals(Object) method intended to compare the contents of the objects. The code written in the Object class simply compares the references using ==. This method is overridden for most API classes to do an appropriate comparison. For example, with String objects, the method compares the actual characters up to the end of the string. For classes you create, you would override this method to do whatever comparisons you deem appropriate.
Java-Control/Demos/Rectangle.java
The equals method compares another object to this object.
This example is necessarily somewhat complicated. It involves a few concepts we haven't covered yet, including inheritance. Because the equals method inherited from Object, it takes a parameter which is an Object, we need to keep that that type for the parameter (technically, we don't need to do it by the rules of Java inheritance, but because other tools in the API are coded to pass an Object to this method). But, that means that someone could call this method and pass in something else, like a String.
So, the first thing we need to do is test that the parameter was actually a Rectangle. If so, we can work with it; if not, there is no way it could be equal, so we return false.
We will cover instanceof later, but, for now, we can assume it does what it implies: test that the object we received was an instance of Rectangle. Even after that test, in order to treat it as a Rectangle, we need to do a typecast to explicitly store it into a Rectangle variable (and again, we will cover object typecasting later). Once we have it in a Rectangle variable, we can check its height and width fields.
In yet another complication, if we write an equals method, we should really write a public int hashcode() method as well, since their meanings are interrelated; two elements that compare as equal should produce the same hashcode.
As an aside, note that private data in one instance of a class is visible to other instances of the same class; it is only otherclasses that cannot see the private elements.
Java-Control/Demos/ObjectEquivalenceIdentity.java
Since all the important work is done in Rectangle, all we need to do here is instantiate two and compare them using both == and the equals method to see the differing results.
The output should be:
Example - write a brief program which has a word stored as a string of text. Print a message asking for a word, read it, then test if they are the same or not.
Java-Control/Demos/StringEquals.java
Java uses the same conditional expression as C and C++
This performs a conditional test in an expression, resulting in the first value if the condition is true,or the second if the condition is false
Note: due to operator precedence issues, it is often best to enclose the entire expression in parentheses
Example
Java-Control/Demos/Conditional.java
Note that the parentheses around the test are not necessary by the operator precedence rules, but may help make the code clearer
The parentheses around the entire conditional expression are necessary; without them, precedence rules would concatenate the boolean result onto the initial string, and then the ? operator would be flagged as an error, since the value to its left would not be a boolean.
Again, the loops in Java are pretty much the same as in C - with the exception that the conditional expressions must evaluate to only boolean values
while loops
or
do ... while loops
or
A for loop uses a counter to progress through a series of values
or
for loops can use a variable declared out side of the control portion of the loop or in the control portion. The latter gives the variable block-level scope (existing only for the duration of the loop)
A for loop may use multiple control variables by using the sequence operator, the comma ( , )
Note: if you use a block-scope variable (such as above) for the first counter, the additional ones will be block scope as well, and also will be the same type of data - i.e., the variable k above also exists only for the duration of the block. There is no way to declare two counters of different types at block-level scope.
Note that neither while nor do . . . while loops allow declaring a looping variable with this type of scope. The looping variable must be declared in advance.
Java 5 introduced a new type of loop, the for-each loop. When you have an array or collection class instance, you can loop through it using a simplified syntax
The looping variable is not a counter - it will contain each element of the array or collection in turn (the actual value and not an index to it, so its type should be the same as the type of items in the array or collection). You can read the : character as if it is the word "from". We will cover this type of loop in more depth in the Arrays section.
For some reason, the looping variable must be declared within the parentheses controlling the loop - you cannot use a preexisting variable.
Since the looping variable is a local variable, it gets a copy of each value from the array or collection. Therefore you cannot use the ForEach loop to write values back to the array/collection - assigning a new value to the variable in the body of the loop is only overwriting the local copy.
Java-Control/Demos/Loops1.java
Breaking Out of a Loop
The break statement will end a loop early and execution jumps to the first statement following the loop. The following example prints random digits until a random value is less than 0.1.
Java-Control/Demos/Break.java
This code loops, generating and printing a random number for each iteration. If the number is less than 0.1, we break out before printing it.
Java-Control/Demos/BreakNot.java
This code avoids the break, by creating and testing the random number in the control part of the loop. As part of the iteration condition, if the number is less than 0.1, the loop simply ends "normally".
If you need to stop the current iteration of the loop, but continue the looping process, you can use the continue statement. Note that:
Example - a program to enter 10 non-negative numbers
Java-Control/Demos/Continuer.java
A better way to handle the loop is shown in the commented out version of main - try removing the comment and comment out the original method.
But,continue is easier to use in nested loops, because you can label the level that will be continued
In normal usage, break and continue only affect the current loop; a break in a nested loop would break out of the inner loop, not the outer one
But, you can label a loop, and break or continue at that level. A label is a unique identifier followed by a colon character.
Try the following example as is, then reverse the commenting on the break lines
Java-Control/Demos/BreakOuter.java
Duration: 10 to 20 minutes.
(Optional)
Solutions/Game04/Game.java
Duration: 20 to 40 minutes.
Solutions/Payroll-Control02/Payroll.java
By now, you may have noticed that every demo and solution folder contains its own copy of util and KeyboardReader. Not only is it inefficient, but it means that we would have to locate and update each copy if we wanted to change KeyboardReader.
A better solution would be to have one master copy somewhere that all of our exercises could access.
Using CLASSPATH
Java has a CLASSPATH concept that enables you to specify multiple locations for .class files, at both compile-time and runtime.
By default, Java uses rt.jar in the current Java installation's jre/lib directory, and assumes that the classpath is the current directory (the working directory in an IDE).
If you create a classpath, the default one disappears, so any classpath that you create must include the current directory using a period (.) character.
To use an external library, you would need to create a classpath in one of two ways:
Here is an example of a pair of commands to compile and run using an external library stored in a jar file. Note that we need the jar file at both compile-time and runtime. The -cp option in both commands replaces the system classpath with one specifically for that command.
Many Integrated Development Environments (IDEs) have a means to specify project properties; usually an item like "Build Path" will have options to specify external jar files (as well as choose from various libraries supplied with the environment).
Creating a jar File (a Library)
If you wish to create your own library of useful classes, you can bundle one or more classes and/or directories of classes in a jar file. Yyou can also add other resources such as image files.
A jar file contains files in a zipped directory structure. The root level of the file structure should match the root of the package structure; for example, to put KeyboardReader in a jar file, we would want to start at the directory where util is visible, and jar that
The following command will create a jar file called utilities.jar for all files in the util package (just KeyboardReader, in this case).
The options are create, verbose, and use a list of files supplied at the end of the command.
An array stores a group of data items all of the same type.
An array is an object.
You can read the [] as the word "array".
To declare a variable for an array of integers:
..which you can read as "int array nums".
To declare a variable for an array of String objects:
...which you can read as "String array names" - the array holds String references.
You may also put the brackets after the variable name (as in C/C++), but that is less clearly related to how Java actually works.
But, that syntax does allow the following, which is legal, but seems like a bad practice.
Instantiate an array object using new, the data type, and an array size in square brackets
The second line constructs a new array object with 10 integer elements, all initialized to 0, and stores the reference into nums.
You can declare and instantiate all at once:
The elements of the array, String references, are initialized to null.
The original ten-element array is no longer referenced by nums, since it now points to the new, larger array.
An array can be initialized when it is created
The notation looks like this:
or
This automatically creates an array of length 3, because there were 3 items supplied.
This array will have a length of 6.
If a new array is being assigned to an existing variable, you cannot use the shorter variant, you must use the new keyword and the data type:
For arrays of other types of objects:
The valid elements are 0, 1, and 2, as in:
You could access array elements in a for loop with:
Or, better programming practice would be to use the length property:
The compiler does not check to ensure that you stay within the bounds of the array, but the JVM does check at runtime - if you try to exceed the bounds of the array, an exception will occur.
Note that a zero-length array is valid:
You might create a zero-length array as the return value from a method typed as returning an array, when there are no items to return (as opposed to returning null).
Java-Arrays/Demos/Arrays1.java
The array as a whole can be referenced by the array name without the brackets, for example, as a parameter to or return value from a function
Java-Arrays/Demos/Arrays2.java
The array names is passed to printArray, where it is received as data.
Note also the syntax to access a method directly for an array element: data[i].toUpperCase()
Since an array reference is a variable, it can be made to refer to a different array at some point in time
You can use System.arraycopy to copy an array into another.
You might do this to expand an array by creating a larger one and copying the contents of the smaller one into it (but any references to the original array will need to be changed to point to the new array).
The declaration is:
Java-Arrays/Demos/CopyArray.java
Solutions/Arrays/HelloArgs.java
The for loop iterates through the array; each separate word on the command line becomes one element in the array (note that java HelloArgs is not part of the array).
There are three arrays of messages; note that they are not all the same size. The code to handle too high, too low, and correct generates a random number between 0 and the appropriate array's length, by using the Random object's nextInt method, and passing the length of the array.
If an array contains objects, those objects' properties and methods may be accessed.
The notation uses the array variable name, the index in brackets, a dot, and the property or method.
Java-Arrays/Demos/Arrays2.java
Solutions/Payroll-Arrays01/Payroll.java
The code uses e[i].getPayInfo() to print the pay information for employee i. Element i of the array is one employee reference. It uses the same approach to call e[i].getLastName() for each employee to compare with the requested name.
You cannot write into the array using a for-each loop. The looping variable you declare receives a copy of the data in the array, so, if you change its value, you are only changing the local copy.
Arrays are objects, and, like other objects, declaring a variable does not instantiate the array - that must be done separately. To instantiate a multidimensional array:
The most significant dimension is listed first; the least significant dimension listed last.
The code below could be used to declare an array to store an image that is 640 pixels across and 480 pixels down - in a graphic the image data is stored sequentially across each row; each row is a 640 pixel block; there are 480 of these blocks in our image:
This code might be used for an image where the data is stored in three layers, each of which is an entire 480 by 640 array:
Note that it is possible to replace any of the one-dimensional elements with a different one, or that the second-dimension arrays each have a different length - the following line would replace one of the arrays with another of a different length
Java-Arrays/Demos/ArrayPicture.java
public class ArrayPicture { public static void main(String[] args) { char[][] imgData = new char[][] { { ' ',' ',' ',' ',' ',' ',' ' }, { ' ',' ',' ','0',' ',' ',' ' }, { ' ',' ',' ','|',' ',' ',' ' }, { ' ','0','-','+','-','0',' ' }, { ' ',' ',' ','|',' ',' ',' ' }, { ' ',' ',' ','0',' ',' ',' ' }, { ' ',' ',' ',' ',' ',' ',' ' } }; for (int row = 0; row < imgData.length ; row++ ) { for (int col = 0; col < imgData[row].length; col++ ) { System.out.print(imgData[row][col]); } System.out.println(); } } }
Because multi-dimensional arrays are implemented as arrays of array references, it is possible to partially instantiate an array:
This creates nums as a two-dimensional array (better viewed in this case as an array of array references), and creates an array holding three null references to integer arrays
It is not possible to typecast an array of one type of primitive to an array of another type of primitive. For example, the following will cause compiler errors if the comment marks are removed:
Java-Arrays/Demos/ArrayTypecast.java
Neither an implicit or explicit typecast can be performed. With a single int i, the copy of it that is given to d can be expanded to a double. But, with the int[] inums, the value that would be given to dnums is just a copy of the reference to inums, so there is no way that each of the individual elements can be expanded to double.
The next chapter will discuss typecasting from arrays of one type of object to another.
Say you were creating an arcade game, with a number of different types of beings that might appear - wizards, trolls, ogres, princesses (or princes), frogs, etc. All of these entities would have some things in common, such as a name, movement, ability to add/subtract from the player's energy - this could be coded in a base class Entity.
For entities that can be chosen and controlled by a player (as opposed to those that merely appear during the course of the game but can't be chosen as a character) a new class Playable could extend Entity by adding the control features.
Then, each individual type of entity would have its own special characteristics; those that can be played would extend Playable, the rest would simply extend Entity.
you could then create an array that stored Entity objects, and fill it with randomly created objects of the specific classes. For example, your code could generate a random number between 0 and 1; if it is between 0.0 and 0.2, create a Wizard, 0.2 - 0.4 a Prince, etc.
The Java API is a set of classes that make extensive use of inheritance. One of the classes used in the GUI is Window; its family tree looks like this:
Our payroll program could make use of inheritance if we had different classes of employees: exempt employees, nonexempt employees, and contract employees
This would leave us with an inheritance scheme as follows:
Note that a scheme with ContractEmployee extending NonexemptEmployee might also be a reasonable approach
You can view a derived class object as having a complete base class object inside it. Let's assume that the Entity class defines the fields name, energy, and position, and methods moveTo() and changeEnergy().
The Playable class adds a field playerID, and the Wizard class adds a spells field (an array of spells they can cast) and a castSpell() method.
Any Wizard object contains all the elements inside its box, include those of the base classes. So, for example, the complete set of properties in a Wizard object is:
A Wizard reference to a Wizard object has access to any public elements from any class in the inheritance chain from Object to Wizard. Code inside the Wizard class has access to all elements of the base classes (except those defined as private in the base class - those are present, but not directly accessible).
A more complete description of access levels is coming up.
Note: although it appears that a base class object is physically located inside the derived class instance, it is not actually implemented that way.
If a derived class extends a base class, it is not only considered an instance of the derived class, but an instance of the base class as well. The compiler knows that all the features of the base class were inherited, so they are still there to work in the derived class (keeping in mind that they may have been changed).
This demonstrates what is known as an Is A relationship - a derived class object is A base class instance as well.
It is an example of polymorphism; that one reference can store several different types of objects. For example, in the arcade game example, for any character that is used in the game, an Entity reference variable could be used, so that at runtime, any subclass can be instantiated to store in that variable.
For the player's character, a Playable variable could be used.
When this is done, however, the only elements immediately available through the reference are those know to exist; that is, those elements defined in the reference type object. Note that:
There is no way the compiler could determine what type of object would actually be created.
The variables names above, shrek, merlin, and charles, are probably not good choices: presumably we know shrek is an ogre, and always will be, so the type might as well be Ogre (unless, of course, he could transmogrify into something else during the game ...).
When a method is called through a reference, the JVM looks to the actual class of the instance to find the method. If it doesn't find it there, it backs up to the ancestor class (the class this class extended) and looks there (and if it doesn't find it there, it backs up again, potentially all the way to Object).
Sooner or later, it will find the method, since if it wasn't defined somewhere in the chain of inheritance, the compiler would not have allowed the class to compile.
In this manner, what you could consider the most advanced (or most derived) version of the method will run, even if you had a base class reference.
So, for our arcade game, an Entity reference could hold a Wizard, and when the moveTo method is called, the Wizard version of moveTo will run.
An interesting aspect of dynamic method invocation is that it occurs even if the method is called from base class code. If, for example:
The Entity version of moveTo would run, but its call to toString would invoke the toString method from Ogre!
The syntax for extending a base class to create a new class is:
If you do not extend any class, Java assumes you are extending Object by default
Your new class can use the fields and methods contained in the original class (subject to the note coming up in a few pages about access keywords), add new data fields and methods, or replace fields or methods.
A derived class object may be stored in a base class reference variable without any special treatment. If you then want to store that object in a derived class reference again, you can force that with a typecast.
Java doesn't allow multiple inheritance, where one class inherits from two or more classes. Note that:
When a derived class is created, an object of the new class will in effect contain all the members of the base and derived classes. In some cases, the accessibility modifiers can limit base class members availability in the derived class, but we will cover that issue later.
The following maps out the relation between the derived class and the base class (note that the diagrams show the apparent memory allocation, in a real implementation the base class memory block is not inside the derived class block).
Class Code | Apparent Memory Allocation |
---|---|
public class MyBase { public int x; public void show() { System.out.println("x =" + x); } |
|
class MyDerived extends MyBase { public int y; public void show() { System.out.println("x = " + x); System.out.println("y = " + y); } } |
Since everything in MyBase is public, code in the MyDerived class has free access to the x value from the MyBase object inside it, as well as y and show() from itself.
The show() method from MyBase is also available, but only within MyDerived class code (but some work is required to get it, since it is hidden by the show() method added with MyDerived) - code in other classes cannot invoke the MyBase version of show() at all.
When inheritance is used to create a new (derived) class from an existing (base) class, everything in the base class is also in the derived class. It may not be accessible; however, the access in the derived class depends on the access in the base class:
Base class access | Accessibility in derived class |
---|---|
public
|
public
|
protected
|
protected
|
private
|
Inaccessible |
Unspecified (package access) | Unspecified (package access) |
Note that private elements become inaccessible to the derived class - this does not mean that they disappear, or that that there is no way to affect their values, just that they can't be referenced by name in code within the derived class
Also note that a class can extend a class from a different package
Since a derived class object contains the elements of a base class object, it is reasonable to want to use the base class constructor as part of the process of constructing a derived class object.
Constructors are "not inherited". In a sense, this is a moot point, since they would have a different name in the new class, and can't be called by name under any circumstances, so, for example, when one calls new Integer(int i) they shouldn't expect a constructor named Object(int i) to run.
Within a derived class constructor, however, you can use super( parameterList ) to call a base class constructor. Note that:
Java-Inheritance/Demos/Inheritance1.java
The diagram below shows the structure of our improved classes:
As we saw before, you can create a method in the derived class with the same name as a base class method. Note that:
One base class constructor will always run when instantiating a new derived class object.
Java-Inheritance/Demos/Inheritance2.java
Each constructor prints a message so that we can follow the flow of execution. Note that using new Violet() causes Purple() to run, and that new Violet(4) also causes Purple() to run.
For the sake of simplicity, the i field has been made protected, but this is not considered a good practice.
If your base class has constructors, but no no-arguments constructor, then the derived class must call one of the existing constructors with super(args), since there will be no default constructor in the base class.
If the base class has a no-arguments constructor that is private, it will be there, but not be available, since private elements are hidden from the derived class. So, again, you must explicitly call an available form of base class constructor, rather than relying on the default.
Try the above code with the Purple() constructor commented out or marked as private.
In general, when an object is instantiated, an object is created for each level of the inheritance hierarchy. Each level is completed before the next level is started, and the following takes place at each level:
When the process has completed, the expression that created the instance evaluates to the address of the block for the last unit in the chain.
Inheritance and static Elementsstatic methods in a class may not be overridden in a derived class. This is because the static method linkages are not resolved with the same dynamic mechanism that non-static methods use. The linkage is established at compile time.
Since personnel and probably other people in our overall corporate software suite (contact management, perhaps) would have some basic personal attributes in common, we will pull the first and last name fields into a base class representing a person.
Java-Inheritance/Demos/employees/Person.java
This class includes the name fields and related set and get methods.
Java-Inheritance/Demos/employees/Employee.java
Since this class now extends Person, the name-related elements are already present, so we remove them from this code. We took advantage of the Person constructor that accepst first and last names in the corresponding Employee constructor.
Note that since getPayInfo calls getFullName, which is now inherited and publicly accessible, that code did not need to change.
Java-Inheritance/Demos/Payroll.java
No changes need to be made to Payroll to take advantage of the addition of the inheritance hierarchy that we added. The only changes we made were for the sake of brevity.
To revisit the sequence of events when instantiating an Employee using the constructor that accepts the first and last names, department, and pay rate:
Duration: 30 to 45 minutes. We wish to improve our payroll system to take account of the three different types of employees we actually have: exempt, nonexempt, and contract employees. Rather than use some sort of identifying code as a property, OOP makes use of inheritance to handle this need, since at runtime a type can be programmatically identified. So we will create three new classes that extend Employee:
In our company, exempt employees get a monthly salary, nonexempt an hourly rate that is multiplied by their hours, as do contract employees. There won't be any real difference between nonexempt and contract employees within their code. Realistically, in a real application, there would be, but, even if there weren't, it would still be a good idea to have separate classes, since the class type itself becomes a bit of information about the object. In the exception class hierarchy, there are many classes that have no internal differences; The multiple classes serve merely to identify the type of problem that occured.
We can inherit much of the logic from Employee, such as the pay rate fields and methods, as well as the name-related elements indirectly gained from Person. But, ContractEmployee and NonexemptEmployee will both add logic related to hours, and all three classes will override the getPayInfo method.
Also, the solution code builds upon the Person base class from the preceding example. You can either copy the Person.java file into your working directory and edit Employee.java to match, or just copy the set of files from the Java-Inheritance/Demos directory into your working directory and use those.
Solutions/Payroll-Inheritance01/employees/ExemptEmployee.java
The primary thing to notice about this file is that it rewrites each constructor with one line to call the equivalent form of super.
Solutions/Payroll-Inheritance01/employees/NonexemptEmployee.java
In addition to rewriting the existing constructors, this class adds another that accepts hours, as well as appropriate methods to get and set that value.
Solutions/Payroll-Inheritance01/employees/ContractEmployee.java
This class is virtually identical to NonexemptEmployee. Realistically, there would be differences due to benefits, dependents, etc.
Given the similarity between ContractEmployee and NonexemptEmployee, it might be worth refactoring to have a common base class for hourly employees, especially if there were situations where we would want to work with all hourly employees, regardless of type.
Exercises/Payroll4Inheritance01.java
Object references can be typecast only along a chain of inheritance. If class MyDerived is derived from MyBase, then a reference to one can be typecast to the other. An upcast converts from a derived type to a base type, and will be done implicitly, because it is guaranteed that everything that could be used in the base is also in the derived class.
A downcast converts from a parent type to a derived type, and must be done explicitly.
even though o came from a String, the compiler only recognizes it as an Object, since that is the type of data the variable is declared to hold.
As a memory aid, if you draw your inheritance diagrams with the parent class on top, then an upcast moves up the page, while a downcast moves down the page.
The compiler will not check your downcasts, other than to confirm that the cast is at least feasible. For instance, there is no possibility of a typecase between String and Integer, since neither is a base class to the other.
But, the JVM will check at runtime to make sure that the cast will succeed. A downcast could fail at runtime because you might call a method that is not there, so the JVM checks when performing the cast in order to fail as soon as possible, rather than possibly having some additional steps execute between casting and using a method.
Since t was not actually a String, this would fail with a runtime exception during the cast operation. At that point, the runtime engine sees that it cannot make the conversion and fails.
You can use a typecast in the flow of an operation, such as:
((MyBase) rv) casts rv to a MyDerived, for which the getY() method is run.
Note the parentheses enclosing the inline typecast operation; this is because the dot operator is higher precedence than the typecast; without them we would be trying to run rv.getY() and typecast the result (technically, Java does not consider the dot an operator, but a separator , like curly braces, parentheses, and square brackets - the net effect is the same, since separators get applied before operators).
The concept of polymorphism means "one thing - many forms."
In this case, the one thing is a base class variable; the many forms are the different types derived from that base class that can be stored in the variable.
Storing a reference in a variable of a base type does not change the contents of the object, just the compiler's identification of its type - it still has its original methods and fields.
You must explicitly downcast the references back to their original class in order to access their unique properties and methods. If you have upcast, to store a derived class object with a base class reference, the compiler will not recognize the existence of derived class methods that were not in the base class.
The collection classes, such as Vector, are defined to store Objects, so that anything you store in them loses its identity. You must downcast the reference back to the derived type in order to access those methods. The introduction of generics in Java 1.5 provides a solution to this annoyance (more on this in the Collections lesson).
During execution, using a base class reference to call to a method that has been overridden in the derived class will result in the derived class version being used. This is called dynamic method invocation.
The following example prints the same way twice, even though two different types of variable are used to reference the object:
Java-Inheritance/Demos/Inheritance3.java
Situations where you would often see a base class reference:
You can change the access level of a method when you override it, but only to make it more accessible.
This avoids a logical inconsistency:
As a more specific example of why this is the case, imagine that ExemptEmployee overrode public String getPayInfo() with private String getPayInfo().
The compiler would allow
But, if you were to extend a class from the Java API or other library, you wouldn't necessarily know what fields it had - this facility allows you to use whatever field names you want, and, as long as the base class versions were private, you would not get any adverse effects.
Say our game program needed to store references to Entity objects.
Perhaps our code for Entity includes a method moveTo() that moves it to a new location. Many of the entities move the same way, but perhaps some can fly, etc. We could write a generally useful form of moveTo in the Entity class, but then override it as necessary in some of the classes derived from Entity.
Java-Inheritance/Demos/EntityTest.java
The compiler allows the calls to the moveTo method because it is guaranteed to be present in any of the subclasses - since it was created in the base class.
If not overridden in the derived class, then the base class version will be used.
If the method is overridden by the derived class, then the derived class version will be used.
At runtime, the JVM searches for the method implementation, starting at the actual class of the instance, and moving up the inheritance hierarchy until it finds where the method was implemented, so the most derived version will run.
Given that you can have base class references to several different derived class types, you will eventually come to a situation where you need to determine exactly which derived class is referenced - you may not know it at the time the program is compiled.
In the above example, perhaps wizards, ogres, trolls, etc. have their own special methods.
How would you know which method to call if you had an Entity reference that could hold any subclass at any time?
The instanceof operator is used in comparisons - it gives a boolean answer when used to compare an object reference with a class name.
It will yield true if the reference points to an instance of that class.
It will also give true if the object is a derived class of the one tested.
If the test yields true, then you can safely typecast to call a derived class method (you still need to typecast to call the method - the compiler doesn't care that you performed the test).
For example:
There is another method of testing:
It is rare that you would need this type of test.
Duration: 45 to 60 minutes.
Solutions/Payroll-Inheritance02/Payroll.java
We reduced the amount of code by recognizing that some of the data entry logic is common to all three types - asking for first and last names and department before the switch. This required some additional shuffling of declarations, plus some restructuring to avoid asking for the name information all over again if the employee type is not valid (we used continue to avoid processing an employee if the type wasn't valid, and backed up the loop counter to go over the same array location on the next iteration).
For the report, the same logic is essentially repeated three times:
The instanceof test enables us to isolate just one type of employee to print; the others will be skipped over.
Duration: 5 to 5 minutes.
Solutions/Payroll-Inheritance03/employees/Person.java
Solutions/Payroll-Inheritance03/employees/Employee.java
package employees; public abstract class Employee extends Person { ---- C O D E O M I T T E D ---- public abstract String getPayInfo(); }
There are a number of useful methods defined for Object.
Some are useful as is, such as:
Class getClass() - returns a Class object (a representation of the class that can be used for comparisons or for retrieving information about the class).
Others are useful when overridden with code specific to the new class:
Object clone() - creates a new object that is a copy of the original object. This method must be overridden, otherwise an exception will occur (the Object version of clone throws a CloneNotSupportedException).
The issue is whether to perform a shallow copy or a deep copy - a shallow copy merely copies the same reference addresses, so that both the original object and the new object point to the same internal objects; a deep copy makes copies of all the internal objects (and then what if the internal objects contained references to objects ...? ).
boolean equals(Object) - does a comparison between this object and another. If you don't override this method, you get the same result as if you used == (that is, the two references must point to the same object to compare as equal - two different objects with the same field values would compare as unequal) - that is how the method is written in the Object class. You would override this method with whatever you need to perform a comparison.
int hashCode() - returns an integer value used by collection objects that store elements using a hashtable. Elements that compare as the same using the equals(Object) method should have the same hashcode.
String toString() - converts this object to a string representation.
This method is called by a some elements in the Java API when the object is used in a situation that requires a String, for example, when you concatenate the object with an existing String, or send the object to System.out.println().
Note that the call to toString is not made automatically as a typecast to a String - the only behavior built into the syntax of Java is string concatenation with the + sign (so one of the operands must already be a String); the code in println is explicitly written to call toString.
If you don't override this method, you will get a strange string including the full class name and the hashcode for the object void finalize() - called by the JVM when the object is garbage-collected. This method might never be called (the program may end without the object being collected).
There are also a several methods (wait, notify, and notifyAll) related to locking and unlocking an object in multithreaded situations.
Java-Inheritance/Demos/ObjectMethods.java
The clone method returns Object rather than ObjectMethods, since that is how it was declared in the Object class, and you can't change the return type when overriding - thus the typecast on the returned value.
Similarly, the parameter to equals is Object, rather than ObjectMethods. This is not required by Java's syntax rules, but rather a convention that enables other classes to work with this class. For example, the Collections API classes use the equals method to determine if an object is already in a set. If we wrote the method as equals(ObjectMethods om) instead of equals(Object o), the collections classes would call equals(Object o) as inherited from Object, which would test for identity using an == test.
The hashCode method was written out of a sense of duty - Sun specifies that the behavior of hashCode "should be consistent with equals", meaning that if two items compare as equal, then they should have the same hash code - this will be revisited in the section on Collections.
nterfaces define a standardized set of commands that a class will obey.
The commands are a set of methods that a class implements.
The interface definition states the names of the methods and their return types and argument signatures. There is no executable body for any method that is left to each class that implements the interface.
Once a class implements an interface, the Java compiler knows that an instance of the class will contain the specified set of methods. Therefore, it will allow you to call those methods for an object referenced by a variable whose type is the interface.
Implementing an interface enables a class to be "plugged in" to any situation that requires a specific behavior (manifested through the set of methods).
An analogy: a serial interface on a computer defines a set of pin
/wire assignments and the control signals that will be used. Note that:
To create an interface definition:
Java-Interfaces/Demos/Printable.java
This interface requires only one method. Any class implementing Printable must contain a public void printall() method in order to compile.
Because the above interface is defined as public, its definition must be in its own file, even though that file will be tiny.
An interface definition may also define fields that are automatically public static final - these are used as constants.
A class definition may, in addition to whatever else it does, implement one or more interfaces.
Once a class states that it implements an interface, it must supply all the methods defined for that interface, complete with executable code.
It is important to note that a class may implement an interface in addition to whatever else it might do, so it could have additional fields and methods not associated with the interface.
A class may implement more than one interface - that merely adds to the list of required methods. Use a comma-separated list for the interface names.
The complete example will use three separate files (the third file will be shown shortly):
Java-Interfaces/Demos/Printable.java
Java-Interfaces/Demos/PrintableThings.java
This file contains two classes with package access. Since the classes are not public, they can both be in the same file, and the file name does not need to match either class name. This is done purely as a convenience; it is not a good programming practice in general, but is sometimes useful if one class is highly coupled (interrelated) with the other, which is not the case here. Both classes implement the Printable interface, but are otherwise not related. Stock has another method not related to Printable.
An interface is like a class where the internal structure and some of the behavior is hidden.
Interfaces are listed like classes in the API documentation.
They compile to a .class file, and get loaded by the same process that loads true classes.
Since a class that implements an interface is a class in all other respects, you can create a reference variable for that class, as usual.
You can also create a reference variable whose type is the interface name.
Only the methods defined in the interface are visible through a variable whose type is the interface.
For a Printable variable containing a Stock instance, the sell method is not visible, since it is not declared in Printable.
Any constants defined by the interface can be accessed without a prefix from code within the class, since implementing the interface makes them part of this class.
To access an interface-implementing class with an interface class reference:
Example:
or
or
If you have a variable that is declared as a reference to the interface type, you can use it to call an interface method.
Note :that you cannot call any of the additional methods that are not defined by the interface.
Java-Interfaces/Demos/PrintableTest.java
Once pr has been assigned a Printable instance, we can call pr.printAll();
We cannot directly call the sell() method when pr refers to a Stock, since the compiler would not associate it with a variable whose type was Printable.
Note: to compile this, use *.java; since the name of the file containing Stock and Person is PrintableThings.java, the compiler won't be able to find those classes, since it would be looking for Person.java and Stock.java.
Note: you can test the type of object actually contained in an interface reference, and typecast it back to that type.
for instance, to use the sell() method for a Stock:
If a class implements an interface, then all subclasses of it will also automatically implement the interface.
Java-Interfaces/Demos/Printable2.java
A class implementing Printable2 must define both versions of printAll.
Java-Interfaces/Demos/Printable2Test.java
Solutions/Payroll-Interfaces01/Payroll.java
The last several lines of code create an array of invoices, then use the CheckPrinter to print employees and invoices separately. It would also be possible to create an array of Payable objects, and add in the elements from both the employees and invoices arrays, but that seems like an unneccessary complication for this application.
Duration: 30 to 40 minutes.
It turns out that our hypothetical system is to be used for all payments our company makes, not just payroll checks, and things like invoices will be paid through the system as well.
Solutions/Payroll-Interfaces01/finance/Payable.java
This interface declares the public String getPayInfo() method that our employee classes already implement.
Solutions/Payroll-Interfaces01/employees/Employee.java
The class has been marked as implementing Payable. Although it would not be required, we should mark the derived classes the same way, to have more self-documenting code.
A real-world use of interfaces is for event-handling
The ActionListener interface is used for GUI events like button clicks.
A class can listen for events if it implements ActionListener.
For the class that fires the event, registering is done with the addActionListener(ActionListener) method, which receives a reference to an ActionListener object:
For the sake of completeness, when the listener interface has multiple methods, there are often abstract classes that implement most or all of the methods as do-nothing methods - so that all you need to do is extend the class and implement the methods that you choose
The Swing classes contain a component called JTable, which displays a spreadsheet-like grid. Note that:
Below are some of the methods from TableModel:
public interface TableModel
int getColumnCount()
Returns the number of columns in the model.
int getRowCount()
Returns the number of rows in the model.
String getColumnName(int columnIndex)
Returns the name of the column at columnIndex.
Class<?> getColumnClass(int columnIndex)
Returns the most specific superclass for all the cell values in the column.
Object getValueAt(int rowIndex, int columnIndex)
Returns the value for the cell at columnIndex and rowIndex.
boolean isCellEditable(int rowIndex, int columnIndex)
Returns true if the cell at rowIndex and columnIndex is editable.
void setValueAt(Object aValue, int rowIndex, int columnIndex)
Sets the value in the cell at columnIndex and rowIndex to aValue.
You can see the conversation that will take place between the controller and the model. Note that:
Java-Interfaces/Demos/TableModelExample.java
For convenience, all the classes are in one file.
The DemoTableModel class implements TableModel by extending AbstractTableModel, thus gaining implementations of several methods (like those relating to model change event listener lists), then adding the remaining methods.
The model is based on parallel arrays of student data: name, grade, and active or not- each array represents one column of data, and element 0 in each array is the same student.
The titles array holds column names.
getColumnCount returns 3, because we know that in advance.
getRowCount returns the length of one of the data arrays.
For getColumnName, we return an appropriate string from the titles array.
For getValueAt, we pick an array based on the column number, and return the element at the row index.
getColumnClass returns a class object that matches the type of data for each array.
isCellEditable returns false, and setValueAt does nothing, because our model is not editable.
We then have three possible views of the data: a Swing GUI view that uses a JTable, a console view that prints column-aligned data, and an HTML view that produces HTML code to the console (you can copy that and paste it into a file to view in a browser, like in tablemodel.html).
Since the JTable is the whole reason TableModel exists, it knows what to do with the model. The TableConsole and TableHTML view objects have to explicitly call the appropriate methods in order to display the data.
It is actually possible to have an interface that requires no methods at all! This creates what is called a marker interface.
A declaration that a class implements the interface makes it an instance of that interface, so that it can be passed as a parameter to a method expecting an instance of the interface, or as a return value from a method that declares it returns an instance of the interface.
An example from the API is Serializable
Java 5 added a new syntax element: the annotation. An annotation is a piece of descriptive data (metadata) about a class, field, or method. It is somewhat like a comment, except that individual annotations are predefined, reusable, and can have effects on either the compilation process or the use of the class once compiled. If you have used an IDE like Eclipse or NetBeans, you may have seen the @Override annotation on editor-supplied template code. This particular annotation tells the compiler that the method that immediately follows is meant to override a base class method (or a method required by an interface). If it does not (because perhaps you spelled the name incorrectly, or got the parameter list wrong), then a compiler error is issued.
Annotations provide Java with a means to achieve, at least to some extent, Aspect-Oriented Programming, or AOP. AOP recognizes cross-cutting concerns, that is, aspects of an element that cut across classes that might not be related by inheritance or implementation of an interface.
An example is a Java web service. While servlets usually extend a Java EE base class (and will always implement the Servlet interface), there is no specified base class or interface for a web service. Instead, configuration information informs the web server that a specific class is intended to be used as a web service, and the server takes steps to make that happen. Prior to annotations, that information was supplied solely by XML configuration files. With Java EE 5, annotations were provided with which a class could be internally marked as a web service.
To apply an annotation to a class or element, precede the item with the name of the annotation, prefixed with the @ symbol.
If the annotation takes parameters, supply them in parentheses, as a comma separated list of parameterName=parameterValue. If the only parameter is called value, then you can just supply the parameterValue, without specifying it by name.
Java-Interfaces/Demos/AnnotatedWebService.java
The @WebService annotation persists into compiled code. Tools that work with enterprise-level web servers (like Glassfish, JBoss, etc.), can read the annotation via reflection, and install the class as a web service, performing all the necessary tasks, such as creating a WSDL file, establishing a URL for the service, and installation it under that URL. The annotation can be parameterized with the name for the service (which defaults to the class name followed by "Service"), as well as several other items affecting the setup as a web service.
xceptions are generated when a recognized condition, usually an error condition, occurs during the execution of a method. There are a number of standard error conditions defined in Java, and you may define your own error conditions as well.
When an exception is generated, it is said to be thrown.
Java syntax includes a system for managing exceptions, by tracking the potential for each method to throw specific exceptions. Note that:
There are two ways to handle an exception:
Let's say we are writing a method called getThatInt(ResultSet rs) and we want to use the method getInt(int column) from the ResultSet passed in as a parameter:
A look at the API listing for ResultSet tells us that the getInt() method throws SQLException, so we must handle that in our code
1.Use try and catch
2.Declare that the method will throw the exception and let our caller handle it
Note that although you are required to "handle" the exception, you aren't necessarily required to do anything useful about it!
Your decision as to which approach to use should be based on where you think responsibility for handling the exception lies. In the example above, the second approach is probably better, so that the code that works more closely with the SQL handles the exception.
When an exception is thrown, an exception object is created and passed to the catch block much like a parameter to a method. Note that:
There is an API class called Exception. Note that:
So, there are several classes of exceptions you are not required to handle (shaded in the image below). Note that:
If a method is going to resolve a potential exception internally, the line of code that could generate the exception is placed inside a try block.
There is usually at least one catch block immediately after the try block. A catch block must specify what type of exception it will catch.
Java-Exceptions/Demos/ExceptionTest.java
The program will print the first result, then fail while performing the division for the second equation. Execution will jump to the catch block to print our message on the screen.
Note: ArithmeticException is one of the few you are not required to catch, but you can still catch it if you wish.
The preceding example used a RuntimeException which your code is not obligated to handle.
Most methods in the I/O classes throw IOException which is an exception you must handle.
Our KeyboardReader class has try and catch to handle this, essentially stifling the exception, since it is unlikely, if not impossible, to actually get an IOException from the keyboard.
Java-Exceptions/Demos/IOExceptionTest.java
The line marked to comment out throws IOException, but is not in a try block, so the compiler rejects it. The second read attempt is within a try block, as it should be.
It is possible that a statement might throw more than one kind of exception. You can list a sequence of catch blocks, one for each possible exception. Remember that there is an object hierarchy for exceptions. Since the first one that matches is used and the others skipped, you can put a derived class first and its base class later (you will actually get a compiler error if you list a more basic class before a derived class, as it is "unreachable code").
Java-Exceptions/Demos/MultiCatchTest.java
The code in the try block could throw NumberFormatException during the parsing, and ArithmeticException while doing the division, so we have catch blocks for those specific cases. The more generic catch block for Exception would catch other problems, like NullPointerException.
To guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try ... catch blocks.
The code in the finally block will almost always execute.
In summary, note the following:
It's possible to have a try block followed by a finally block, with no catch block. This is used to prevent an unchecked exception, or an exception the method declared it throws, from exiting the method before cleanup code can be executed.
Java-Exceptions/Demos/FinallyTest.java
import util.KeyboardReader; public class FinallyTest { public static void main(String[] args) { System.out.println("Returned value is " + go()); } public static int go() { int choice = 0; try { String name = KeyboardReader.getPromptedString("Enter your name: "); System.out.println("MENU:"); System.out.println("1 - normal execution"); System.out.println("2 - uncaught ArithmeticException"); System.out.println("3 - return from try block"); System.out.println("4 - call System.exit"); System.out.println( "5 - return 5 from finally after ArithmeticException"); System.out.println( "6 - return 6 from finally after try returns -1"); System.out.println("X - catch NumberFormatException"); choice = KeyboardReader.getPromptedInt("Enter your choice: "); if (choice == 1) System.out.println("Hello " + name); else if (choice == 2) System.out.println("1 / 0 = " + 1/0); else if (choice == 3) return 3; else if (choice == 4) System.exit(1); else if (choice == 5) System.out.println("1 / 0 = " + 1/0); else if (choice == 6) return -1; } catch (NumberFormatException e) { System.out.println("Number Format Exception occurred"); } finally { System.out.println("Goodbye from finally block"); if (choice == 5) return 5; if (choice == 6) return 6; } return 0; } }
The program shows a menu of possible execution paths you can trigger. The "Goodbye from finally block " message will always appear except from an explicit call to System.exit in the try block:
A method that generates an exception can be written to not catch it. Instead it can let it be thrown back to the method that called it.
The possibility that a method may throw an exception must be defined with the method.
Then an instance of ExceptionClassName or a class that extends it may be thrown so, stating that a method throws Exception is about as generic as you can get (stating that it throws Throwableis as generic as you can get, but not recommended). A method can throw more than one type of exception; in which case you would use a comma-separated list of exception types.
In this way, the method is now marked as throwing that type of exception, and a code that calls this method will be obligated to handle it.
When you extend a class and override a method, you cannot add exceptions to the throws list, but a base class method can list exceptions that it does not throw in the expectation that an overriding method will throw the exception. This is another example of the "inheritance cannot restrict access" principle we saw earlier.
If main() throws an exception, the JVM, which runs under Java rules, will handle the exception (by printing a stack trace and closing down the offending thread. In a single-threaded program, this will shut down the JVM).
The keyword throw is used to trigger the exception-handling process (or, "raise" the exception, as it is often termed in other languages).
That word is followed by an instance of a throwable object, i.e., an instance of a class that extends Throwable. Usually, a new instance of an appropriate exception class is created to contain information about the exception.
For example, suppose a setAge() method expects a nonnegative integer; we can have it throw an IllegalArgumentException if it receives a negative value. It makes sense for the method that calls setAge() to do something about the problem, since it is where the illegal number came from.
So, we can declare setAge() as throws IllegalArgumentException.
Duration: 5 to 10 minutes.
Our program to this point has been prone to potential bad numeric inputs when reading from the keyboard. The parsing methods all throw NumberFormatException.
We could now put each line that requests a number inside a small loop.
The loop could be controlled by a boolean variable, perhaps with a name like isInvalid and initially set to true (using the reverse approach is also a possible strategy).
Where would you put this code? In the payroll main method or in the KeyboardReader class?
As a general principle, tools shouldn't attempt to handle exceptions when the handling logic would vary depending on the code using the tool. But, it would be a tremendous burden to put each step of a program that requests a numeric input in a looped try/catch block.
Instead, we could recognize that a common approach would be to loop until the input is numeric, printing an error message each time.
We could overload the get methods in KeyboardReader to accept an error message string, so it could do the looping for us. This way a reasonable solution would be provided, but the original method would still be available if the programmer wants to customize the exception handling.
If a programmer wants a different approach, they are still free to write it in their code and use the original KeyboardReader methods .
This approach still doesn't solve the problem of limited employee types, valid department numbers, etc. Can you think of an approach that would? (Hint: interfaces are a powerful tool ...).
Solutions/Payroll-Exceptions01/util/KeyboardReader.java
Solutions/Payroll-Exceptions01/Payroll.java
The revised code uses the new overloads of the getPromptedXXX methods.
Solutions/Payroll-Exceptions01-challenge/util/IntValidator.java
This interface specifies a method that will be used to validate integers. A validator for a specific field (like department) would implement this with code to test for legal values for that field. The package contains similar interfaces for floats and doubles.
Solutions/Payroll-Exceptions01-challenge/employees/DeptValidator.java
This class validates department numbers to be from 1 - 5 inclusive. We also could create separate validators for pay rates, etc.
Solutions/Payroll-Exceptions01-challenge/util/KeyboardReader.java
If a base class method throws an exception, that behavior will also occur in any derived classes that do not override the method.
An overriding method may throw the same exception(s) that the base class method threw.
An overriding method cannot add new exceptions to the throws list. Similar to placing more strict access on the method, this would restrict the derived class object in ways that a base class reference would be unaware of.
If the derived class method does not throw the exception that the base class threw, it can either:
Retain the exception in the throws list, even though it does not throw it; this would enable subclasses to throw the exception.
Remove the exception from its throws list, thus blocking subsequent extensions from throwing that exception.
If you have a base class method that does not throw an exception, but you expect that subclasses might, you can declare the base class to throw that exception.
There are several forms of constructors defined in the base class for the exception hierarchy.
Constructor | Description |
---|---|
Throwable()
|
Constructs a new throwable with null as its detail message. |
Throwable(String message)
|
Constructs a new throwable with the specified detail message. |
Throwable(String message, Throwable cause)
|
Constructs a new throwable with the specified detail message and cause. |
Throwable(Throwable cause)
|
Constructs a new throwable with the
specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause). |
The forms involving a cause are used in situations like Servlets and Java Server Pages, where a specific exception is thrown by the JSP engine, but it may be rooted in an exception from your code.
In both cases, a method in a base class is overridden by your code since the writers of the base class did not know what specific exceptions your code might throw, and didn't want to specify something too broad like throws Exception, they settled on throws IOException, ServletException (or JSPException for Java Server Pages).
You would try and catch for your expected exceptions and repackage them inside ServletException objects if you did not want to handle them
Method | Description |
---|---|
getMessage()
|
Prints the message that was associated with the exception (many of
the exceptions that deal with outside resources pass on the message from
the outside) - for example, when you connect to a database and run a
query, that could generate an error in the database; getMessage() will
show that message. |
printStackTrace()
|
Prints to the standard error stream the trace of what function called what function, etc., leading up to the exception. There are variations of this method where you may specify a destination for the printing (note that stack trace includes the message). |
printStackTrace(PrintStream stream)
|
Same as above, but prints to the specified output stream (which could be hooked to a log file, for example). |
Also worth noting is that the Java Logging API has logging methods that will accept a Throwable parameter and make a log entry with the stack trace.
You can create your own exception class by extending an existing exception class.
You could then add any fields or methods that you wish, although often that is not necessary.
You must, however, override any constructors you wish to use: Exception(), Exception(String message), Exception(String message, Throwable cause), Exception(Throwable cause). Usually you can just call the corresponding super-constructor.
If you extend RuntimeException or one of its subclasses, your exception will be treated as a runtime exception (it will not be checked).
When a situation arises for which you would want to throw the exception, use the throw keyword with a new object from your exception class, for example:
Java-Exceptions/Demos/NewExceptionTest.java
The thrower method randomly throws a NewException, by creating and throwing a new instance of NewException.
main tries to call thrower, and catches the NewException when it occurs.
Duration: 20 to 30 minutes.
Our payroll program can now handle things like a bad numeric input for pay rate (valid format, but not sensible, like a negative number) in a more comprehensive manner. We already are checking the numeric inputs from the keyboard, but there is no guarantee that later code will remember to do this. Using an exception mechanism guarantees protection from invalid values.
In the util package, create an exception class for InvalidValueException. Note that the Java API already contains a class for this purpose, IllegalArgumentException, but it is a RuntimeException - we would like ours to be a checked exception.
In Employee (and potentially its subclasses), change the constructors that accept pay rate and the setPayRate methods to now throw that exception (a question to ask yourself - is it necessary to actually test the pay rate value anywhere other than in the Employee class setPayRate method?). You will see that the effect of throwing the exception ripples through a lot of code.
For any code that calls those constructors/methods, choose an appropriate approach to dealing with the potential exception.
The solution uses the validators from the previous challenge exercise, it will work without that feature, but feel free to add that logic into your code as well.
Solutions/Payroll-Exceptions02/util/InvalidValueException.java
Solutions/Payroll-Exceptions02/employees/Employee.java
The marking of setPayRate throws InvalidValueException ripples through the constructors, so they should be marked as well.
Solutions/Payroll-Exceptions02/employees/ExemptEmployee.java
Calling super-constructors that throw our exception requires that these constructors also be marked. The other classes, not shown, should be similarly marked.
Solutions/Payroll-Exceptions02/Payroll.java
Since we are already checking the values of the pay rate and hours, we shouldn't expect to see any exceptions thrown, so it is reasonable to put the entire block that gets the employee data and creates an employee in a try block. If we decrement the counter upon a failure, then that employee's data will be requested again.
You might want to test your logic by temporarily changing one of the test conditions you use when reading input (like hours > 0 to hours > -20), so that you can the result (keep count of how many employees you are asked to enter).
An exception may be rethrown.
When we throw an exception, it does not necessarily have to be a new object. We can reuse an existing one.
This allows us to partially process the exception and then pass it up to the method that called this one to complete processing. This is often used in servlets and JSPs to handle part of the problem (possibly just log it), but then pass the problem up to the servlet or JSP container to abort and send an error page.
The stack trace will still have the original information. The fillInStackTrace method for the exception object will replace the original information with information detailing the line on which fillInStackTrace was called as the origin of the exception.
Class properties that are object types can be initialized with a newly constructed object.
The MegaString class constructor code will run whenever a MyClass object is instantiated.
But what if the object's constructor throws an exception?
The MyClass code won't compile - you cannot put a property declaration into a try ... catch structure and there is no place to state that the property declaration throws an exception.
You can use an initializer block to handle this situation.
This is not absolutely necessary, since the initialization could be done in a constructor, where a try ... catch would be legal. But then it would need to be done in every constructor, which someone adding another constructor later might forget.
Initializers are run in the order in which they appear in the code, whether standalone initializers, or initializers in a field declaration so, in the above code:
The Random object gets created for the first field.
The MegaString gets the first generated random number.
x gets the second generated random number.
If a field is static, and is populated with a newly constructed object, that object's constructor code will run when the class loads. In our example, if we make the MegaString property static, its constructor will run when the class loads.
Again, this won't compile, but now there is no way even to defer the issue to the constructors, since the element is static.
You can use a static initializer block to handle this problem.
Again, the initializers are run in the order in which they appear in the code, when the class is loaded.
Java 1.4 added the concept of assertions, code lines that test that a presumed state actually exists
-If the state is not as presumed, then an AssertionError will be thrown.
-Assertions are not intended for testing values that could be expected; they are intended to be used when it is believed that a state exists, but we are not absolutely sure we have covered all the possible avenues that affect the state.
To use an assertion in code:
The optional messageExpression will be converted to a String and passed as the message to the AssertionError constructor, so it cannot be a call to a function declared as void.
For example, perhaps we are using a third-party function that is specified to return a double value between 0 and 1, but we'd like to guarantee that is the case.
Java-Exceptions/Demos/AssertionTest.java
If the function returns a value outside of our expected range, like 5.0, the assertion condition will evaluate to false, so an AssertionError will be thrown with the message "thirdPartyFunction value 5.0 out of range."
Note: in a 1.4 compiler, you must inform the compiler that you are compiling your code under Java 1.4 rules to use assertions, using the -source 1.4 command line switch:
In Java 5 and later this is not necessary.
Assertions are used for debugging a program, and usually not enabled for production runs. You must specifically enable assertions when you run the program, by using the command line switch -enableassertions (or -ea).
Oracle's "rules" for assertions emphasize that they will be disabled most of the time:
-They should not be used for checking the values passed into public methods, since that check will disappear if assertions are not enabled.
-The assertion code shouldn't have any side effects required for normal operation.
The Java Collections API is a set of classes and interfaces designed to store multiple objects.
There are a variety of classes that store objects in different ways:
The basic distinctions are defined in several interfaces in the java.util package:
In addition to the List, Set, and Map categories, there are also several inferences you can make from some of the collection class names:
Several additional interfaces are used to define useful helper classes:
The following diagrams show some of the classes and interfaces that are available:
The following are several examples of collection classes:
Vector stores objects in a linear list, in order of addition. Some additional notes on Vector are:
ArrayList, like Vector, stores objects in a linear list, in order of addition. Methods are not synchronized, so that the class is not inherently thread-safe (but there are now tools in the Collections API to provide a thread-safe wrapper for any collection, which is why Vector has fallen into disuse).
TreeSet stores objects in a linear sequence, sorted by a comparison, with no duplicates. TreeSet also:
Note that there is no tree list collection, because the concepts of insertion order and natural order are incompatible. Since sets reject duplicates, any comparison algorithm should include a guaranteed tiebreaker (for example, to store employees in last name, first name order: to allow for two Joe Smiths, we should include the employee id as the final level of comparison).
TreeMap stores objects in a Map, where any subcollection or iterator obtained will be sorted by the key values. Note that:
Hashtable stores objects in a Map. Note also that:
HashSet uses hashing strategy to manage a Set. Note also that:
Iterators provide a standard way to loop through all items in a collection, regardless of the type of collection. Note that:
Some collections allow you to remove an element through the iterator. The remove method is marked in the docs as optional by the definition of interfaces it has to be present, but the optional status indicates that it may be implemented to merely throw an UnsupportedOperationException.
In any case, if the collection is modified from a route other than via the iterator (perhaps by using remove(int index), or even just using the add method), a ConcurrentModificationException is thrown.
The Enumeration class is an older approach to this concept; it has methods hasMoreElements() and nextElement().
Java-Collections/Demos/CollectionsTest.java
This program demonstrates the three types of collections. As is commonly done, the variables are typed as the most basic interfaces (List, Set, and Map).
We attempt to add the same sequence of values to each: 1, 4, 3, 2, and 3; then:
In the output, first note the true and false values resulting from attempting to add the values to the Set. Also note in the Map listing, which value associated with the key 3 is retained.
An iterator is then obtained for each and the series printed out (for the Map, we try two different approaches: iterating through the keys and retrieving the associated entries, and iterating directly through the set of entries).
Note the order of the values for each, and also which of the duplicates was kept or not. Note also that:
Both the equals(Object) method and hashCode() methods are used by methods in the Collections API. Note also that:
Oracle specifies that the behavior of hashCode should be "consistent with equals", meaning that two objects that compare as equal should return the same hash code. The reverse is not required; two objects with the same hash code might be unequal, since hash codes provide "bins" for storing objects.
This is critical when writing collectible classes. For example, the implementation of HashSet, which should reject duplicate entries, compares a candidate entry's hashcode against that of each object currently in the collection. It will only call equals if it finds a matching hash code. If no hash code matches, it assumes that the candidate object must not match any already present in the set.
Sorted collections can sort elements in two ways:
As an example: TreeSet uses a tree structure to store items. Tthe tree part of the name is just for identifying the algorithm used for storage; you cannot make use of any of the node-related behaviors from the outside. There are several forms of constructors, most notably:
Java-Collections/Demos/UseComparable.java
Since String implements Comparable, the names will appear in alphabetical order when we iterate through the set.
The Arrays class provides useful methods for working with arrays, some of which will return a collection backed by the array (the Collections classes contain useful methods for working with collections, some of which perform the reverse operation).
Classes that implement the Comparable interface may be stored in ordered collections. They must have a int compareTo(Object other) method to implement the interface. Note the following:
Classes that implement the Comparator interface may be also used with ordered collections, but the collection must be constructed with an explicit reference to an instance of the Comparator. The Comparator is a separate class that will compare two instances of your class to determine the ordering.
The interface specifies int compare(Object a, Object b). The function returns a negative value for an object considered less than the object b, a positive value for b considered greater than a, and 0 if they are equal.
It is still important that the results of the compareTo method match with the results of the objects' equals method. Note that you should usually implement this method to avoid "ties" for objects that would not be considered equal. For example, for two different employees who coincidentally have the same name would be returned in an indeterminate order.
Java-Collections/Demos/UseComparator.java
The compare method of our comparator makes use of the existing compareTo method in String and simply inverts the result. Note that the objects being compared are tested to make sure both are String objects. If the test fails, the method throws a ClassCastException.
Java-Collections/Demos/UseComparableAndComparator.java
Since all the collections store are references, it will not use a lot of memory to store the same references in different collections. This creates an analog to a set of table indexes in a database
Java 5.0 added the concept of Generics, which allow data types to be parameterized for a class
In earlier versions of Java, the collection methods to store objects all received a parameter whose type was Object. Therefore, the methods to retrieve elements were typed to return Object. To use a retrieved element, you had to typecast the returned object back to whatever it actually was (and somehow you had to know what it actually was).
The collections in Java 5.0 use a special, new syntax where the type of object is stated in angle brackets after the collection class name.
Instead of ArrayList, there is now ArrayList<E>, where the E can be replaced by any type. Within the class, method parameters and return values can be parameterized with the same type.
For example, an ArrayList of String objects would be ArrayList<String>.
Java-Collections/Demos/GenericCollectionsTest.java
As you can see, the objects retrieved from the ArrayList are already typed as being String objects. Note the following:
A type parameter may set bounds on the type used, by setting an upper limit (in inheritance diagram terms) on the class used. The extends keyword is used to mean that the class must either be an instance of the specified boundary class, or extend it, or, if it is an interface, implement it:
In the first case, the class may be parameterized with Employee, or any class that extends Employee. In the second, the class may be parameterized with Payable or any type that implements the Payable interface.
When extending a generic class or implementing a generic interface, you can maintain the generic type, as in public class ArrayList<T> implements List<T>. In this case, types are still stated in terms of T.
You can lock in the generic type: public class EmployeeList extends ArrayList<Employee> or public class StringList implements java.util.List<String>. In these cases, methods would use the fixed type. For example, if you overrode add(E) in ArrayList<E> in the above EmployeeList, it would be add(Employee).
Methods may be generic, whether or not they are in a generic class. The syntax is somewhat ugly, since it requires listing the type variable before the return type and requires that at least one parameter to the method be of the generic type (that is how the compiler knows what the type is).
The above method is parameterized with type T. The type for T is established by whatever type of array is passed in; if we pass in a String array, then T is String. The method will then randomly pick one to return.
The type may be bounded with extends.
In the documentation for a collections class, you may see some strange type parameters for methods or constructors, such as:
he question mark is a wildcard, indicating that the actual type is unknown. But, we at least know limits in the second two cases. The extends keyword in this usage actually means "is, extends, or implements" (which is the same criteria the instanceof operator applies). The super keyword means essentially the opposite: that the type parameter of the other class is, or is more basic than, this class's type. The usages with extends and super are called bounded wildcards.
This syntax only occurs when the variable is itself a generic class. The wildcards then state how that class's generic type relates to this class's type.
Why this is necessary leads down a long and winding path. To start, consider the following:
This seems reasonable at first glance, but then consider if this line followed:
<textarea>exEmps.add(new ContractEmployee());</textarea>Perfectly legal as far as the compiler is concerned, since ContractEmploye fits within the Employee type that the exEmps variable requires, but now we have a contract employee in a list instance that is supposed to hold only exempt employees. So, an instance of a class parameterized with a derived class is not an instance of that class parameterized with the base class, even though individual instances of the derived class can be used in the base-parameterized generic class; e.g., our List<Employee> can add individual exempt employees.
For the first wildcard case above, public boolean containsAll(Collection<?> c), it does no harm for us to see if our collection contains all the elements of some other collection that may contain an entirely unrelated type (but few, if any, of the items would compare as equal). Note that the contains method accepts an Object parameter, not an E, for this same reason.
The extends term in public boolean addAll(Collection<? extends E> c)means that the unknown class is, extends, or implements the listed type. For instance, we could add all the elements of an ArrayList<ExemptEmployee> to an ArrayList<Employee>. That makes sense, since we could add individual exempt employees to a basic employee collection. But, since we don't actually know what the parameterized type of the incoming collection is (it is the ? class), we cannot call any methods on that object that depend on its parameterized type. So we can't add to that collection; we can only read from it.
The super term is seen less often; it means that the parameterized type of the incoming collection must be of the same type or a more basic type. The TreeSet constructor can accept a Comparator for its actual type, or any type more basic (e.g., a Comparator<Object> can be used for a TreeSet of anything, since its compare method will accept any type of data). It is, however, likely that many "acceptable" comparators will end up throwing a ClassCastException at runtime if they can't actually compare the types involved. So, for example, if we had a Comparator<Employee> class that compared employee ids, we might still wish to use it in a TreeSet<ExemptEmployee>, where it would be perfectly valid (in fact, it would be an annoyance to have to write a special comparator for every employee type, if all the comparators did was compare the ids).
Duration: 15 to 25 minutes.
We can modify our payroll application to use generic lists instead of arrays for our employees, invoices, and payables.
The parameter is a "dummy" array used to tell the generic method what type of array to create. Note in the Collection documentation that this method is typed with T rather than the E used in the rest of the class. This method has its own local type, which is determined by the type of the array passed in.
Solutions/Payroll-Collections01/Payroll.java
Inner classes, also known as nested classes are classes defined within another class.
They may be defined as public, protected, private, or with package access.
They may only be used "in the context" of the containingclass (outer class, or enclosing class), unless they are marked as static.
Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is).
Outer class code has free access to all elements in any of its inner classes, no matter what their access term.
An inner class compiles to its own class file, separate from that of the outer class (the name of the file will be OuterClassName$InnerClassName.class, although within your code the name of the class will be OuterClassName.InnerClassName); you cannot use the dollar sign version of the name in your code.
An inner class occupies its own memory block, separate from the outer class memory block.
An inner class may extend one class, which might be unrelated to the class the outer class extends.
An inner class can implement one of more interfaces, and, if treated as an instance of one of its interfaces, external code may have no knowledge that the object actually comes from an inner class.
The definition of the inner class is always available for the outer class to use. Note that:
Java-InnerClasses/Demos/MyOuter.java
This is a simple example of an inner class
The connection between the two classes is handled automatically.
The following diagram maps out the memory used by the example.
An inner class instance may be directly instantiated from code in the enclosing class, without any special syntax:
Such an instance is automatically associated with the enclosing class instance that instantiated it.
Java-InnerClasses/Demos/Inner1.java
This code simply creates an instance of the outer class, MyOuter.
The MyOuter constructor creates an instance of MyInner as mentioned earlier.
If the access term for the inner class definition is public (or the element is accessible at package access or protected level to the other class), then other classes can hold references to one or more of these inner class objects
For code that is not in the outer class, a reference to a static or non-static inner class object must use the outer class name, a dot, then the inner class name:
If the inner class has an accessible constructor, you can you instantiate one from outside of the enclosing class, although the syntax is ugly, and there is rarely a need for this capability.
If inner class code needs a reference to the outer class instance that it is attached to, use the name of the outer class, a dot, and this. Remember that if there is no name conflict, there is no need for any special syntax.
For code in MyInner to obtain a reference to its MyOuter:
An inner class may be marked as static.
A static inner class my be instantiated without an instance of the outer class. Note that:
To create a static inner class object from outside the enclosing class, you must still reference the outer class name
An inner class may not have static members unless the inner class is itself marked as static.
Java-InnerClasses/Demos/StaticInnerTest.java
We have a class StaticOuter that declares a static inner class StaticInner. StaticOuter has a method that will create instances of StaticInner. But, StaticInner also has a public constructor. Note that:
It is easiest if inner class objects can always be instantiated from the enclosing class object. You can create a factory method to accomplish this.
Java-InnerClasses/Demos/FactoryInnerOuter.java
For convenience, this file contains both the main class and the FactoryOuter class (with package access). Note that:
This is exactly the sort of thing that happens when you obtain an iterator from a collection class. In order to successfully navigate what is most likely a complex internal structure, the object will need access to the private elements. So, an inner class is used, but all you need to know about the object is that it implements the Iterator interface.
Java-InnerClasses/Demos/PayrollInnerClass/employees/Employee.java
Payment is an inner class to a simplified Employee, and, as an inner class, has free access to all private elements of Employee. Unlike a standalone payment class, this class can retrieve the employee name from the outer class instance. We also use this access to defer updating the year-to-date amounts until the payment is posted, via the process method.
To get this degree of interaction between two separate classes would be difficult, since it would mean that either:
Note that we have also separated the concepts of creating a payment from actually posting it. This gives us better control over transactions - note that a payment cannot be processed twice.
Java-InnerClasses/Demos/PayrollInnerClass/Payroll.java
We have only one employee for simplicity. As we loop for each month, a payment is created for each. We try to process the June payment twice (remember that the array is zero-based, so January is month 0; this matches the behavior of the java.util.Date class) . The second attempt to process the payment should throw an exception which our catch block handles.
We retrieve and print the year-to-date pay each time we process a payment.
At the end, we have the Employee object print the entire payment history created by our calls to the inner class' process method..
Java-InnerClasses/Demos/PayrollInnerClassInterface/employees/Employee.java
This code goes one step further to create a Payment inner class that implements the Payable interface.
Java-InnerClasses/Demos/PayrollInnerClassInterface/Payroll.java
The only difference here is that we declare the variable holding the payments as Payable, hiding the fact that it is an inner class.
In Java 5, the enum element was introduced. Long sought by the C/C++ part of the Java community, enums provide a set of predefined constants for indicating a small set of mutually exclusive values or states.
Why Another Syntax Element for a Set of Constants?
The other approaches all have some sort of flaw, particularly as involves type-safety.
Java enums provide a type-safe way of creating a set of constants, since they are defined as a class, and therefore are a type of data.
A disadvantage to this approach is that the set of values is written into the code. For sets of values that may change, this would require recompiling the code, and would invalidate any serialized instances of the enum class. For example, if we offered a choice of benefits plans to our employees, the set of available plans would not be a good candidate for an enum, since it is likely that the set of available plans would eventually change.
To create a simple enum class:
One instance of the enum class will be created to represent each item you listed, available as a static field of the class, using the name you supplied which will be the individual values. Each instance can provide an integral value, with sequential indexes starting at 0, in the order that the names were defined - there is no way to change this, but there is a route to get specific values which have a complex internal state.
There will be three instances of the class created, Alignment.left, Alignment.right, and Alignment.center. An Alignment type variable can hold any of these three values.
Enums automatically extend the Enum class from the API, and they inherit several useful methods:
There are also several other methods that will be present, although they are not listed in the documentation for Enum.
The reason for the last two methods not being in the documentation has to do with generics and type erasure - the methods cannot be declared in the Enum base class in a way that would allow the use of the as-yet unknown subclass.
Individual values from the set may be accessed as static elements of the enum class. The JVM will instantiate exactly one instance of each value from the set. Therefore, they can be used in comparisons with ==, or in switch statements (using the equals method is preferred to ==, since it will serve as a reminder that you are dealing with true objects, not integers).
Although enums may be top-level classes, they are often created as inner classes, as in the following example, where the concept of the enum is an integral part of a new BookWithEnum class. When used as an inner class, they are automatically static, so that an instance of an inner enum does not have access to instance elements of the enclosing class.
Java-InnerClasses/Demos/BookWithEnum.java
The Category enum is defined as an inner class to BookWithEnum. The full names of the complete set of values are: BookWithEnum.Category.required, BookWithEnum.Category.supplemental, BookWithEnum.Category.optional, and BookWithEnum.Category.unknown. From within the BookWithEnum class, they may be accessed as: Category.required, Category.supplemental, Category.optional, and Category.unknown.
We set the category for a book constructed without one as Category.unknown, and provide methods to get the value, and to set it with either an enum object or from a string.
Note that enums may be used in switch statements - for the cases you use only the short name for the value.
Enums are more than just a set of integer constants. They are actually a set of unique object instances, and, as objects, can have multiple fields. So, an enum is a class with a fixed number of possible instances, each with it's own unique state, and each of the possible instances is created automatically and stored as static field under the same name. (In design pattern terms, an enum is a Flyweight - a class where only a limited number of fixed states exist.)
To create a more complex enum class:
If you don't understand this, don't worry. Just skip it and move on.
Python is an interpreted programming language. For those who don't know, a programming language is what you write down to tell a computer what to do. However, the computer doesn't read the language directly - there are hundreds of programming languages, and it couldn't understand them all. So, when someone writes a program, they will write it in their language of choice, and then compile it - that is, turn it in to lots of 0s and 1s, that the computer can easily and quickly understand. A windows program that you buy is already compiled for windows - if you opened the program file up, you'd just get a mass of weird characters and rectangles. Give it a go - find a small windows program, and open it up in notepad or wordpad. See what garbled mess you get.
But that windows program is compiled for windows - no other machine can run that program, unless it has windows. What Python is, is a language which is never actually compiled in full - instead, an interpreter turns each line of code into 0s and 1s that your computer can understand this. And it is done on the fly - it compiles the bits of the program you are using as you are using them. If you were to quit the program and come back another day, it would compile the bits you are using, as you are using them, again. Seems a waste of time? Maybe, but the fact is that when you come back another day, you might be using a Windows instead of a Mac. You might send the program to a friend, who uses another type of computer. Or you might post your program on the internet, where everyone using all different types of systems might download it. That is the wonder of an interpreted programming language - it is like a language that EVERYONE can understand.
Remember that garbled mess that you got when opening a program in notepad? Not much use to anyone, apart from the computer. And there is no reliable (or legal) way of turning that program back in to a programming language that you or I could understand.
The same is with Civ3 AI - it is compiled into a garbled mess. Nobody can understand it, and most of all, nobody can change it. Only Firaxis can change the AI, and they can't share the logic behind it with anyone.
With cIV, they decided to change that - they would leave the AI uncompiled in the language of Python, and have it compiled on-the-fly by an interpreter. This is so that Joe modder can look at the AI and change it, yet when it is neede to be used, the python interpreter turns it into 0s and 1s for your computer to understand. And it isn't permanently compiled into a garbled mess - you are still left with python code, that you can read, understand, and MODIFY!!!!!
OK! Hopefully now everything is good! Now, to test if that just worked, type this in your DOS window:
python -V
If you forgot a CAPITAL V, you will accidently load python in verbose mode. Give it a go, see what happens. Just press CTRL-D to quit, or type 'quit' for quit instructions.
Good work! Lesson 1 over! Next lesson, we learn our way around Python Interactive Mode, and write simple one-line pieces of code. I'll also have a lesson plan drawn up by then, so you can see where you are going. If any of our more experienced members have suggestions for the lesson plan, tell me!
OK! We have python installed, now what? Well, we program! And it is that simple (at least for now). Python makes it easy to run single lines of code - one-liner programs. Lets give it a go.
Go to the start menu, find Python, and run the program labelled 'IDLE' (Stands for Integrated Development Environment.
Now you are in the IDLE environment. This is the place you will be spending most time in. Here you can open a new window to write a program, or you can simply mess around with single lines of code, which is what we are going to do. Type the following and press enter: (don't type >>> as it should already be there)
>>> print "Hello, World!"
What happened? You just created a program, that prints the words 'Hello, World'. The IDLE environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, and then test to see if a certain line will work. That will come in a later lesson, though.
Now try typing the stuff in bold. You should get the output shown in blue. I've given explainations in brackets.
>>> 1 + 1 2 >>> 20+80 100 >>> 18294+449566 467860 (These are additions) >>> 6-5 1 (Subtraction) >>> 2*5 10 (Multiply, rabbits!) >>> 5**2 25 (Exponentials e.g. this one is 5 squared) >>> print "1 + 2 is an addition" 1 + 2 is an addition (the print statement, which writes something onscreen) >>> print "one kilobyte is 2^10 bytes, or", 2**10, "bytes" one kilobyte is 2^10 bytes, or 1024 bytes (you can print sums and variables in a sentence. The commas seperating each section are a way of seperating clearly different things that you are printing) >>> 21/3 7 >>> 23/3 7 >>> 23.0/3.0 7.6666... (division, 2nd time ignoring remainder/decimals, 3rd time including decimals) >>> 23%3 2 >>> 49%10 9 (the remainder from a division)
As you see, there is the code, then the result of that code. I then explain them in brackets. These are the basic commands of python, and what they do. Here is a table to clarify them (because tables look cool, and make you feel smarter ;) ):
Remember that thing called order of operation that they taught in maths? Well, it applies in python, too. Here it is, if you need reminding:
Here are some examples that you might want to try, if you're rusty on this:
n the first example, the computer calculates 2 * 3 first, then adds 1 to it. This is because multiplication has the higher priority (at 3) and addition is below that (at lowly 4).
In the second example, the computer calculates 1 + 2 first, then multiplies it by 3. This is because parentheses (brackets, like the ones that are surrounding this interluding text ;) ) have the higher priority (at 1) and addition comes in later than that.
Also remember that the math is calculated from left to right, UNLESS you put in parentheses. The innermost parentheses are calculated first. Watch these examples:
In the first example, 4 -40 is calculated,then - 3 is done.
In the second example, 40 - 3 is calculated, then it is subtracted from 4.
The final thing you'll need to know to move on to multi-line programs is the comment. Type the following (and yes, the output is shown):
A comment is a piece of code that is not run. In python, you make something a comment by putting a hash in front of it. A hash comments everything after it in the line, and nothing before it. So you could type this:
Comments are important for adding necessary information for another programmer to read, but not the computer. For example, an explanation of a section of code, saying what it does, or what is wrong with it. You can also comment bits of code by putting a # in front of it - if you don't want it to compile, but cant delete it because you might need it later.
There you go! Lesson 2 Completed. That was even shorter than lesson 1! Next lesson, we make programs with many lines of code, and save them, so we can actually send them to people. That's right, you don't have to retype every program you run! What an amazing innovation!
Well, we can make one-liner programs. So What? You want to send programs to other people, so that they can use them, without knowing how to write them.
Writing programs in python to a file is VERY easy. Python programs are simply text documents - you can open them up in notepad, and have a look at them, just like that. So, go and open notepad. Type the following:
Code Example 1 - mary.pyKeep this exactly the same, down to where the commas are placed. Save the file as 'mary.py' - and make sure notepad doesn't add .txt to the end of the filename - You will have to tell it to save as any file, to avoid this. Turn off 'Hide known file extensions' in Windows Explorer, if it makes it easier.
Now, open up the Python IDLE program (should be in your start menu). Click 'File > Open' and find mary.py and open it. if you cant find mary.py, set the open dialogue to 'Files of type: All Files (*)'. A new window will open, showing the program you just wrote. To run your program, click 'Run>Run Module' (or just press F5). Your program will now run in the main Python screen (Titled *Python Shell*) and will look like this:
Code Example 2 - mary.py outputYou can also use IDLE to create Python programs, like what you did in notepad. Simply click 'File > New'. We will be writing all of our programs now in the python IDLE program - the notepad thing is just a demonstration to tell you that a .py file is just a simple text file, which anyone can see.
There are a couple of things to notice here:
Now lets start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables. Open up IDLE, click 'File>New Window' - a new window now appears, and it is easy to type in programs. Type the following (or just copy and paste - just read very carefully, and compare the code to the output that the program will make):
Code Example 3 - VariablesAs you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:
Code Example 4 - StringsGood Morning
Good Morning to you too!
As you see, the variables above were holding text. Variable names can also be longer than one letter - here, we had word1, word2, and word3. As you can also see, strings can be added together to make longer words or sentences. However, it doesn't add spaces in between the words - hence me putting in the " " things (there is one space between those).
Well done! We now understand longer programs, and know the use of variables. Next lesson, we look at functions, what they are, and how to use them.
Our final lesson before we get into interacting with human input. Can't wait, can you?)
Just imagine you needed a program to do something 20 times. What would you do? You could copy and paste the code 20 times, and have a virtually unreadable program, not to mention slow and pointless. Or, you could tell the computer to repeat a bit of code between point A and point B, until the time comes that you need it to stop. Such a thing is called a loop.
The following are examples of a type of loop, called the 'while' loop:
Code Example 1 - The while loopHow does this program work? Lets go through it in English:
Code Example 2 - plain-language while loopSo in short, try to think of it that way when you write 'while' loops. This is how you write them, by the way (and a couple of examples:
Code Example 4 - while loop form, and exampleRemember, to make a program, you open IDLE, click File > New Window, type your program in the new window, then press F5 to run.
What do you type in the area marked {conditions that the loop continues}? The answer is a boolean expression.
What? A forgotten concept for the non-math people here. Never mind, boolean expression just means a question that can be answered with a TRUE or FALSE response. For example, if you wanted to say your age is the same as the person next to you, you would type:
My age == the age of the person next to me
And the statement would be TRUE. If you were younger than the person opposite, you'd say:
My age < the age of the person opposite me
And the statement would be TRUE. If, however, you were to say the following, and the person
opposite of you was younger than you:
My age < the age of the person opposite me
The statement would be FALSE - the truth is that it is the other way around. This is how a loop thinks - if the expression is true, keep looping. If it is false, don't loop. With this in mind, lets have a look at the operators (symbols that represent an action) that are involved in boolean expressions:
Dont get '=' and '==' mixed up - the '=' operator makes what is on the left equal to what is on the right. the '==' operator says whether the thing on the left is the same as what is on the right, and returns true or false.
OK! We've (hopefully) covered 'while' loops. Now let's look at something a little different - conditionals.
Conditionals are where a section of code is only run if certain conditions are met. This is similar to the 'while' loop you just wrote, which only runs when x doesn't equal 0. However, Conditionals are only run once. The most common conditional in any program language, is the 'if' statement. Here is how it works:
Example 2 there looks tricky. But all we have done is run an 'if' statement every time the 'while' loop runs. Remember that the % just means the remainder from a division - just checking that there is nothing left over if the number is divided by two - showing it is even. If it is even, it prints what 'n' is.
'else' and 'elif' - When it Ain't True
There are many ways you can use the 'if' statement, do deal with situations where your boolean expression ends up FALSE. They are 'else' and 'elif'.
'else' simply tells the computer what to do if the conditions of 'if' arent met. For example, read the following:
'a' is not greater than five, therefore what is under 'else' is done.
'elif' is just a shortened way of saying 'else if'. When the 'if' statement fails to be true, 'elif' will do what is under it IF the conditions are met. For example:
The 'if' statement, along with 'else' and 'elif' follow this form:
Code Example 8 - the complete if syntaxOne of the most important points to remember is that you MUST have a colon : at the end of every line with an 'if', 'elif', 'else' or 'while' in it. I forgot that, and as a result a stack of people got stumped at this lesson (sorry ;) ).
One other point is that the code to be executed if the conditions are met, MUST BE INDENTED. That means that if you want to loop the next five lines with a 'while' loop, you must put a set number of spaces at the beginning of each of the next five lines. This is good programming practice in any language, but python requires that you do it. Here is an example of both of the above points:
Code Example 9 - IndentationNotice the three levels of indents there:
There is another loop, called the 'for' loop, but we will cover that in a later lesson, after we have learnt about lists.
And that is lesson 4! In lesson 5, we get into user interaction, and writing programs that actually serve a purpose. Can't wait!
Last lesson I said that we would delve into purposefull programming. That involves user input, and user input requires a thing called functions.
What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example getting the user to type something in.
Python has lots of pre-made functions, that you can use right now, simply by 'calling' them. 'Calling' a function involves you giving a function input, and it will return a value (like a variable would) as output. Don't understand? Here is the general form that calling a function takes:
Code Example 1 - How to call a functionfunction_name(parameters)
See? Easy.
Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what is does?
Well, in effect, when a computer runs a function, it doesn't actually see the function name, but the result of what the function did. Variables do the exact same thing - the computer doesn't see the variable name, it sees the value that the variable holds. Lets call this program that multiplied any number by five, multiply(). You put the number you want multiplied in the brackets. So if you typed this:
a = multiply(70)
The computer would actually see this:
Code Example 3 - What the computer seesa = 350
note: don't bother typing in this code - multiply() isn't a real function, unless you create it.
The function ran itself, then returned a number to the main program, based on what parameters it was given.
Now let's try this with a real function, and see what it does. The function is called raw_input, and asks the user to type in something. It then turns it into a string of text. Try the code below:
Say in the above program, you typed in 'hello' when it asked you to type something in. To the computer, this program would look like this:
Code Example 5 - What the computer seesRemember, a variable is just a stored value. To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running.
Lets write another program, that will act as a calculator. This time it will do something more adventerous than what we have done before. There will be a menu, that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. Only problem - the raw_input function returns what you type in as a string - we want the number 1, not the letter 1 (and yes, in python, there is a difference.).
Luckily, somebody wrote the function input, which returns what you typed in, to the main program - but this time, it puts it in as a number. If you type an integer (a whole number), what comes out of input is an integer. And if you put that integer into a variable, the variable will be an integer-type variable, which means you can add and subtract, etc.
Now, lets design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!) you tell it the program should still run.
We want it to do an option in the menu if you type in that number. That involves you typing in a number (a.k.a input) and an if loop.
Lets write it out in understandable English first:
Lets put this in something that python can understand:
Code Example 7 - Python verion of menuWow! That is an impressive program! Paste it into python IDLE, save it as 'calculator.py' and run it. Play around with it - try all options, entering in integers (numbers without decimal points), and numbers with stuff after the decimal point (known in programming as a floating point). Try typing in text, and see how the program chucks a minor fit, and stops running (That can be dealt with, using error handling, which we can address later.)
Well, it is all well and good that you can use other people's functions, but what if you want to write your own functions, to save time, and maybe use them in other programs? This is where the 'def' operator comes in. (An operator is just something that tells python what to do, e.g. the '+' operator tells python to add things, the 'if' operator tells python to do something if conditions are
met.)
This is how the 'def' operator works:
function_name is the name of the function. You write the code that is in the function below that line, and have it indented. (We will worry about parameter_1 and parameter_2 later, for now imagine there is nothing between the parentheses.
Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value, that the function returns? Here's the quote:
Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value, that the function returns? Here's the quote:
To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running.
A function is like a miniture program that some parameters are given to - it then runs itself, and then returns a value. Your main program sees only the returned value. If that function flew to the moon and back, and then at the end had:
return "Hello"
then all your program would see is the string "hello", where the name of the function was. It would have no idea what else the program did.
Because it is a seperate program, a function doesn't see any of the variables that are in your main program, and your main program doesn't see any of the variables that are in a function. For example, here is a function that prints the words "hello" onscreen, and then returns the number '1234' to the main program:
Think about the last line of code above. What did it do? Type in the program (you can skip the comments), and see what it does. The output looks like this:
Code Example 11 - the outputSo what happened?
That accounts for everything that happened. remember, that the main program had NO IDEA that the words "hello" were printed onscreen. All it saw was '1234', and printed that onscreen.
There is one more thing we will cover in this (monsterously huge) lesson - passing parameters to a function. Think back to how we defined functions:
Code Example 12 - Defining functions with parametersWhere parameter_1 and parameter_2 are (between the parentheses), you put the names of variables that you want to put the parameters into. Put as many as you need, just have them seperated by commas. When you run a function, the first value you put inside the parentheses would go into the variable where parameter_1 is. The second one (after the first comma) would go to the variable where parameter_2 is. This goes on for however many parameters there are in the function (from zero, to the sky) For example:
Code Example 13 - how parameters workWhen you run the function above, you would type in something like this: funnyfunction("meat","eater","man"). The first value (that is, "meat") would be put into the variable called first_word. The second value inside the brackets (that is, "eater") would be put into the variable called second_word, and so on. This is how values are passed from the main program to functions - inside the parentheses, after the function name.
Think back to that calculator program. Did it look a bit messy to you? I think it did, so lets re-write it, with functions.
To design - First we will define all the functions we are going to use with the 'def' operator (still remember what an operator is ;) ). Then we will have the main program, with all that messy code replaced with nice, neat functions. This will make it so much easier to look at again in the future.
The initial program had 34 lines of code. The new one actually had 35 lines of code! It is a little longer, but if you look at it the right way, it is actually simpler.
You defined all your functions at the top. This really isn't part of your main program - they are just lots of little programs, that you will call upon later. You could even re-use these in another program if you needed them, and didn't want to tell the computer how to add and subtract again.
If you look at the main part of the program (between the line 'loop = 1' and 'print "Thankyou for..."'), it is only 15 lines of code. That means that if you wanted to write this program differently, you would only have to write 15 or so lines, as opposed to the 34 lines you would normally have to without functions.
Your brain still hurting from the last lesson? Never worry, this one will require a little less thought. We're going back to something simple - variables - but a little more in depth.
Think about it - variables store one bit of information. They may regurgitate (just not on the carpet...) that information at any point, and their bit of information can be changed at any time. Variables are great at what they do - storing a piece of information that may change over time.
But what if you need to store a long list of information, which doesn't change over time? Say, for example, the names of the months of the year. Or maybe a long list of information, that does change over time? Say, for example, the names of all your cats. You might get new cats, some may die, some may become your dinner (we should trade recipies!). What about a phone book? For that you need to do a bit of referencing - you would have a list of names, and attached to each of those names, a phone number. How would you do that?
For these three problems, Python uses three different solutions - Tuples, lists, and dictionaries:
Tuples are pretty easy to make. You give your tuple a name, then after that the list of values it will carry. For example, the months of the year:
Code Example 1 - creating a tuplePython then organises those values in a handy, numbered index - starting from zero, in the order that you entered them in. It would be organised like this:
Table 1 - tuple indiciesAnd that is tuples! Really easy...
Lists are extremely similar to tuples. Lists are modifiable (or 'mutable', as a programmer may say), so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.
Lists are defined very similarly to tuples. Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, you would do this:
As you see, the code is exactly the same as a tuple, EXCEPT that all the values are put between square brackets, not parentheses. Again, you don't have to have spaces after the comma.
You recall values from lists exactly the same as you do with tuples. For example, to print the name of your 3rd cat you would do this:
print cats[2]
You can also recall a range of examples, like above, for example - cats[0:2] would recall your 1st and 2nd cats.
Where lists come into their own is how they can be modified. To add a value to a list, you use the 'append()' function. Let's say you got a new cat called Catherine. To add her to the list you'd do this:
That's a little weird, isn't it? I'll explain. That function is in a funny spot - after a period (the '.' kind of period, not otherwise), after the list name. You'll get to see those things more in a later lesson. For the meanwhile, this is the form of the function that adds a new value to a list:
Code Example 5 - Using the append functionClears things up? Good!
Now to a sad situation - Snappy was shot by a neighbour, and eaten for their dinner (good on 'em!). You need to remove him (or her) from the list. Removing that sorry cat is an easy task, thankfully, so you have to wallow in sadness for as short a time as possible:
You've just removed the 2nd cat in your list - poor old Snappy.
And with that morbid message, lets move on to...
Ok, so there is more to life than the names of your cats. You need to call your sister, mother, son, the fruit man, and anyone else who needs to know that their favourite cat is dead. For that you need a telephone book.
Now, the lists we've used above aren't really suitable for a telephone book. You need to know a number based on someone's name - not the other way around, like what we did with the cats. In the examples of months and cats, we gave the computer a number, and it gave us a name. This time we want to give the computer a name, and it give us a number. For this we need
Dictionaries.
So how do we make a dictionary? Put away your binding equipment, it isn't that advanced.
Remember, dictionaries have keys, and values. In a phone book, you have people's names, then their numbers. See a similarity?
When you initially create a dictionary, it is very much like making a tuple or list. Tuples have ( and ) things, lists have [ and ] things. Guess what! dictionaries have { and } things - curly braces. Here is an example below, showing a dictionary with four phone numbers in it
the program would then print Lewis Lame's number onscreen. Notice how instead of identifying the value by a number, like in the cats and months examples, we identify the value, using another value - in this case the person's name.
Ok, you've created a new phone book. Now you want to add new numbers to the book. What do you do? A very simple line of code:
All that line is saying is that there is a person called Gingerbread Man in the phone book, and his number is 1234567. In other words - the key is 'Gingerbread Man', and the value is 1234567.
You delete entries in a dictionary just like in a list. Let's say Andrew Parson is your neighbour, and shot your cat. You never want to talk to him again, and therefore don't need his number. Just like in a list, you'd do this:
Again, very easy. the 'del' operator deletes any function, variable, or entry in a list or dictionary (An entry in a dictionary is just a variable with a number or text string as a name. This comes in handy later on.) remember that append function that we used with the list? Well, there are quite a few of those that can be used with dictionaries. Below, I will write you a program, and it will incorporate some of those functions in. It will have comments along the way explaining what it does. Type this program into Python IDLE (you can skip the comments). Experiment as much as you like with it. Type it where you see the lines beginning with >>>
Code Example 10 - Functions of dictionaries#A few examples of a dictionary #First we define the dictionary #it will have nothing in it this time ages = {} #Add a couple of names to the dictionary ages['Sue'] = 23 ages['Peter'] = 19 ages['Andrew'] = 78 ages['Karren'] = 45 #Use the function has_key() - #This function takes this form: #function_name.has_key(key-name) #It returns TRUE #if the dictionary has key-name in it #but returns FALSE if it doesn't. #Remember - this is how 'if' statements work - #they run if something is true #and they don't when something is false. if ages.has_key('Sue'): print "Sue is in the dictionary. She is", \ ages['Sue'], "years old" else: print "Sue is not in the dictionary" #Use the function keys() - #This function returns a list #of all the names of the keys. #E.g. print "The following people are in the dictionary:" print ages.keys() #You could use this function to #put all the key names in a list: keys = ages.keys() #You can also get a list #of all the values in a dictionary. #You use the values() function: print "People are aged the following:", \ ages.values() #Put it in a list: values = ages.values() #You can sort lists, with the sort() function #It will sort all values in a list #alphabetically, numerically, etc... #You can't sort dictionaries - #they are in no particular order print keys keys.sort() print keys print values values.sort() print values #You can find the number of entries #with the len() function: print "The dictionary has", \ len(ages), "entries in it"
There are many other functions you can use to work with lists and dictionaries - too many to go through right now. We'll leave the lesson at this point - you have learnt enough for one lesson.
Well, in the first lesson about loops, I said I would put off teaching you the for loop, until we had reached lists. Well, here it is!
The 'for' Loop
Basically, the for loop does something for every value in a list. The way it is set out is a little confusing, but otherwise is very basic. Here is an example of it in code
As you see, when the loop executes, it runs through all of the values in the list mentioned after 'in'. It then puts them into value, and executes through the loop, each time with value being worth something different. Let's see it a again, in a classic cheerleading call that we all know:
Code Example 2 - A for Loop ExampleA couple of things you've just learnt:
And that is all there is to the for loop. Making a Menu Function
Now to the business end of the lesson. Lets start writing programs. So far we have learnt variables, lists, loops, and functions. That is pretty much all we need for quite a bit of programming. So let's set ourselves a task.
Code Example 3 - A menu functionThat wasn't very difficult, was it? the actual program only took up five lines - this is the wonder of how much we have learnt so far! All my comments take up sixteen lines - more than three times the program length. It is a good idea to comment your programs extensively. Remember that if you are going to be publishin gyour code open-source, there are going to be a lot of people checking out the code that you have written. We'll see the function we just wrote in our first example program.
What will our first example program be? How about a (very) simple text adventure game? Sounds like fun! It will only encompass one room of a house, and will be extremely simple. There will be five things, and a door. In one of the five things, is a key to the door. You need to find the key, then open the door. I will give a plain-english version first, then do it in python:
Code Example 4 - Plain-english version of codeFrom this, we can write a real program. Ready? Here it is (skip typing the comments):
Code Example 5 - Text Adventure GameWell, a very simple, but fun, game. Don't get daunted by the amount of code there, 53 of the lines are just the 'if' statements, which is the easiest thing to read there (Once you comprehend all the indentation. Soon you'll make your own game, and you can make it as simple (or as complex) as you like. I'll post quite a few, later.
The fist question you should ask is "does this program work?". The answer here is yes. Then you should ask "does this program work well?" - not quite. The menu() function is great - it reduces a lot of typing. The 'while' loop that we have, however, is a little messy - four levels of indents, for a simple program. We can do better!
Now, this will become much MUCH more straightforward when we introduce classes. But that will have to wait. Until then, let's make a function that reduces our mess. It we will pass two things to it - the menu choice we made, and the location of the key. It will return one thing - whether or not the key has been found. Lets see it:
Now the main program can be a little simpler. Let's take it from the while loop, and change things around:
Code Example 7 - The new gameNow the program becomes massively shorter - from a cumbersome 83 lines, to a very shapely 50 lines! Of course, you lose quite a bit of versatility - all the items in the room do the same thing. You automatically open the door when you find the key. The game becomes a little less interesting. It also becomes a little harder to change.
Now I said you would write some programs now. Here is your chance! Your task, if you chose to accept it, is to post a better text adventure game. You can use any of the code I have given you here. Remember to check back on previous lessons we have done - they are priceless tools. Do a search for some simple text adventure games - if you find some nice, fun text adventure games, have a look at them.
One thing that you will get to know about programming, is that programmers like to be lazy. If something has been done before, why should you do it again?
That is what functions cover in python. You've already had your code do something special. Now you want to do it again. You put that special code into a function, and re-use it for all it is worth. You can refer to a function anywhere in your code, and the computer will always know what you are talking about. Handy, eh?
Of course, functions have their limitations. Functions don't store any information like variables do - every time a function is run, it starts afresh. However, certain functions and variables are related to each other very closely, and need to interact with each other a lot. For example, imagine you have a golf club. It has information about it (i.e. variables) like the length of the shaft, the material of the grip, and the material of the head. It also has functions associated with it, like the function of swinging your golf club, or the function of breaking it in pure frustration. For those functions, you need to know the variables of the shaft length, head material, etc.
That can easily be worked around with normal functions. Parameters affect the effect of a function. But what if a function needs to affect variables? What happens if each time you use your golf club, the shaft gets weaker, the grip on the handle wears away a little, you get that little more frustrated, and a new scratch is formed on the head of the club? A function cannot do that. A function only makes one output, not four or five, or five hundred. What is needed is a way to group functions and variables that are closely related into one place so that they can interact with each other.
Chances are that you also have more than one golf club. Without classes, you need to write a whole heap of code for each different golf club. This is a pain, seeing that all clubs share common features, it is just that some have changed properties - like what the shaft is made of, and it's weight. The ideal situation would be to have a design of your basic golf club. Each time you create a new club, simply specify its attributes - the length of its shaft, its weight, etc.
Or what if you want a golf club, which has added extra features? Maybe you decide to attach a clock to your golf club (why, I don't know - it was your idea). Does this mean that we have to create this golf club from scratch? We would have to write code first for our basic golf club, plus all of that again, and the code for the clock, for our new design. Wouldn't it be better if we were to just take our existing golf club, and then tack the code for the clock to it?
These problems that a thing called object-oriented-programming solves. It puts functions and variables together in a way that they can see each other and work together, be replicated, and altered as needed, and not when unneeded. And we use a thing called a 'class' to do this.
What is a class? Think of a class as a blueprint. It isn't something in itself, it simply describes how to make something. You can create lots of objects from that blueprint - known technically as an instance.
So how do you make these so-called 'classes'? very easily, with the class operator:
Makes little sense? Thats ok, here is an example, that creates the definition of a Shape:
Code Example 2 - Example of a ClassWhat you have created is a description of a shape (That is, the variables) and what operations you can do with the shape (That is, the fuctions). This is very important - you have not made an actual shape, simply the description of what a shape is. The shape has a width (x), a height (y), and an area and perimeter (area(self) and perimeter(self)). No code is run when you define a class - you are simply making functions and variables.
The function called __init__ is run when we create an instance of Shape - that is, when we create an actual shape, as opposed to the 'blueprint' we have here, __init__ is run. You will understand how this works later.
self is how we refer to things in the class from within itself. self is the first parameter in any function defined inside a class. Any function or variable created on the first level of indentation (that is, lines of code that start one TAB to the right of where we put class Shape is automatically put into self. To access these functions and variables elsewhere inside the class, their name must be preceeded with self and a full-stop (e.g. self.variable_name).
Its all well and good that we can make a class, but how do we use one? Here is an example, of what we call creating an instance of a class. Assume that the code example 2 has already been run:
Code Example 3 - Creating a classWhat has been done? It takes a little explaining...
The __init__ function really comes into play at this time. We create an instance of a class by first giving its name (in this case, Shape) and then, in brackets, the values to pass to the __init__ function. The init function runs (using the parameters you gave it in brackets) and then spits out an instance of that class, which in this case is assigned to the name rectangle.
Think of our class instance, rectangle, as a self-contained collection of variables and functions. In the same way that we used self to access functions and variables of the class instance from within itself, we use the name that we assigned to it now (rectangle) to access functions and variables of the class instance from outside of itself. Following on from the code we ran above, we would do this:
As you see, where self would be used from within the class instance, its assigned name is used when outside the class. We do this to view and change the variables inside the class, and to access the functions that are there.
We aren't limited to a single instance of a class - we could have as many instances as we like. I could do this:
and both longrectangle and fatrectangle have their own functions and variables contained inside them - they are totally independent of each other. There is no limit to the number of instances I could create.
Object-oriented-programming has a set of lingo that is associated with it. Its about time that we have this all cleared up:
Lets have a look back at the introduction. We know how classes group together variables and functions, known as attributes and methods, so that both the data and the code to process it is in the same spot. We can create any number of instances of that class, so that we don't have to write new code for every new object we create. But what about adding extra features to our golf club design? This is where inheritance comes into play.
Python makes inheritance really easily. We define a new class, based on another, 'parent' class. Our new class brings everything over from the parent, and we can also add other things to it. If any new attributes or methods have the same name as an attribute or method in our parent class, it is used instead of the parent one. Remember the Shape class?
If we wanted to define a new class, lets say a square, based on our previous Shape class, we would do this:
Code Example 7 - Using inheritanceIt is just like normally defining a class, but this time we put in brackets after the name, the parent class that we inherited from. As you see, we described a square really quickly because of this. That's because we inherited everything from the shape class, and changed only what needed to be changed. In this case we redefined the __init__ function of Shape so that the X and Y values are the same.
Let's take from what we have learnt, and create another new class, this time inherited from Square. It will be two squares, one immediately left of the other:
This time, we also had to redefine the perimeter function, as there is a line going down the middle of the shape. Try creating an instance of this class. As a helpful hint, the idle command line starts where your code ends - so typing a line of code is like adding that line to the end of the program you have written.
Thinking back, when you say that one variable equals another, e.g. variable2 = variable1, the variable on the left-hand side of the equal-sign takes on the value of the variable on the right. With class instances, this happens a little differently - the name on the left becomes the class instance on the right. So in instance2 = instance1, instance2 is 'pointing' to instance1 - there are two names given to the one class instance, and you can access the class instance via either name.
In other languages, you do things like this using pointers, however in python this all happens behind the scenes.
The final thing that we will cover is dictionaries of classes. Keeping in mind what we have just learnt about pointers, we can assign an instance of a class to an entry in a list or dictionary. This allows for virtually any amount of class instances to exist when our program is run. Lets have a look at the example below, and see how it describes what I am talking about:
As you see, we simply replaced our boring old name on the left-hand side with an exciting, new, dynamic, dictionary entry. Pretty cool, eh?
And that is the lesson on classes! You won't believe how long it took me to write this in a clear-cut manner, and I am still not completely satisfied! I have already gone through and rewritten half of this lesson once, and if you're still confused, I'll probably go through it again. I've probably confused some of you with my own confusion on this topic, but remember - it is not something's name that is important, but what it does (this doesn't work in a social setting, believe me... ;)).
Last lesson we covered the killer topic of Classes. As you can remember, classes are neat combinations of variables and functions in a nice, neat package. Programming lingo calls this feature encapsulation, but reguardless of what it is called, it's a really cool feature for keeping things together so the code can be used in many instances in lots of places. Of course, you've got to ask, "how do I get my classes to many places, in many programs?". The answer is to put them into a module, to be imported into other programs.
A module is a python file that (generally) has only defenitions of variables, functions, and classes. For example, a module might look like this:
Code Example 1 - moduletest.pyAs you see, a module looks pretty much like your normal python program.
So what do we do with a module? We import bits of it (or all of it) into other programs.
To import all the variables, functions and classes from moduletest.py into another program you are writing, we use the import operator. For example, to import moduletest.py into your main program, you would have this:
This assumes that the module is in the same directory as mainprogram.py, or is a default module that comes with python. You leave out the '.py' at the end of the file - it is ignored. You normally put all import statements at the beginning of the python file, but technically they can be anywhere. In order to use the items in the module in your main program, you use the following:
Code Example 3 - mainprogram.py continuedAs you see, the modules that you import act very much like the classes we looked at last lesson - anything inside them must be preceeded with modulename. for it to work.
Wish you could get rid of the modulename. part that you have to put before every item you use from a module? No? Never? Well, I'll teach it you anyway.
One way to avoid this hassle is to import only the wanted objects from the module. To do this, you use the from operator. You use it in the form of from modulename import itemname. Here is an example:
What is the point of this? Well, maybe you could use it to make your code a little more readable. If we get into heaps of modules inside modules, it could also remove that extra layer of crypticness.
If you wanted to, you could import everything from a module is this way by using from modulename import *. Of course, this can be troublesome if there are objects in your program with the same name as some items in the module. With large modules, this can easily happen, and can cause many a headache. A better way to do this would be to import a module in the normal way (without the from operator) and then assign items to a local name:
This way, you can remove some crypticness, AND have all of the items from a certain module.
That's it! A very simple lesson, but now you can organise your programs very neatly. In fact, now it is increadibly easy to make progams that can grow in complexity without ending up with one cryptic file that is full of bugs.
Modules are great for importing code. Next lesson, we learn about file input and output, and the saving of information inside classes, to be retrieved later. Will be great! But until then...
Last lesson we learnt how to load external code into our program. Without any introduction (like what I usually have), let's delve into file input and output with normal text files, and later the saving and restoring of instances of classes. (Wow, our lingo power has improved greatly!)
To open a text file you use, well, the open() function. Seems sensible. You pass certain parameters to open() to tell it in which way the file should be opened - 'r' for read only, 'w' for writing only (if there is an old file, it will be written over), 'a' for appending (adding things on to the end of the file) and 'r+' for both reading and writing. But less talk, lets open a file for reading (you can do this in your python idle mode). Open a normal text file. We will then print out what we read inside the file:
Code Example 1 - Opening a file That was interesting. You'll notice a lot of '\n' symbols. These represent newlines (where you pressed enter to start a new line). The text is completely unformatted, but if you were to pass the output of openfile.read() to print (by typing print openfile.read()) it would be nicely formatted.Did you try typing in print openfile.read()? Did it fail? It likely did, and reason is because the 'cursor' has changed it's place. Cursor? What cursor? Well, a cursor that you really cannot see, but still a cursor. This invisible cursor tells the read function (and many other I/O functions) where to start from. To set where the cursor is, you use the seek() function. It is used in the form seek(offset, whence).
whence is optional, and determines where to seek from. If whence is 0, the bytes/letters are counted from the beginning. If it is 1, the bytes are counted from the current cursor position. If it is 2, then the bytes are counted from the end of the file. If nothing is put there, 0 is assumed.
offset decribes how far from whence that the cursor moves. for example:
Try it out now. Use openfile.seek() to go to any spot in the file and then try typing print openfile.read(). It will print from the spot you seeked to. But realise that openfile.read() moves the cursor to the end of the file - you will have to seek again.
There are many other functions that help you with dealing with files. They have many uses that empower you to do more, and make the things you can do easier. Let's have a look at tell(), readline(), readlines(), write() and close().
tell() returns where the cursor is in the file. It has no parameters, just type it in (like what the example below will show). This is infinitely useful, for knowing what you are refering to, where it is, and simple control of the cursor. To use it, type fileobjectname.tell() - where fileobjectname is the name of the file object you created when you opened the file (in openfile = open('pathtofile', 'r') the file object name is openfile).
readline() reads from where the cursor is till the end of the line. Remember that the end of the line isn't the edge of your screen - the line ends when you press enter to create a new line. This is useful for things like reading a log of events, or going through something progressively to process it. There are no parameters you have to pass to readline(), though you can optionally tell it the maximum number of bytes/letters to read by putting a number in the brackets. Use it with fileobjectname.readline().
readlines() is much like readline(), however readlines() reads all the lines from the cursor onwards, and returns a list, with each list element holding a line of code. Use it with fileobjectname.readlines(). For example, if you had the text file:
then the returned list from readlines() would be:
Table 1 - resulting list from readlinesThe write() function, writes to the file. How did you guess??? It writes from where the cursor is, and overwrites text in front of it - like in MS Word, where you press 'insert' and it writes over the top of old text. To utilise this most purposeful function, put a string between the brackets to write e.g. fileobjectname.write('this is a string').
close, you may figure, closes the file so that you can no longer read or write to it until you reopen in again. Simple enough. To use, you would write fileobjectname.close(). Simple!
In Python idle mode, open up a test file (or create a new one...) and play around with these functions. You can do some simple (and very inconvenient) text editing.
Pickles, in Python, are to be eaten. Their flavour is just to good to let programmers leave them in the fridge.
Ok, just joking there. Pickles, in Python, are objects saved to a file. An object in this case could be a variables, instance of a class, or a list, dictionary, or tuple. Other things can also be pickled, but with limits. The object can then be restored, or unpickled, later on. In other words, you are 'saving' your objects.
So how do we pickle? With the dump() function, which is inside the pickle module - so at the beginning of your program you will have to write import pickle. Simple enough? Then open an empty file, and use pickle.dump() to drop the object into that file. Let's try that:
The code to do this is laid out like pickle.load(object_to_pickle, file_object) where:
After you close the file, open it in notepad and look at what you see. Along with some other gibblygook, you will see bits of the list we created.
Now to re-open, or unpickle, your file. to use this, we would use pickle.load():
Which ends this lesson.
Thanks to all,
The essential tools needed to follow these tutorials are a computer and a compiler toolchain able to compile C++ code and build the programs to run on it.
C++ is a language that has evolved much over the years, and these tutorials explain many features added recently to the language. Therefore, in order to properly follow the tutorials, a recent compiler is needed. It shall support (even if only partially) the features introduced by the 2011 standard.
Many compiler vendors support the new features at different degrees. See the bottom of this page for some compilers that are known to support the features needed. Some of them are free!
If for some reason, you need to use some older compiler, you can access an older version of these tutorials here (no longer updated).
Computers understand only one language and that language consists of sets of instructions made of ones and zeros. This computer language is appropriately called machine language.
A single instruction to a computer could look like this:
00000 | 10011110 |
A particular computer's machine language program that allows a user to input two numbers, adds the two numbers together, and displays the total could include these machine code instructions:
00000 | 10011110 |
00001 | 11110100 |
00010 | 10011110 |
00011 | 11010100 |
00100 | 10111111 |
00101 | 00000000 |
As you can imagine, programming a computer directly in machine language using only ones and zeros is very tedious and error prone. To make programming easier, high level languages have been developed. High level programs also make it easier for programmers to inspect and understand each other's programs easier.
This is a portion of code written in C++ that accomplishes the exact same purpose:
Even if you cannot really understand the code above, you should be able to appreciate how much easier it will be to program in the C++ language as opposed to machine language.
Because a computer can only understand machine language and humans wish to write in high level languages high level languages have to be re-written (translated) into machine language at some point. This is done by special programs called compilers, interpreters, or assemblers that are built into the various programming applications.
C++ is designed to be a compiled language, meaning that it is generally translated into machine language that can be understood directly by the system, making the generated program highly efficient. For that, a set of tools are needed, known as the development toolchain, whose core are a compiler and its linker.
Console programs are programs that use text to communicate with the user and the environment, such as printing text to the screen or reading input from a keyboard.
Console programs are easy to interact with, and generally have a predictable behavior that is identical across all platforms. They are also simple to implement and thus are very useful to learn the basics of a programming language: The examples in these tutorials are all console programs.
The way to compile console programs depends on the particular tool you are using.
The easiest way for beginners to compile C++ programs is by using an Integrated Development Environment (IDE). An IDE generally integrates several development tools, including a text editor and tools to compile programs directly from it.
Here you have instructions on how to compile and run console programs using different free Integrated Development Interfaces (IDEs):
IDE | Platform | Console programs |
---|---|---|
Code::blocks | Windows/ Linux/ MacOS | Compile console programs using Code::blocks |
Visual Studio Express | Windows | Compile console programs using VS Express 2013 |
Dev-C++ | Windows | Compile console programs using Dev-C++ |
If you happen to have a Linux or Mac environment with development features, you should be able to compile any of the examples directly from a terminal just by including C++11 flags in the command for the compiler:
Compiler | Platform | Command |
---|---|---|
GCC | Linux, among others... | g++ -std=c++0x example.cpp -o example_program |
Clang | OS X, among others... | clang++ -std=c++11 -stdlib=libc++ example.cpp -o example_program |
The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which simply prints "Hello World" to your computer screen. Although it is very simple, it contains all the fundamental components C++ programs have:
Hello World!
The left panel above shows the C++ code for this program. The right panel shows the result when the program is executed by a computer. The grey numbers to the left of the panels are line numbers to make discussing programs and researching errors easier. They are not part of the program.
Let's examine this program line by line:
Line 1: // my first program in C++
Two slash signs indicate that the rest of the line is a comment inserted by the programmer but which has no effect on the behavior of the program. Programmers use them to include short explanations or observations concerning the code or program. In this case, it is a brief introductory description of the program.
Line 2: #include <iostream>
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor. They are special lines interpreted before the compilation of the program itself begins. In this case, the directive #include <iostream>, instructs the preprocessor to include a section of standard C++ code, known as header iostream, that allows to perform standard input and output operations, such as writing the output of this program (Hello World) to the screen.
Line 3: A blank line.
Blank lines have no effect on a program. They simply improve readability of the code.
Line 4: int main ()
This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name: in this case, this gives the name "main" to the group of code statements that follow. Functions will be discussed in detail in a later chapter, but essentially, their definition is introduced with a succession of a type (int), a name (main) and a pair of parentheses (()), optionally including parameters.
The function named main is a special function in all C++ programs; it is the function called when the program is run. The execution of all C++ programs begins with the main function, regardless of where the function is actually located within the code.
Lines 5 and 7: { and }
The open brace ({) at line 5 indicates the beginning of main's function definition, and the closing brace (}) at line 7, indicates its end. Everything between these braces is the function's body that defines what happens when main is called. All functions use braces to indicate the beginning and end of their definitions.
Line 6: std::cout< "Hello World!";
This line is a C++ statement. A statement is an expression that can actually produce some effect. It is the meat of a program, specifying its actual behavior. Statements are executed in the same order that they appear within a function's body.
This statement has three parts: First, std::cout, which identifies the standard character output device (usually, this is the computer screen). Second, the insertion operator (<<), which indicates that what follows is inserted into std::cout. Finally, a sentence within quotes ("Hello world!"), is the content inserted into the standard output.
Notice that the statement ends with a semicolon (;). This character marks the end of the statement, just as the period ends a sentence in English. All C++ statements must end with a semicolon character. One of the most common syntax errors in C++ is forgetting to end a statement with a semicolon.
You may have noticed that not all the lines of this program perform actions when the code is executed. There is a line containing a comment (beginning with //). There is a line with a directive for the preprocessor (beginning with #). There is a line that defines a function (in this case, the main function). And, finally, a line with a statements ending with a semicolon (the insertion into cout), which was within the block delimited by the braces ( { } ) of the main function.
The program has been structured in different lines and properly indented, in order to make it easier to understand for the humans reading it. But C++ does not have strict rules on indentation or on how to split instructions in different lines.
For example, instead of
We could have written:
all in a single line, and this would have had exactly the same meaning as the preceding code.
In C++, the separation between statements is specified with an ending semicolon (;), with the separation into different lines not mattering at all for this purpose. Many statements can be written in a single line, or each statement can be in its own line. The division of code in different lines serves only to make it more legible and schematic for the humans that may read it, but has no effect on the actual behavior of the program.
Now, let's add an additional statement to our first program:
Hello World! I'm a C++ program
In this case, the program performed two insertions into std::cout in two different statements. Once again, the separation in different lines of code simply gives greater readability to the program, since main could have been perfectly valid defined in this way:
The source code could have also been divided into more code lines instead:
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not statements. They are lines read and processed by the preprocessor before proper compilation begins. Preprocessor directives must be specified in their own line and, because they are not statements, do not have to end with a semicolon (;).
As noted above, comments do not affect the operation of the program; however, they provide an important tool to document directly within the source code what the program does and how it operates.
C++ supports two ways of commenting code:
The first of them, known as line comment, discards everything from where the pair of slash signs (//) are found up to the end of that same line. The second one, known as block comment, discards everything between the /* characters and the first appearance of the */ characters, with the possibility of including multiple lines.
Let's add comments to our second program:
Hello World! I'm a C++ program
If comments are included within the source code of a program without using the comment characters combinations //, /* or */, the compiler takes them as if they were C++ expressions, most likely causing the compilation to fail with one, or several, error messages.
If you have seen C++ code before, you may have seen cout being used instead of std::cout. Both name the same object: the first one uses its unqualified name (cout), while the second qualifies it directly within the namespace std (as std::cout).
cout is part of the standard library, and all the elements in the standard C++ library are declared within what is a called a namespace: the namespace std.
In order to refer to the elements in the std namespace a program shall either qualify each and every use of elements of the library (as we have done by prefixing cout with std::), or introduce visibility of its components. The most typical way to introduce visibility of these components is by means of using declarations:
using namespace std;
The above declaration allows all elements in the std namespace to be accessed in an unqualified manner (without the std:: prefix).
With this in mind, the last example can be rewritten to make unqualified uses of cout as:
Hello World! I'm a C++ program
Both ways of accessing the elements of the std namespace (explicit qualification and using declarations) are valid in C++ and produce the exact same behavior. For simplicity, and to improve readability, the examples in these tutorials will more often use this latter approach with using declarations, although note that explicit qualification is the only way to guarantee that name collisions never happen.
The usefulness of the "Hello World" programs shown in the previous chapter is rather questionable. We had to write several lines of code, compile them, and then execute the resulting program, just to obtain the result of a simple sentence written on the screen. It certainly would have been much faster to type the output sentence ourselves.
However, programming is not limited only to printing simple texts on the screen. In order to go a little further on and to become able to write programs that perform useful tasks that really save us work, we need to introduce the concept of variables.
Let's imagine that I ask you to remember the number 5, and then I ask you to also memorize the number 2 at the same time. You have just stored two different values in your memory (5 and 2). Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Then we could, for example, subtract these values and obtain 4 as result.
The whole process described above is a simile of what a computer can do with two variables. The same process can be expressed in C++ with the following set of statements:
Obviously, this is a very simple example, since we have only used two small integer values, but consider that your computer can store millions of numbers like these at the same time and conduct sophisticated mathematical operations with them.
We can now define variable as a portion of memory to store a value.
Each variable needs a name that identifies it and distinguishes it from the others. For example, in the previous code the variable names were a, b, and result, but we could have called the variables any names we could have come up with, as long as they were valid C++ identifiers.
A valid identifier is a sequence of one or more letters, digits, or underscore characters (_). Spaces, punctuation marks, and symbols cannot be part of an identifier. In addition, identifiers shall always begin with a letter. They can also begin with an underline character (_), but such identifiers are -on most cases- considered reserved for compiler-specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere. In no case can they begin with a digit.
C++ uses a number of keywords to identify operations and data descriptions; therefore, identifiers created by a programmer cannot match these keywords. The standard reserved keywords that cannot be used for programmer created identifiers are:
alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch, char, char16_t, char32_t, class, compl, const, constexpr, const_cast, continue, decltype, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_assert, static_cast, struct, switch, template, this, thread_local, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while, xor, xor_eq
Specific compilers may also have additional specific reserved keywords.
Very important: The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different identifiers identifiying three different variables.The values of variables are stored somewhere in an unspecified location in the computer memory as zeros and ones. Our program does not need to know the exact location where a variable is stored; it can simply refer to it by its name. What the program needs to be aware of is the kind of data stored in the variable. It's not the same to store a simple integer as it is to store a letter or a large floating-point number; even though they are all represented using zeros and ones, they are not interpreted in the same way, and in many cases, they don't occupy the same amount of memory.
Fundamental data types are basic types implemented directly by the language that represent the basic storage units supported natively by most systems. They can mainly be classified into:
Here is the complete list of fundamental types in C++:
Group | Type names* | Notes on size / precision |
---|---|---|
Character types | char | Exactly one byte in size. At least 8 bits. |
char16_t | Not smaller than char . At least 16 bits. | |
char32_t | Not smaller than char16_t . At least 32 bits. | |
wchar_t | Can represent the largest supported character set. | |
Integer types (signed) | signed char | Same size as char . At least 8 bits. |
signed short int | Not smaller than char . At least 16 bits. | |
signed int | Not smaller than short . At least 16 bits. | |
signed long int | Not smaller than int . At least 32 bits. | |
signed long long int | Not smaller than long . At least 64 bits. | |
Integer types (unsigned) | unsigned char | (same size as their signed counterparts) |
unsigned short int | ||
unsigned int | ||
unsigned long int | ||
unsigned long long int | ||
Floating-point types | float | |
double | Precision not less than float | |
long double | Precision not less than double | |
Boolean type | bool | |
Void type | void | no storage |
Null pointer | decltype(nullptr) |
* The names of certain integer types can be abbreviated without their signed and int components - only the part not in italics is required to identify the type, the part in italics is optional. I.e., signed short int can be abbreviated as signed short, short int, or simply short; they all identify the same fundamental type.
Within each of the groups above, the difference between types is only their size (i.e., how much they occupy in memory): the first type in each group is the smallest, and the last is the largest, with each type being at least as large as the one preceding it in the same group. Other than that, the types in a group have the same properties.
Note in the panel above that other than char (which has a size of exactly one byte), none of the fundamental types has a standard size specified (but a minimum size, at most). Therefore, the type is not required (and in many cases is not) exactly this minimum size. This does not mean that these types are of an undetermined size, but that there is no standard size across all compilers and machines; each compiler implementation may specify the sizes for these types that fit the best the architecture where the program is going to run. This rather generic size specification for types gives the C++ language a lot of flexibility to be adapted to work optimally in all kinds of platforms, both present and future.
Type sizes above are expressed in bits; the more bits a type has, the more distinct values it can represent, but at the same time, also consumes more space in memory:
Size | Unique representable values | Notes |
---|---|---|
8-bit | 256 | = 28 |
16-bit | 65 536 | = 216 |
32-bit | 4 294 967 296 | = 232 (~4 billion) |
64-bit | 18 446 744 073 709 551 616 | = 264 (~18 billion billion) |
For integer types, having more representable values means that the range of values they can represent is greater; for example, a 16-bit unsigned integer would be able to represent 65536 distinct values in the range 0 to 65535, while its signed counterpart would be able to represent, on most cases, values between -32768 and 32767. Note that the range of positive values is approximately halved in signed types compared to unsigned types, due to the fact that one of the 16 bits is used for the sign; this is a relatively modest difference in range, and seldom justifies the use of unsigned types based purely on the range of positive values they can represent.
For floating-point types, the size affects their precision, by having more or less bits for their significant and exponent.
If the size or precision of the type is not a concern, then char, int, and double are typically selected to represent characters, integers, and floating-point values, respectively. The other types in their respective groups are only used in very particular cases.
The properties of fundamental types in a particular system and compiler implementation can be obtained by using the numeric_limits classes (see standard header <limits>). If for some reason, types of specific sizes are needed, the library defines certain fixed-size type aliases in header <cstdint>.
The types described above (characters, integers, floating-point, and boolean) are collectively known as arithmetic types. But two additional fundamental types exist: void, which identifies the lack of type; and the type nullptr, which is a special type of pointer. Both types will be discussed further in a coming chapter about pointers.
C++ supports a wide variety of types based on the fundamental types discussed above; these other types are known as compound data types, and are one of the main strengths of the C++ language. We will also see them in more detail in future chapters.
C++ is a strongly-typed language, and requires every variable to be declared with its type before its first use. This informs the compiler the size to reserve in memory for the variable and how to interpret its value. The syntax to declare a new variable in C++ is straightforward: we simply write the type followed by the variable name (i.e., its identifier). For example:
int a;
float mynumber;
These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber. Once declared, the variables a and mynumber can be used within the rest of their scope in the program. If declaring more than one variable of the same type, they can all be declared in a single statement by separating their identifiers with commas. For example:
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:
int a;
int b;
int c;
4
Don't be worried if something else than the variable declarations themselves look a bit strange to you. Most of it will be explained in more detail in coming chapters.
When the variables in the example above are declared, they have an undetermined value until they are assigned a value for the first time. But it is possible for a variable to have a specific value from the moment it is declared. This is called the initialization of the variable.
In C++, there are three ways to initialize variables. They are all equivalent and are reminiscent of the evolution of the language over the years:
The first one, known as c-like initialization (because it is inherited from the C language), consists of appending an equal sign followed by the value to which the variable is initialized:
type identifier = initial_value;
For example, to declare a variable of type int called x and initialize it to a value of zero from the same moment it is declared, we can write:
int x = 0;
A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (()):
type identifier (initial_value);
For example:
int x (0);
Finally, a third method, known as uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011):
type identifier {initial_value};
For example:
int x {0};
All three ways of initializing variables are valid and equivalent in C++.
6
When a new variable is initialized, the compiler can figure out what the type of the variable is automatically by the initializer. For this, it suffices to use auto as the type specifier for the variable:
int foo = 0;
auto bar = foo; // the same as: int bar = foo;
Here, bar is declared as having an auto type; therefore, the type of bar is the type of the value used to initialize it: in this case it uses the type of foo, which is int.
Variables that are not initialized can also make use of type deduction with the decltype specifier:
int foo = 0;
decltype(foo) bar; // the same as: int bar;
Here, bar is declared as having the same type as foo.
auto and decltype are powerful features recently added to the language. But the type deduction features they introduce are meant to be used either when the type cannot be obtained by other means or when using it improves code readability. The two examples above were likely neither of these use cases. In fact they probably decreased readability, since, when reading the code, one has to search for the type of foo to actually know the type of bar.
Fundamental types represent the most basic types handled by the machines where the code may run. But one of the major strengths of the C++ language is its rich set of compound types, of which the fundamental types are mere building blocks. An example of compound type is the string class. Variables of this type are able to store sequences of characters, such as words or sentences. A very useful feature! A first difference with fundamental data types is that in order to declare and use objects (variables) of this type, the program needs to include the header where the type is defined within the standard library (header <tring>):
This is a string
As you can see in the previous example, strings can be initialized with any valid string literal, just like numerical type variables can be initialized to any valid numerical literal. As with fundamental types, all initialization formats are valid with strings:
string mystring = "This is a string";
string mystring ("This is a string");
string mystring {"This is a string"};
Strings can also perform all the other basic operations that fundamental data types can, like being declared without an initial value and change its value during execution:
This is the initial string content
This is a different string content
Literals are the most obvious kind of constants. They are used to express particular values within the source code of a program. We have already used some in previous chapters to give specific values to variables or to express messages we wanted our programs to print out, for example, when we wrote:
a = 5;
The 5 in this piece of code was a literal constant.
Literal constants can be classified into: integer, floating-point, characters, strings, Boolean, pointers, and user-defined literals.
1776
707
-273
These are numerical constants that identify integer values. Notice that they are not enclosed in quotes or any other special character; they are a simple succession of digits representing a whole number in decimal base; for example, 1776 always represents the value one thousand seven hundred seventy-six.
In addition to decimal numbers (those that most of us use every day), C++ allows the use of octal numbers (base 8) and hexadecimal numbers (base 16) as literal constants. For octal literals, the digits are preceded with a 0 (zero) character. And for hexadecimal, they are preceded by the characters 0x (zero, x). For example, the following literal constants are all equivalent to each other:
75 // decimal
0113 // octal
0x4b // hexadecimal
All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively.
These literal constants have a type, just like variables. By default, integer literals are of type int. However, certain suffixes may be appended to an integer literal to specify a different integer type:
Suffix | Type modifier |
---|---|
u or U | unsigned |
l or L | long |
ll or LL | long long |
Unsigned may be combined with any of the other two in any order to form unsigned long or unsigned long long.
For example:
In all the cases above, the suffix can be specified using either upper or lowercase letters.
They express real values, with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character:
These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated-, and the last one is the number three expressed as a floating-point numeric literal.
The default type for floating-point literals is double. Floating-point literals of type float or long double can be specified by adding one of the following suffixes:
Suffix | Type |
---|---|
f or F | float |
l or L | long double |
For example:
Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters with no difference in meaning.
Character and string literals
Character and string literals are enclosed in quotes:
The first two expressions represent single-character literals, and the following two represent string literals composed of several characters. Notice that to represent a single character, we enclose it between single quotes ('), and to express a string (which generally consists of more than one character), we enclose the characters between double quotes (").
Both single-character and string literals require quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions:
x
'x'
Here, x alone would refer to an identifier, such as the name of a variable or a compound type, whereas 'x' (enclosed within single quotation marks) would refer to the character literal 'x' (the character that represents a lowercase x letter).
Character and string literals can also represent special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). These special characters are all of them preceded by a backslash character (\).
Here you have a list of the single character escape codes:
Escape code | Description |
---|---|
\n | newline |
\r | carriage return |
\t | tab |
\v | vertical tab |
\b | backspace |
\f | form feed (page feed) |
\a | alert (beep) |
\' | single quote (' ) |
\" | double quote (" ) |
\? | question mark (? ) |
\\ | backslash (\ ) |
For example:
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"
Internally, computers represent characters as numerical codes: most typically, they use one extension of the ASCII character encoding system (see ASCII code for more info). Characters can also be represented in literals using its numerical code by writing a backslash character (\) followed by the code expressed as an octal (base-8) or hexadecimal (base-16) number. For an octal value, the backslash is followed directly by the digits; while for hexadecimal, an x character is inserted between the backslash and the hexadecimal digits themselves (for example: \x20 or \x4A).
Several string literals can be concatenated to form a single string literal simply by separating them by one or more blank spaces, including tabs, newlines, and other valid blank characters. For example:
The above is a string literal equivalent to:
Note how spaces within the quotes are part of the literal, while those outside them are not.
Some programmers also use a trick to include long string literals in multiple lines: In C++, a backslash (\) at the end of line is considered a line-continuation character that merges both that line and the next into a single line. Therefore the following code:
is equivalent to:
All the character literals and string literals described above are made of characters of type char. A different character type can be specified by using one of the following prefixes:
Prefix | Character type |
---|---|
u | char16_t |
U | char32_t |
L | wchar_t |
Note that, unlike type suffixes for integer literals, these prefixes are case sensitive: lowercase for char16_t and uppercase for char32_t and wchar_t.
For string literals, apart from the above u, U, and L, two additional prefixes exist:
Prefix | Description |
---|---|
u8 | The string literal is encoded in the executable using UTF-8 |
R | The string literal is a raw string |
In raw strings, backslashes and single and double quotes are all valid characters; the content of the literal is delimited by an initial R"sequence( and a final )sequence", where sequence is any sequence of characters (including an empty sequence). The content of the string is what lies inside the parenthesis, ignoring the delimiting sequence itself. For example:
Both strings above are equivalent to "string with \\backslash". The R prefix can be combined with any other prefixes, such as u, L or u8.
Three keyword literals exist in C++: true, false and nullptr:
Sometimes, it is just convenient to give a name to a constant value:
We can then use these names instead of the literals they were defined to:
31.4159
Another mechanism to name constant values is the use of preprocessor definitions. They have the following form:
#define identifier replacement
After this directive, any occurrence of identifier in the code is interpreted as replacement, where replacement is any sequence of characters (until the end of the line). This replacement is performed by the preprocessor, and happens before the program is compiled, thus causing a sort of blind replacement: the validity of the types or syntax involved is not checked in any way.
For example:
31.4159
Note that the #define lines are preprocessor directives, and as such are single-line instructions that -unlike C++ statements- do not require semicolons (;) at the end; the directive extends automatically until the end of the line. If a semicolon is included in the line, it is part of the replacement sequence and is also included in all replaced occurrences.
Once introduced to variables and constants, we can begin to operate with them by using operators. What follows is a complete list of operators. At this point, it is likely not necessary to know all of them, but they are all listed here to also serve as reference.
The assignment operator assigns a value to a variable.
x = 5;
This statement assigns the integer value 5 to the variable x. The assignment operation always takes place from right to left, and never the other way around:
x = y;
This statement assigns to variable x the value contained in variable y. The value of x at the moment this statement is executed is lost and replaced by the value of y.
Consider also that we are only assigning the value of y to x at the moment of the assignment operation. Therefore, if y changes at a later moment, it will not affect the new value taken by x.
For example, let's have a look at the following code - I have included the evolution of the content stored in the variables as comments:
a:4 b:7
This program prints on screen the final values of a and b (4 and 7, respectively). Notice how a was not affected by the final modification of b, even though we declared a = b earlier.
Assignment operations are expressions that can be evaluated. That means that the assignment itself has a value, and -for fundamental types- this value is the one assigned in the operation. For example:
y = 2 + (x = 5);
In this expression, y is assigned the result of adding 2 and the value of another assignment expression (which has itself a value of 5). It is roughly equivalent to:
x = 5;
y = 2 + x;
With the final result of assigning 7 to y.
The following expression is also valid in C++:
y = y = z = 5;
It assigns 5 to the all three variables: x, y and z; always from right-to-left.
The five arithmetical operations supported by C++ are:
operator | description |
---|---|
+ | addition |
- | subtraction |
* | multiplication |
/ | division |
% | modulo |
Operations of addition, subtraction, multiplication and division correspond literally to their respective mathematical operators. The last one, modulo operator, represented by a percentage sign (%), gives the remainder of a division of two values. For example:
x = 11 % 3;
results in variable x containing the value 2, since dividing 11 by 3 results in 3, with a remainder of 2.
Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand:
expression | equivalent to... |
---|---|
y += x; | y = y + x; |
x -= 5; | x = x - 5; |
x /= y; | x = x / y; |
price *= units + 1; | price = price * (units+1); |
and the same for all other compound assignment operators. For example:
Some expression can be shortened even more: the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:
are all equivalent in its functionality; the three of them increase by one the value of x.
In the early C compilers, the three previous expressions may have produced different executable code depending on which one was used. Nowadays, this type of code optimization is generally performed automatically by the compiler, thus the three expressions should produce exactly the same executable code.
A peculiarity of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable name (++x) or after it (x++). Although in simple expressions like x++ or ++x, both have exactly the same meaning; in other expressions in which the result of the increment or decrement operation is evaluated, they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++x) of the value, the expression evaluates to the final value of x, once it is already increased. On the other hand, in case that it is used as a suffix (x++), the value is also increased, but the expression evaluates to the value that x had before being increased. Notice the difference:
Example 1 | Example 2 |
---|---|
x = 3; |
x = 3; |
In Example 1, the value assigned to y is the value of x after being increased. While in Example 2, it is the value x had before being increased.
Two expressions can be compared using relational and equality operators. For example, to know if two values are equal or if one is greater than the other.
The result of such an operation is either true or false (i.e., a Boolean value).
The relational operators in C++ are:
operator | description |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
Here there are some examples:
Of course, it's not just numeric constants that can be compared, but just any value, including, of course, variables. Suppose that a=2, b=3 and c=6, then:
Be careful! The assignment operator (operator =, with one equal sign) is not the same as the equality comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the right-hand to the variable on its left, while the other (==) compares whether the values on both sides of the operator are equal. Therefore, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a (that also stores the value 2), yielding true.
The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:
The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a&&b:
&& OPERATOR (and) | ||
---|---|---|
a | b | a && b |
true | true | true |
true | false | false |
false | true | false |
false | false | false |
The operator || corresponds to the Boolean logical operation OR, which yields true if either of its operands is true, thus being false only when both operands are false. Here are the possible results of a||b:
|| OPERATOR (or) | ||
---|---|---|
a | b | a || b |
true | true | true |
true | false | true |
false | true | true |
false | false | false |
When using the logical operators, C++ only evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest. Therefore, in the last example ((5==5)||(3>6)), C++ evaluates first whether 5==5 is true, and if so, it never checks whether 3>6 is true or not. This is known as short-circuit evaluation, and works like this for these operators:
operator | short-circuit |
---|---|
&& | if the left-hand side expression is false , the combined result is false (the right-hand side expression is never evaluated). |
|| | if the left-hand side expression is true , the combined result is true (the right-hand side expression is never evaluated). |
This is mostly important when the right-hand expression has side effects, such as altering values:
Here, the combined conditional expression would increase i by one, but only if the condition on the left of && is true, because otherwise, the condition on the right-hand side (++i<n) is never evaluated.
The conditional operator evaluates an expression, returning one value if that expression evaluates to true, and a different one if the expression evaluates as false. Its syntax is:
condition ? result1 : result2
If condition is true, the entire expression evaluates to result1, and otherwise to result2.
For example:
7
In this example, a was 2, and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b (with a value of 7).
The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.
For example, the following code:
a = (b=3, b+2);
would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.
Bitwise operators modify variables considering the bit patterns that represent the values they store.
operator | asm equivalent | description |
---|---|---|
& | AND | Bitwise AND |
| | OR | Bitwise inclusive OR |
^ | XOR | Bitwise exclusive OR |
~ | NOT | Unary complement (bit inversion) |
<< | SHL | Shift bits left |
>> | SHR | Shift bits right |
Type casting operators allow to convert a value of a given type to another type. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):
The previous code converts the floating-point number 3.14 to an integer value (3); the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is to use the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses:
Both ways of casting types are valid in C++.
This operator accepts one parameter, which can be either a type or a variable, and returns the size in bytes of that type or object:
Here, x is assigned the value 1, because char is a type with a size of one byte.
The value returned by sizeof is a compile-time constant, so it is always determined before program execution.
Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the specifics for object-oriented programming.
A single expression may have multiple operators. For example:
In C++, the above expression always assigns 6 to variable x, because the % operator has a higher precedence than the + operator, and is always evaluated before. Parts of the expressions can be enclosed in parenthesis to override this precedence order, or to make explicitly clear the intended effect. Notice the difference:
From greatest to smallest priority, C++ operators are evaluated in the following order:
Level | Precedence group | Operator | Description | Grouping |
---|---|---|---|---|
1 | Scope | :: | scope qualifier | Left-to-right |
2 | Postfix (unary) | ++ -- | postfix increment / decrement | Left-to-right |
() | functional forms | |||
[] | subscript | |||
. -> | member access | |||
3 | Prefix (unary) | ++ -- | prefix increment / decrement | Right-to-left |
~ ! | bitwise NOT / logical NOT | |||
+ - | unary prefix | |||
& * | reference / dereference | |||
new delete | allocation / deallocation | |||
sizeof | parameter pack | |||
(type) | C-style type-casting | |||
4 | Pointer-to-member | .* ->* | access pointer | Left-to-right |
5 | Arithmetic: scaling | * / % | multiply, divide, modulo | Left-to-right |
6 | Arithmetic: addition | + - | addition, subtraction | Left-to-right |
7 | Bitwise shift | << >> | shift left, shift right | Left-to-right |
8 | Relational | < > <= >= | comparison operators | Left-to-right |
9 | Equality | == != | equality / inequality | Left-to-right |
10 | And | & | bitwise AND | Left-to-right |
11 | Exclusive or | ^ | bitwise XOR | Left-to-right |
12 | Inclusive or | | | bitwise OR | Left-to-right |
13 | Conjunction | && | logical AND | Left-to-right |
14 | Disjunction | || | logical OR | Left-to-right |
15 | Assignment-level expressions | = *= /= %= += -= | assignment / compound assignment | Right-to-left |
?: | conditional operator | |||
16 | Sequencing | , | comma separator | Left-to-right |
When an expression has two operators with the same precedence level, grouping determines which one is evaluated first: either left-to-right or right-to-left.
The example programs of the previous sections provided little interaction with the user, if any at all. They simply printed simple values on screen, but the standard library provides many additional ways to interact with the user via its input/output features. This section will present a short introduction to some of the most useful.
C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen, the keyboard or a file. A stream is an entity where a program can either insert or extract characters to/from. There is no need to know details about the media associated to the stream or any of its internal specifications. All we need to know is that streams are a source/destination of characters, and that these characters are provided/accepted sequentially (i.e., one after another).
The standard library defines a handful of stream objects that can be used to access what are considered the standard sources and destinations of characters by the environment where the program runs:
stream | description |
---|---|
cin | standard input stream |
cout | standard output stream |
cerr | standard error (output) stream |
clog | standard logging (output) stream |
We are going to see in more detail only cout and cin (the standard output and input streams); cerr and clog are also output streams, so they essentially work like cout, with the only difference being that they identify streams for specific purposes: error messages and logging; which, in many cases, in most environment setups, they actually do the exact same thing: they print on screen, although they can also be individually redirected.
On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.
For formatted output operations, cout is used together with the insertion operator, which is written as << (i.e., two "less than" signs).
The << operator inserts the data that follows it into the stream that precedes it. In the examples above, it inserted the literal string Output sentence, the number 120, and the value of variable x into the standard output stream cout. Notice that the sentence in the first statement is enclosed in double quotes (") because it is a string literal, while in the last one, x is not. The double quoting is what makes the difference; when the text is enclosed between them, the text is printed literally; when they are not, the text is interpreted as the identifier of a variable, and its value is printed instead. For example, these two sentences have very different results:
Multiple insertion operations (<<) may be chained in a single statement:
This last statement would print the text This is a single C++ statement. Chaining insertions is especially useful to mix literals and variables in a single statement:
Assuming the age variable contains the value 24 and the zipcode variable contains 90064, the output of the previous statement would be: I am 24 years old and my zipcode is 90064 What cout does not do automatically is add line breaks at the end, unless instructed to do so. For example, take the following two statements inserting into cout: cout << "This is a sentence."; cout << "This is another sentence."; The output would be in a single line, without any line breaks in between. Something like: This is a sentence.This is another sentence. To insert a line break, a new-line character shall be inserted at the exact position the line should be broken. In C++, a new-line character can be specified as \n (i.e., a backslash character followed by a lowercase n). For example:
This produces the following output:
First sentence.
Second sentence.
Third sentence.
Alternatively, the endl manipulator can also be used to break lines. For example:
This would print:
First sentence.
Second sentence.
The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it also has an additional behavior: the stream's buffer (if any) is flushed, which means that the output is requested to be physically written to the device, if it wasn't already. This affects mainly fully buffered streams, and cout is (generally) not a fully buffered stream. Still, it is generally a good idea to use endl only when flushing the stream would be a feature and '\n' when it would not. Bear in mind that a flushing operation incurs a certain overhead, and on some devices it may produce a delay.
In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin.
For formatted input operations, cin is used together with the extraction operator, which is written as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the extracted data is stored. For example:
The first statement declares a variable of type int called age, and the second extracts from cin a value to be stored in it. This operation makes the program wait for input from cin; generally, this means that the program will wait for the user to enter some sequence with the keyboard. In this case, note that the characters introduced using the keyboard are only transmitted to the program when the ENTER (or RETURN) key is pressed. Once the statement with the extraction operation on cin is reached, the program will wait for as long as needed until some input is introduced.
The extraction operation on cin uses the type of the variable after the >> operator to determine how it interprets the characters read from the input; if it is an integer, the format expected is a series of digits, if a string a sequence of characters, etc.
As you can see, extracting from cin seems to make the task of getting input from the standard input pretty simple and straightforward. But this method also has a big drawback. What happens in the example above if the user enters something else that cannot be interpreted as an integer? Well, in this case, the extraction operation fails. And this, by default, lets the program continue without setting a value for variable i, producing undetermined results if the value of i is used later.
This is very poor program behavior. Most programs are expected to behave in an expected manner no matter what the user types, handling invalid values appropriately. Only very simple programs should rely on values extracted directly from cin without further checking. A little later we will see how stringstreams can be used to have better control over user input.
Extractions on cin can also be chained to request more than one datum in a single statement:
This is equivalent to:
In both cases, the user is expected to introduce two values, one for variable a, and another for variable b. Any kind of space is used to separate two consecutive input operations; this may either be a space, a tab, or a new-line character.
The extraction operator can be used on cin to get strings of characters in the same way as with fundamental data types:
However, cin extraction always considers spaces (whitespaces, tabs, new-line...) as terminating the value being extracted, and thus extracting a string means to always extract a single word, not a phrase or an entire sentence.
To get an entire line from cin, there exists a function, called getline, that takes the stream (cin) as first argument, and the string variable as second. For example:
What's your name? Homer Simpson
Hello Homer Simpson.
What is your favorite team? The Isotopes
I like The Isotopes too!
Notice how in both calls to getline, we used the same string identifier (mystr). What the program does in the second call is simply replace the previous content with the new one that is introduced.
The standard behavior that most users expect from a console program is that each time the program queries the user for input, the user introduces the field, and then presses ENTER (or RETURN). That is to say, input is generally expected to happen in terms of lines on console programs, and this can be achieved by using getline to obtain input from the user. Therefore, unless you have a strong reason not to, you should always use getline to get input in your console programs instead of extracting from cin.
The standard header <sstream> defines a type called stringstream that allows a string to be treated as a stream, and thus allowing extraction or insertion operations from/to strings in the same way as they are performed on cin and cout. This feature is most useful to convert strings to numerical values and vice versa. For example, in order to extract an integer from a string we can write:
This declares a string with initialized to a value of "1204", and a variable of type int. Then, the third line uses this variable to extract from a stringstream constructed from the string. This piece of code stores the numerical value 1204 in the variable called myint.
Enter price: 22.25 Enter quantity: 7 Total price: 155.75
In this example, we acquire numeric values from the standard input indirectly: Instead of extracting numeric values directly from cin, we get lines from it into a string object (mystr), and then we extract the values from this string into the variables price and quantity. Once these are numerical values, arithmetic operations can be performed on them, such as multiplying them to obtain a total price.
With this approach of getting entire lines and extracting their contents, we separate the process of getting user input from its interpretation as data, allowing the input process to be what the user expects, and at the same time gaining more control over the transformation of its content into useful data by the program.
A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon (;), and are executed in the same order in which they appear in a program.
But programs are not limited to a linear sequence of statements. During its process, a program may repeat segments of code, or take decisions and bifurcate. For that purpose, C++ provides flow control statements that serve to specify what has to be done by our program, when, and under which circumstances.
Many of the flow control statements explained in this section require a generic (sub)statement as part of its syntax. This statement may either be a simple C++ statement, -such as a single instruction, terminated with a semicolon (;) - or a compound statement. A compound statement is a group of statements (each of them terminated by its own semicolon), but all grouped together in a block, enclosed in curly braces: {}:
{ statement1; statement2; statement3; }
The entire block is considered a single statement (composed itself of multiple substatements). Whenever a generic statement is part of the syntax of a flow control statement, this can either be a simple statement or a compound statement.
The if keyword is used to execute a statement or block, if, and only if, a condition is fulfilled. Its syntax is:
if (condition) statement
Here, condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is not executed (it is simply ignored), and the program continues right after the entire selection statement.
For example, the following code fragment prints the message (x is 100), only if the value stored in the x variable is indeed 100:
If x is not exactly 100, this statement is ignored, and nothing is printed.
If you want to include more than a single statement to be executed when the condition is fulfilled, these statements shall be enclosed in braces ({}), forming a block:
As usual, indentation and line breaks in the code have no effect, so the above code is equivalent to:
Selection statements with if can also specify what happens when the condition is not fulfilled, by using the else keyword to introduce an alternative statement. Its syntax is:
if (condition) statement1 else statement2
where statement1 is executed in case condition is true, and in case it is not, statement2 is executed.
For example:
This prints x is 100, if indeed x has a value of 100, but if it does not, and only if it does not, it prints x is not 100 instead.
Several if + else structures can be concatenated with the intention of checking a range of values. For example:
This prints whether x is positive, negative, or zero by concatenating two if-else structures. Again, it would have also been possible to execute more than a single statement per case by grouping them into blocks enclosed in braces: {}.
Loops repeat a statement a certain number of times, or while a condition is fulfilled. They are introduced by the keywords while, do, and for.
The simplest kind of loop is the while-loop. Its syntax is:
while (expression) statement
The while-loop simply repeats statement while expression is true. If, after any execution of statement, expression is no longer true, the loop ends, and the program continues right after the loop. For example, let's have a look at a countdown using a while-loop:
The first statement in main sets n to a value of 10. This is the first number in the countdown. Then the while-loop begins: if this value fulfills the condition n>0 (that n is greater than zero), then the block that follows the condition is executed, and repeated for as long as the condition (n>0) remains being true.
The whole process of the previous program can be interpreted according to the following script (beginning in main):
A thing to consider with while-loops is that the loop should end at some point, and thus the statement shall alter values checked in the condition in some way, so as to force it to become false at some point. Otherwise, the loop will continue looping forever. In this case, the loop includes --n, that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) false after a certain number of loop iterations. To be more specific, after 10 iterations, n becomes 0, making the condition no longer true, and ending the while-loop.
Note that the complexity of this loop is trivial for a computer, and so the whole countdown is performed instantly, without any practical delay between elements of the count (if interested, see sleep_for for a countdown example with delays).
The do-while loop
A very similar loop is the do-while loop, whose syntax is:
do statement while (condition);
It behaves like a while-loop, except that condition is evaluated after the execution of statement instead of before, guaranteeing at least one execution of statement, even if condition is never fulfilled. For example, the following example program echoes any text the user introduces until the user enters goodbye:
Enter text: hello
You entered: hello
Enter text: who's there?
You entered: who's there?
Enter text: goodbye
You entered: goodbye
The do-while loop is usually preferred over a while-loop when the statement needs to be executed at least once, such as when the condition that is checked to end of the loop is determined within the loop statement itself. In the previous example, the user input within the block is what will determine if the loop ends. And thus, even if the user wants to end the loop as soon as possible by entering goodbye, the block in the loop needs to be executed at least once to prompt for input, and the condition can, in fact, only be determined after it is executed.
The for loop
The for loop is designed to iterate a number of times. Its syntax is:
for (initialization; condition; increase) statement;
Like the while-loop, this loop repeats statement while condition is true. But, in addition, the for loop provides specific locations to contain an initialization and an increase expression, executed before the loop begins the first time, and after each iteration, respectively. Therefore, it is especially useful to use counter variables as condition.
It works in the following way:
Here is the countdown example using a for loop:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
The three fields in a for-loop are optional. They can be left empty, but in all cases the semicolon signs between them are required. For example, for (;n<10;) is a loop without initialization or increase (equivalent to a while-loop); and for (;n<10;++n) is a loop with increase, but no initialization (maybe because the variable was already initialized before the loop). A loop with no condition is equivalent to a loop with true as condition (i.e., an infinite loop).
Because each of the fields is executed in a particular time in the life cycle of a loop, it may be useful to execute more than a single expression as any of initialization, condition, or statement. Unfortunately, these are not statements, but rather, simple expressions, and thus cannot be replaced by a block. As expressions, they can, however, make use of the comma operator (,): This operator is an expression separator, and can separate multiple expressions where only one is generally expected. For example, using it, it would be possible for a for loop to handle two counter variables, initializing and increasing both:
This loop will execute 50 times if neither n or i are modified within the loop:
n starts with a value of 0, and i with 100, the condition is n!=i (i.e., that n is not equal to i). Because n is increased by one, and i decreased by one on each iteration, the loop's condition will become false after the 50th iteration, when both n and i are equal to 50.
Range-based for loop
The for-loop has another syntax, which is used exclusively with ranges:
for ( declaration : range ) statement;
This kind of for loop iterates over all the elements in range, where declaration declares some variable able to take the value of an element in this range. Ranges are sequences of elements, including arrays, containers, and any other type supporting the functions begin and end; Most of these types have not yet been introduced in this tutorial, but we are already acquainted with at least one kind of range: strings, which are sequences of characters.
An example of range-based for loop using strings:
[H][e][l][l][o][!]
Note how what precedes the colon (:) in the for loop is the declaration of a char variable (the elements in a string are of type char). We then use this variable, c, in the statement block to represent the value of each of the elements in the range.
This loop is automatic and does not require the explicit declaration of any counter variable.
Range based loops usually also make use of type deduction for the type of the elements with auto. Typically, the range-based loop above can also be written as:
Here, the type of c is automatically deduced as the type of the elements in str.
Jump statements allow altering the flow of a program by performing jumps to specific locations.
The break statement
break leaves a loop, even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, let's stop the countdown before its natural end:
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
The continue statementThe continue statement causes the program to skip the rest of the loop in the current iteration, as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, let's skip number 5 in our countdown:
10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!
The goto statementgoto allows to make an absolute jump to another point in the program. This unconditional jump ignores nesting levels, and does not cause any automatic stack unwinding. Therefore, it is a feature to use with care, and preferably within the same block of statements, especially in the presence of local variables.
The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).
goto is generally deemed a low-level feature, with no particular use cases in modern higher-level programming paradigms generally used with C++. But, just as an example, here is a version of our countdown loop using goto:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
The syntax of the switch statement is a bit peculiar. Its purpose is to check for a value among a number of possible constant expressions. It is something similar to concatenating if-else statements, but limited to constant expressions. Its most typical syntax is:
It works in the following way: switch evaluates expression and checks if it is equivalent to constant1; if it is, it executes group-of-statements-1 until it finds the break statement. When it finds this break statement, the program jumps to the end of the entire switch statement (the closing brace).
If expression was not equal to constant1, it is then checked against constant2. If it is equal to this, it executes group-of-statements-2 until a break is found, when it jumps to the end of the switch.
Finally, if the value of expression did not match any of the previously specified constants (there may be any number of these), the program executes the statements included after the default: label, if it exists (since it is optional).
Both of the following code fragments have the same behavior, demonstrating the if-else equivalent of a switch statement:
switch example | if-else equivalent |
---|---|
|
|
The switch statement has a somewhat peculiar syntax inherited from the early times of the first C compilers, because it uses labels instead of blocks. In the most typical use (shown above), this means that break statements are needed after each group of statements for a particular label. If break is not included, all statements following the case (including those under any other labels) are also executed, until the end of the switch block or a jump statement (such as break) is reached.
If the example above lacked the break statement after the first group for case one, the program would not jump automatically to the end of the switch block after printing x is 1, and would instead continue executing the statements in case two (thus printing also x is 2). It would then continue doing so until a break statement is encountered, or the end of the switch block. This makes unnecessary to enclose the statements for each case in braces {}, and can also be useful to execute the same group of statements for different possible values. For example:
Notice that switch is limited to compare its evaluated expression against labels that are constant expressions. It is not possible to use variables as labels or ranges, because they are not valid C++ constant expressions.
Functions allow to structure programs in segments of code to perform individual tasks.
In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is:
type name ( parameter1, parameter2, ...) { statements }
Where:
- type is the type of the value returned by the function.
- name is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example: int x), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from.
- statements is the function's body. It is a block of statements surrounded by braces { } that specify what the function actually does.
Let's have a look at an example:
The result is 8
This program is divided in two functions: addition and main. Remember that no matter the order in which they are defined, a C++ program always starts by calling main. In fact, main is the only function called automatically, and the code in any other function is only executed if its function is called from main (directly or indirectly).
In the example above, main begins by declaring the variable z of type int, and right after that, it performs the first function call: it calls addition. The call to a function follows a structure very similar to its declaration. In the example above, the call to addition can be compared to its definition just a few lines earlier:
The parameters in the function declaration have a clear correspondence to the arguments passed in the function call. The call passes two values, 5 and 3, to the function; these correspond to the parameters a and b, declared for function addition.
At the point at which the function is called from within main, the control is passed to function addition: here, execution of main is stopped, and will only resume once the addition function ends. At the moment of the function call, the value of both arguments (5 and 3) are copied to the local variables int a and int b within the function.
Then, inside addition, another local variable is declared (int r), and by means of the expression r=a+b, the result of a plus b is assigned to r; which, for this case, where a is 5 and b is 3, means that 8 is assigned to r.
The final statement within the function:
return r;
Ends function addition, and returns the control back to the point where the function was called; in this case: to function main. At this precise moment, the program resumes its course on main returning exactly at the same point at which it was interrupted by the call to addition. But additionally, because addition has a return type, the call is evaluated as having a value, and this value is the value specified in the return statement that ended addition: in this particular case, the value of the local variable r, which at the moment of the return statement had a value of 8.
Therefore, the call to addition is an expression with the value returned by the function, and in this case, that value, 8, is assigned to z. It is as if the entire function call (addition(5,3)) was replaced by the value it returns (i.e., 8).
Then main simply prints this value by calling:
cout << "The result is " << z;
A function can actually be called multiple times within a program, and its argument is naturally not limited just to literals:
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6
Similar to the addition function in the previous example, this example defines a subtract function, that simply returns the difference between its two parameters. This time, main calls this function several times, demonstrating more possible ways in which a function can be called.
Let's examine each of these calls, bearing in mind that each function call is itself an expression that is evaluated as the value it returns. Again, you can think of it as if the function call was itself replaced by the returned value:
If we replace the function call by the value it returns (i.e., 5), we would have:
With the same procedure, we could interpret:
as:
since 5 is the value returned by subtraction (7,2).
In the case of:
The arguments passed to subtraction are variables instead of literals. That is also valid, and works fine. The function is called with the values x and y have at the moment of the call: 5 and 3 respectively, returning 2 as result.
The fourth call is again similar:
The only addition being that now the function call is also an operand of an addition operation. Again, the result is the same as if the function call was replaced by its result: 6. Note, that thanks to the commutative property of additions, the above can also be written as:
With exactly the same result. Note also that the semicolon does not necessarily go after the function call, but, as always, at the end of the whole statement. Again, the logic behind may be easily seen again by replacing the function calls by their returned value:
he syntax shown above for functions:
type name ( argument1, argument2 ...) { statements }
Requires the declaration to begin with a type. This is the type of the value returned by the function. But what if the function does not need to return a value? In this case, the type to be used is void, which is a special type to represent the absence of value. For example, a function that simply prints a message may not need to return any value:
I'm a function!
void can also be used in the function's parameter list to explicitly specify that the function takes no actual parameters when called. For example, printmessage could have been declared as:
In C++, an empty parameter list can be used instead of void with same meaning, but the use of void in the argument list was popularized by the C language, where this is a requirement.
Something that in no case is optional are the parentheses that follow the function name, neither in its declaration nor when calling it. And even when the function takes no parameters, at least an empty pair of parentheses shall always be appended to the function name. See how printmessage was called in an earlier example:
printmessage ();
The parentheses are what differentiate functions from other kinds of declarations or statements. The following would not call the function:
printmessage;
You may have noticed that the return type of main is int, but most examples in this and earlier chapters did not actually return any value from main.
Well, there is a catch: If the execution of main ends normally without encountering a return statement the compiler assumes the function ends with an implicit return statement:
Note that this only applies to function main for historical reasons. All other functions with a return type shall end with a proper return statement that includes a return value, even if this is never used.
When main returns zero (either implicitly or explicitly), it is interpreted by the environment as that the program ended successfully. Other values may be returned by main, and some environments give access to that value to the caller in some way, although this behavior is not required nor necessarily portable between platforms. The values for main that are guaranteed to be interpreted in the same way on all platforms are:
value | description |
---|---|
0 | The program was successful |
EXIT_SUCCESS | The program was successful (same as above). This value is defined in header <cstdlib> . |
EXIT_FAILURE | The program failed. This value is defined in header <cstdlib> . |
Because the implicit return 0; statement for main is a tricky exception, some authors consider it good practice to explicitly write the statement.
In the functions seen earlier, arguments have always been passed by value. This means that, when calling a function, what is passed to the function are the values of these arguments on the moment of the call, which are copied into the variables represented by the function parameters. For example, take:
In this case, function addition is passed 5 and 3, which are copies of the values of x and y, respectively. These values (5 and 3) are used to initialize the variables set as parameters in the function's definition, but any modification of these variables within the function has no effect on the values of the variables x and y outside it, because x and y were themselves not passed to the function on the call, but only copies of their values at that moment.
In certain cases, though, it may be useful to access an external variable from within a function. To do that, arguments can be passed by reference, instead of by value. For example, the function duplicate in this code duplicates the value of its three arguments, causing the variables used as arguments to actually be modified by the call:
x=2, y=6, z=14
To gain access to its arguments, the function declares its parameters as references. In C++, references are indicated with an ampersand (&) following the parameter type, as in the parameters taken by duplicate in the example above.
When a variable is passed by reference, what is passed is no longer a copy, but the variable itself, the variable identified by the function parameter, becomes somehow associated with the argument passed to the function, and any modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call.
In fact, a, b, and c become aliases of the arguments passed on the function call (x, y, and z) and any change on a within the function is actually modifying variable x outside the function. Any change on b modifies y, and any change on c modifies z. That is why when, in the example, function duplicate modifies the values of variables a, b, and c, the values of x, y, and z are affected.
If instead of defining duplicate as:
Was it to be defined without the ampersand signs as:
The variables would not be passed by reference, but by value, creating instead copies of their values. In this case, the output of the program would have been the values of x, y, and z without being modified (i.e., 1, 3, and 7).
Calling a function with parameters taken by value causes copies of the values to be made. This is a relatively inexpensive operation for fundamental types such as int, but if the parameter is of a large compound type, it may result on certain overhead. For example, consider the following function:
This function takes two strings as parameters (by value), and returns the result of concatenating them. By passing the arguments by value, the function forces a and b to be copies of the arguments passed to the function when it is called. And if these are long strings, it may mean copying large quantities of data just for the function call.
But this copy can be avoided altogether if both parameters are made references:
Arguments by reference do not require a copy. The function operates directly on (aliases of) the strings passed as arguments, and, at most, it might mean the transfer of certain pointers to the function. In this regard, the version of concatenate taking references is more efficient than the version taking values, since it does not need to copy expensive-to-copy strings.
On the flip side, functions with reference parameters are generally perceived as functions that modify the arguments passed, because that is why reference parameters are actually for.
The solution is for the function to guarantee that its reference parameters are not going to be modified by this function. This can be done by qualifying the parameters as constant:
By qualifying them as const, the function is forbidden to modify the values of neither a nor b, but can actually access their values as references (aliases of the arguments), without having to make actual copies of the strings.
Therefore, const references provide functionality similar to passing arguments by value, but with an increased efficiency for parameters of large types. That is why they are extremely popular in C++ for arguments of compound types. Note though, that for most fundamental types, there is no noticeable difference in efficiency, and in some cases, const references may even be less efficient!
Calling a function generally causes a certain overhead (stacking arguments, jumps, etc...), and thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.
Preceding a function declaration with the inline specifier informs the compiler that inline expansion is preferred over the usual function call mechanism for a specific function. This does not change at all the behavior of a function, but is merely used to suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call.
For example, the concatenate function above may be declared inline as:
This informs the compiler that when concatenate is called, the program prefers the function to be expanded inline, instead of performing a regular call. inline is only specified in the function declaration, not when it is called.
Note that most compilers already optimize code to generate inline functions when they see an opportunity to improve efficiency, even if not explicitly marked with the inline specifier. Therefore, this specifier merely indicates the compiler that inline is preferred for this function, although the compiler is free to not inline it, and optimize otherwise. In C++, optimization is a task delegated to the compiler, which is free to generate any code for as long as the resulting behavior is the one specified by the code.
In C++, functions can also have optional parameters, for which no arguments are required in the call, in such a way that, for example, a function with three parameters may be called with only two. For this, the function shall include a default value for its last parameter, which is used by the function when called with fewer arguments. For example:
6
5
In this example, there are two calls to function divide. In the first one:
divide (12)
The call only passes one argument to the function, even though the function has two parameters. In this case, the function assumes the second parameter to be 2 (notice the function definition, which declares its second parameter as int b=2). Therefore, the result is 6.
In the second call:
divide (20,4)
The call passes two arguments to the function. Therefore, the default value for b (int b=2) is ignored, and b takes the value passed as argument, that is 4, yielding a result of 5.
In C++, identifiers can only be used in expressions once they have been declared. For example, some variable x cannot be used before being declared with a statement, such as:
int x;
The same applies to functions. Functions cannot be called before they are declared. That is why, in all the previous examples of functions, the functions were always defined before the main function, which is the function from where the other functions were called. If main were defined before the other functions, this would break the rule that functions shall be declared before being used, and thus would not compile.
The prototype of a function can be declared without actually defining the function completely, giving just enough details to allow the types involved in a function call to be known. Naturally, the function shall be defined somewhere else, like later in the code. But at least, once declared like this, it can already be called.
The declaration shall include all types involved (the return type and the type of its arguments), using the same syntax as used in the definition of the function, but replacing the body of the function (the block of statements) with an ending semicolon.
The parameter list does not need to include the parameter names, but only their types. Parameter names can nevertheless be specified, but they are optional, and do not need to necessarily match those in the function definition. For example, a function called protofunction with two int parameters can be declared with either of these statements:
Anyway, including a name for each parameter always improves legibility of the declaration.
Please, enter number (0 to exit): 9
It is odd.
Please, enter number (0 to exit): 6
It is even.
Please, enter number (0 to exit): 1030
It is even.
Please, enter number (0 to exit): 0
It is even.
This example is indeed not an example of efficiency. You can probably write yourself a version of this program with half the lines of code. Anyway, this example illustrates how functions can be declared before its definition:
The following lines:
Declare the prototype of the functions. They already contain all what is necessary to call them, their name, the types of their argument, and their return type (void in this case). With these prototype declarations in place, they can be called before they are entirely defined, allowing for example, to place the function from where they are called (main) before the actual definition of these functions.
But declaring functions before being defined is not only useful to reorganize the order of functions within the code. In some cases, such as in this particular case, at least one of the declarations is required, because odd and even are mutually called; there is a call to even in odd and a call to odd in even. And, therefore, there is no way to structure the code so that odd is defined before even, and even before odd.
Recursivity is the property that functions have to be called by themselves. It is useful for some tasks, such as sorting elements, or calculating the factorial of numbers. For example, in order to obtain the factorial of a number (n!) the mathematical formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1
More concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ could be:
Notice how in function factorial we included a call to itself, but only if the argument passed was greater than 1, since, otherwise, the function would perform an infinite recursive loop, in which once it arrived to 0, it would continue multiplying by all the negative numbers (probably provoking a stack overflow at some point during runtime).
In C++, two different functions can have the same name if their parameters are different; either because they have a different number of parameters, or because any of their parameters are of a different type. For example:
In this example, there are two functions called operate, but one of them has two parameters of type int, while the other has them of type double. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called. If it is called with two int arguments, it calls to the function that has two int parameters, and if it is called with two doubles, it calls the one with two doubles.
In this example, both functions have quite different behaviors, the int version multiplies its arguments, while the double version divides them. This is generally not a good idea. Two functions with the same name are generally expected to have -at least- a similar behavior, but this example demonstrates that is entirely possible for them not to. Two overloaded functions (i.e., two functions with the same name) have entirely different definitions; they are, for all purposes, different functions, that only happen to have the same name.
Note that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type.
Overloaded functions may have the same definition. For example:
Here, sum is overloaded with different parameter types, but with the exact same body.
The function sum could be overloaded for a lot of types, and it could make sense for all of them to have the same body. For cases such as this, C++ has the ability to define functions with generic types, known as function templates. Defining a function template follows the same syntax as a regular function, except that it is preceded by the template keyword and a series of template parameters enclosed in angle-brackets <>:<br>
template <template-parameters> function-declaration
The template parameters are a series of parameters separated by commas. These parameters can be generic template types by specifying either the class or typename keyword followed by an identifier. This identifier can then be used in the function declaration as if it was a regular type. For example, a generic sum function could be defined as:
It makes no difference whether the generic type is specified with keyword class or keyword typename in the template argument list (they are 100% synonyms in template declarations).
In the code above, declaring SomeType (a generic type within the template parameters enclosed in angle-brackets) allows SomeType to be used anywhere in the function definition, just as any other type; it can be used as the type for parameters, as return type, or to declare new variables of this type. In all cases, it represents a generic type that will be determined on the moment the template is instantiated.
Instantiating a template is applying the template to create a function using particular types or values for its template parameters. This is done by calling the function template, with the same syntax as calling a regular function, but specifying the template arguments enclosed in angle brackets:
name <template-arguments> (function-arguments)
For example, the sum function template defined above can be called with:
x = sum<int>(10,20);
The function sum<int> is just one of the possible instantiations of function template sum. In this case, by using int as template argument in the call, the compiler automatically instantiates a version of sum where each occurrence of SomeType is replaced by int, as if it was defined as:
Let's see an actual example:
In this case, we have used T as the template parameter name, instead of SomeType. It makes no difference, and T is actually a quite common template parameter name for generic types.
In the example above, we used the function template sum twice. The first time with arguments of type int, and the second one with arguments of type double. The compiler has instantiated and then called each time the appropriate version of the function.
Note also how T is also used to declare a local variable of that (generic) type within sum:
T result;
Therefore, result will be a variable of the same type as the parameters a and b, and as the type returned by the function. In this specific case where the generic type T is used as a parameter for sum, the compiler is even able to deduce the data type automatically without having to explicitly specify it within angle brackets. Therefore, instead of explicitly specifying the template arguments with:
It is possible to instead simply write:
without the type enclosed in angle brackets. Naturally, for that, the type shall be unambiguous. If sum is called with arguments of different types, the compiler may not be able to deduce the type of T automatically.
Templates are a powerful and versatile feature. They can have multiple template parameters, and the function can still use regular non-templated types. For example:
Note that this example uses automatic template parameter deduction in the call to are_equal:
are_equal(10,10.0)
Is equivalent to:
are_equal<int,double>(10,10.0)
There is no ambiguity possible because numerical literals are always of a specific type: Unless otherwise specified with a suffix, integer literals always produce values of type int, and floating-point literals always produce values of type double. Therefore 10 has always type int and 10.0 has always type double.
The template parameters can not only include types introduced by class or typename, but can also include expressions of a particular type:
20
30
The second argument of the fixed_multiply function template is of type int. It just looks like a regular function parameter, and can actually be used just like one.
But there exists a major difference: the value of template parameters is determined on compile-time to generate a different instantiation of the function fixed_multiply, and thus the value of that argument is never passed during runtime: The two calls to fixed_multiply in main essentially call two versions of the function: one that always multiplies by two, and one that always multiplies by three. For that same reason, the second template argument needs to be a constant expression (it cannot be passed a variable).
Named entities, such as variables, functions, and compound types need to be declared before being used in C++. The point in the program where this declaration happens influences its visibility:
An entity declared outside any block has global scope, meaning that its name is valid anywhere in the code. While an entity declared within a block, such as a function or a selective statement, has block scope, and is only visible within the specific block in which it is declared, but not outside it.
Variables with block scope are known as local variables.
For example, a variable declared in the body of a function is a local variable that extends until the end of the the function (i.e., until the brace } that closes the function definition), but not outside it:
In each scope, a name can only represent one entity. For example, there cannot be two variables with the same name in the same scope:
The visibility of an entity with block scope extends until the end of the block, including inner blocks. Nevertheless, an inner block, because it is a different block, can re-utilize a name existing in an outer scope to refer to a different entity; in this case, the name will refer to a different entity only within the inner block, hiding the entity it names outside. While outside it, it will still refer to the original entity. For example:
Note that y is not hidden in the inner block, and thus accessing y still accesses the outer variable.
Variables declared in declarations that introduce a block, such as function parameters and variables declared in loops and conditions (such as those declared on a for or an if) are local to the block they introduce.
Only one entity can exist with a particular name in a particular scope. This is seldom a problem for local names, since blocks tend to be relatively short, and names have particular purposes within them, such as naming a counter variable, an argument, etc...
But non-local names bring more possibilities for name collision, especially considering that libraries may declare many functions, types, and variables, neither of them local in nature, and some of them very generic.
Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.
The syntax to declare a namespaces is:
Where identifier is any valid identifier and named_entities is the set of variables, types and functions that are included within the namespace. For example:
In this case, the variables a and b are normal variables declared within a namespace called myNamespace.
These variables can be accessed from within their namespace normally, with their identifier (either a or b), but if accessed from outside the myNamespace namespace they have to be properly qualified with the scope operator ::. For example, to access the previous variables from outside myNamespace they should be qualified like:
Namespaces are particularly useful to avoid name collisions. For example:
5
6.2832
3.1416
In this case, there are two functions with the same name: value. One is defined within the namespace foo, and the other one in bar. No redefinition errors happen thanks to namespaces. Notice also how pi is accessed in an unqualified manner from within namespace bar (just as pi), while it is again accessed in main, but here it needs to be qualified as bar::pi.
Namespaces can be split: Two segments of a code can be declared in the same namespace:
This declares three variables: a and c are in namespace foo, while b is in namespace bar. Namespaces can even extend across different translation units (i.e., across different files of source code).
The keyword using introduces a name into the current declarative region (such as a block), thus avoiding the need to qualify the name. For example:
5
2.7183
10
3.1416
Notice how in main, the variable x (without any name qualifier) refers to first::x, whereas y refers to second::y, just as specified by the using declarations. The variables first::y and second::x can still be accessed, but require fully qualified names.
The keyword using can also be used as a directive to introduce an entire namespace:
5
10
3.1416
2.7183
In this case, by declaring that we were using namespace first, all direct uses of x and y without name qualifiers were also looked up in namespace first.
using and using namespace have validity only in the same block in which they are stated or in the entire source code file if they are used directly in the global scope. For example, it would be possible to first use the objects of one namespace and then those of another one by splitting the code in different blocks:
5
3.1416
Existing namespaces can be aliased with new names, with the following syntax:
namespace new_name = current_name;
All the entities (variables, types, constants, and functions) of the standard C++ library are declared within the std namespace. Most examples in these tutorials, in fact, include the following line:
using namespace std;
This introduces direct visibility of all the names of the std namespace into the code. This is done in these tutorials to facilitate comprehension and shorten the length of the examples, but many programmers prefer to qualify each of the elements of the standard library used in their programs. For example, instead of:
cout << "Hello world!";
It is common to instead see:
std::cout << "Hello world!";
Whether the elements in the std namespace are introduced with using declarations or are fully qualified on every use does not change the behavior or efficiency of the resulting program in any way. It is mostly a matter of style preference, although for projects mixing libraries, explicit qualification tends to be preferred.
Whether the elements in the std namespace are introduced with using declarations or are fully qualified on every use does not change the behavior or efficiency of the resulting program in any way. It is mostly a matter of style preference, although for projects mixing libraries, explicit qualification tends to be preferred.
The storage for variables with global or namespace scope is allocated for the entire duration of the program. This is known as static storage, and it contrasts with the storage for local variables (those declared within a block). These use what is known as automatic storage. The storage for local variables is only available during the block in which they are declared; after that, that same storage may be used for a local variable of some other function, or used otherwise.
But there is another substantial difference between variables with static storage and variables with automatic storage:
- Variables with static storage (such as global variables) that are not explicitly initialized are automatically initialized to zeroes.
- Variables with automatic storage (such as local variables) that are not explicitly initialized are left uninitialized, and thus have an undetermined value.
For example:
0
4285838
The actual output may vary, but only the value of x is guaranteed to be zero. y can actually contain just about any value (including zero).
An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
That means that, for example, five values of type int can be declared as an array without having to declare 5 different variables (each with its own identifier). Instead, using an array, the five int values are stored in contiguous memory locations, and all five can be accessed using the same identifier, with the proper index.
For example, an array containing 5 integer values of type int called foo could be represented as:
where each blank panel represents an element of the array. In this case, these are values of type int. These elements are numbered from 0 to 4, being 0 the first and 4 the last; In C++, the first element in an array is always numbered with a zero (not a one), no matter its length.
Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:
type name [elements];
where type is a valid type (such as int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies the length of the array in terms of the number of elements.
Therefore, the foo array, with five elements of type int, can be declared as:
int foo [5];
NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.
By default, regular arrays of local scope (for example, those declared within a function) are left uninitialized. This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.
But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example:
int foo [5] = { 16, 2, 77, 40, 12071 };
This statement declares an array that can be represented like this:
The number of values between braces {} shall not be greater than the number of elements in the array. For example, in the example above, foo was declared having 5 elements (as specified by the number enclosed in square brackets, []), and the braces {} contained exactly 5 values, one for each element. If declared with less, the remaining elements are set to their default values (which for fundamental types, means they are filled with zeroes). For example:
int bar [5] = { 10, 20, 30 };
Will create an array like this:
The initializer can even have no values, just the braces:
int baz [5] = { };
This creates an array of five int values, each initialized with a value of zero:
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty []. In this case, the compiler will assume automatically a size for the array that matches the number of values included between the braces {}:
int foo [] = { 16, 2, 77, 40, 12071 };
After this declaration, array foo would be 5 int long, since we have provided 5 initialization values.
Finally, the evolution of C++ has led to the adoption of universal initialization also for arrays. Therefore, there is no longer need for the equal sign between the declaration and the initializer. Both these statements are equivalent:
int foo[] = { 10, 20, 30 };
int foo[] { 10, 20, 30 };
Static arrays, and those declared directly in a namespace (outside any function), are always initialized. If no explicit initializer is specified, all the elements are default-initialized (with zeroes, for fundamental types).
The values of any of the elements in an array can be accessed just like the value of a regular variable of the same type. The syntax is:
name[index]
Following the previous examples in which foo had 5 elements and each of those elements was of type int, the name which can be used to refer to each element is the following:
For example, the following statement stores the value 75 in the third element of foo:
foo [2] = 75;
and, for example, the following copies the value of the third element of foo to a variable called x:
x = foo[2];
Therefore, the expression foo[2] is itself a variable of type int.
Notice that the third element of foo is specified foo[2], since the first one is foo[0], the second one is foo[1], and therefore, the third one is foo[2]. By this same reason, its last element is foo[4]. Therefore, if we write foo[5], we would be accessing the sixth element of foo, and therefore actually exceeding the size of the array.
In C++, it is syntactically correct to exceed the valid range of indices for an array. This can create problems, since accessing out-of-range elements do not cause errors on compilation, but can cause errors on runtime. The reason for this being allowed will be seen in a later chapter when pointers are introduced.
At this point, it is important to be able to clearly distinguish between the two uses that brackets [] have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements when they are accessed. Do not confuse these two possible uses of brackets [] with arrays.
12206
Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a two-dimensional table made of elements, all of them of a same uniform data type.
jimmy represents a bidimensional array of 3 per 5 elements of type int. The C++ syntax for this is:
int jimmy [3][5];
and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be:
jimmy[1][3]
(remember that array indices always begin with zero).
Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. Although be careful: the amount of memory needed for an array increases exponentially with each dimension. For example:
char century [100][365][24][60][60];
declares an array with an element of type char for each second in a century. This amounts to more than 3 billion char! So this declaration would consume more than 3 gigabytes of memory!
At the end, multidimensional arrays are just an abstraction for programmers, since the same results can be achieved with a simple array, by multiplying its indices:
int jimmy [3][5]; // is equivalent to
int jimmy [15]; // (3 * 5 = 15)
With the only difference that with multidimensional arrays, the compiler automatically remembers the depth of each imaginary dimension. The following two pieces of code produce the exact same result, but one uses a bidimensional array while the other uses a simple array:
multidimensional array | pseudo-multidimensional array |
---|---|
|
|
None of the two code snippets above produce any output on the screen, but both assign values to the memory block called jimmy in the following way:
Note that the code uses defined constants for the width and height, instead of using directly their numerical values. This gives the code a better readability, and allows changes in the code to be made easily in one place.
At some point, we may need to pass an array to a function as a parameter. In C++, it is not possible to pass the entire block of memory represented by an array to a function directly as an argument. But what can be passed instead is its address. In practice, this has almost the same effect, and it is a much faster and more efficient operation.
To accept an array as parameter for a function, the parameters can be declared as the array type, but with empty brackets, omitting the actual size of the array. For example:
void procedure (int arg[])
This function accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:
int myarray [40];
it would be enough to write a call like this:
procedure (myarray);
Here you have a complete example:
5 10 15
2 4 6 8 10
In the code above, the first parameter (int arg[]) accepts any array whose elements are of type int, whatever its length. For that reason, we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the array passed, without going out of range.
In a function declaration, it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:
base_type[][depth][depth]
For example, a function with a multidimensional array as argument could be:
void procedure (int myarray[][3][4])
Notice that the first brackets [] are left empty, while the following ones specify sizes for their respective dimensions. This is necessary in order for the compiler to be able to determine the depth of each additional dimension.
In a way, passing an array as argument always loses a dimension. The reason behind is that, for historical reasons, arrays cannot be directly copied, and thus what is really passed is a pointer. This is a common source of errors for novice programmers. Although a clear understanding of pointers, explained in a coming chapter, helps a lot.
The arrays explained above are directly implemented as a language feature, inherited from the C language. They are a great feature, but by restricting its copy and easily decay into pointers, they probably suffer from an excess of optimization.
To overcome some of these issues with language built-in arrays, C++ provides an alternative array type as a standard container. It is a type template (a class template, in fact) defined in header <array>.
Containers are a library feature that falls out of the scope of this tutorial, and thus the class will not be explained in detail here. Suffice it to say that they operate in a similar way to built-in arrays, except that they allow being copied (an actually expensive operation that copies the entire block of memory, and thus to use with care) and decay into pointers only when explicitly told to do so (by means of its member data).
Just as an example, these are two versions of the same example using the language built-in array described in this chapter, and the container in the library:
language built-in array | container library array |
---|---|
|
|
As you can see, both kinds of arrays use the same syntax to access its elements: myarray[i]. Other than that, the main differences lay on the declaration of the array, and the inclusion of an additional header for the library array. Notice also how it is easy to access the size of the library array.
The string class has been briefly introduced in an earlier chapter. It is a very powerful class to handle and manipulate strings of characters. However, because strings are, in fact, sequences of characters, we can represent them also as plain arrays of elements of a character type.
For example, the following array:
char foo [20];
is an array that can store up to 20 elements of type char. It can be represented as:
Therefore, this array has a capacity to store sequences of up to 20 characters. But this capacity does not need to be fully exhausted: the array can also accommodate shorter sequences. For example, at some point in a program, either the sequence "Hello" or the sequence "Merry Christmas" can be stored in foo, since both would fit in a sequence with a capacity for 20 characters.
By convention, the end of strings represented in character sequences is signaled by a special character: the null character, whose literal value can be written as '\0' (backslash, zero).
In this case, the array of 20 elements of type char called foo can be represented storing the character sequences "Hello" and "Merry Christmas" as:
Notice how after the content of the string itself, a null character ('\0') has been added in order to indicate the end of the sequence. The panels in gray color represent char elements with undetermined values.
Because arrays of characters are ordinary arrays, they follow the same rules as these. For example, to initialize an array of characters with some predetermined sequence of characters, we can do it just like any other array:
char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
The above declares an array of 6 elements of type char initialized with the characters that form the word "Hello" plus a null character '\0' at the end.
But arrays of character elements have another way to be initialized: using string literals directly.
In the expressions used in some examples in previous chapters, string literals have already shown up several times. These are specified by enclosing the text between double quotes ("). For example:
"the result is: "
This is a string literal, probably used in some earlier example.
Sequences of characters enclosed in double-quotes (") are literal constants. And their type is, in fact, a null-terminated array of characters. This means that string literals always have a null character ('\0') automatically appended at the end.
Therefore, the array of char elements called myword can be initialized with a null-terminated sequence of characters by either one of these two statements:
char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char myword[] = "Hello";
In both cases, the array of characters myword is declared with a size of 6 elements of type char: the 5 characters that compose the word "Hello", plus a final null character ('\0'), which specifies the end of the sequence and that, in the second case, when using double quotes (") it is appended automatically.
Please notice that here we are talking about initializing an array of characters at the moment it is being declared, and not about assigning values to them later (once they have already been declared). In fact, because string literals are regular arrays, they have the same restrictions as these, and cannot be assigned values.
Expressions (once myword has already been declared as above), such as:
myword = "Bye";
myword[] = "Bye";
would not be valid, like neither would be:
myword = { 'B', 'y', 'e', '\0' };
This is because arrays cannot be assigned values. Note, though, that each of its elements can be assigned a value individually. For example, this would be correct:
myword[0] = 'B';
myword[1] = 'y';
myword[2] = 'e';
myword[3] = '\0';
Plain arrays with null-terminated sequences of characters are the typical types used in the C language to represent strings (that is why they are also known as C-strings). In C++, even though the standard library defines a specific type for strings (class string), still, plain arrays with null-terminated sequences of characters (C-strings) are a natural way of representing strings in the language; in fact, string literals still always produce null-terminated character sequences, and not string objects.
In the standard library, both representations for strings (C-strings and library strings) coexist, and most functions requiring strings are overloaded to support both.
For example, cin and cout support null-terminated sequences directly, allowing them to be directly extracted from cin or inserted into cout, just like strings. For example:
What is your name? Homer
Where do you live? Greece
Hello, Homer from Greece!
In this example, both arrays of characters using null-terminated sequences and strings are used. They are quite interchangeable in their use together with cin and cout, but there is a notable difference in their declarations: arrays have a fixed size that needs to be specified either implicit or explicitly when declared; question1 has a size of exactly 20 characters (including the terminating null-characters) and answer1 has a size of 80 characters; while strings are simply strings, no size is specified. This is due to the fact that strings have a dynamic size determined during runtime, while the size of arrays is determined on compilation, before the program runs.
In any case, null-terminated character sequences and strings are easily transformed from one another:
Null-terminated character sequences can be transformed into strings implicitly, and strings can be transformed into null-terminated character sequences by using either of string's member functions c_str or data:
In earlier chapters, variables have been explained as locations in the computer's memory which can be accessed by their identifier (their name). This way, the program does not need to care about the physical address of the data in memory; it simply uses the identifier whenever it needs to refer to the variable.
For a C++ program, the memory of a computer is like a succession of memory cells, each one byte in size, and each with a unique address. These single-byte memory cells are ordered in a way that allows data representations larger than one byte to occupy memory cells that have consecutive addresses.
This way, each cell can be easily located in the memory by means of its unique address. For example, the memory cell with the address 1776 always follows immediately after the cell with address 1775 and precedes the one with 1777, and is exactly one thousand cells after 776 and exactly one thousand cells before 2776.
When a variable is declared, the memory needed to store its value is assigned a specific location in memory (its memory address). Generally, C++ programs do not actively decide the exact memory addresses where its variables are stored. Fortunately, that task is left to the environment where the program is run - generally, an operating system that decides the particular memory locations on runtime. However, it may be useful for a program to be able to obtain the address of a variable during runtime in order to access data cells that are at a certain position relative to it.
The address of a variable can be obtained by preceding the name of a variable with an ampersand sign (&), known as address-of operator. For example:
foo = &myvar;
This would assign the address of variable myvar to foo; by preceding the name of the variable myvar with the address-of operator (&), we are no longer assigning the content of the variable itself to foo, but its address.
The actual address of a variable in memory cannot be known before runtime, but let's assume, in order to help clarify some concepts, that myvar is placed during runtime in the memory address 1776.
In this case, consider the following code fragment:
myvar = 25;
foo = &myvar;
bar = myvar;
The values contained in each variable after the execution of this are shown in the following diagram:
First, we have assigned the value 25 to myvar (a variable whose address in memory we assumed to be 1776).
The second statement assigns foo the address of myvar, which we have assumed to be 1776.
Finally, the third statement, assigns the value contained in myvar to bar. This is a standard assignment operation, as already done many times in earlier chapters.
The main difference between the second and third statements is the appearance of the address-of operator (&).
The variable that stores the address of another variable (like foo in the previous example) is what in C++ is called a pointer. Pointers are a very powerful feature of the language that has many uses in lower level programming. A bit later, we will see how to declare and use pointers.
As just seen, a variable which stores the address of another variable is called a pointer. Pointers are said to "point to" the variable whose address they store.
An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator (*). The operator itself can be read as "value pointed to by".
Therefore, following with the values of the previous example, the following statement:
baz = *foo;
This could be read as: "baz equal to value pointed to by foo", and the statement would actually assign the value 25 to baz, since foo is 1776, and the value pointed to by 1776 (following the example above) would be 25.
It is important to clearly differentiate that foo refers to the value 1776, while *foo (with an asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25. Notice the difference of including or not including the dereference operator (I have added an explanatory comment of how each of these two expressions could be read):
The reference and dereference operators are thus complementary:
Thus, they have sort of opposite meanings: An address obtained with & can be dereferenced with *.
Earlier, we performed the following two assignment operations:
myvar = 25;
foo = &myvar;
Right after these two statements, all of the following expressions would give true as result:
myvar == 25
&myvar == 1776
foo == 1776
*foo == 25
The first expression is quite clear, considering that the assignment operation performed on myvar was myvar=25. The second one uses the address-of operator (&), which returns the address of myvar, which we assumed it to have a value of 1776. The third one is somewhat obvious, since the second expression was true and the assignment operation performed on foo was foo=&myvar. The fourth expression uses the dereference operator (*) that can be read as "value pointed to by", and the value pointed to by foo is indeed 25.
So, after all that, you may also infer that for as long as the address pointed to by foo remains unchanged, the following expression will also be true:
*foo == myvar
Due to the ability of a pointer to directly refer to the value that it points to, a pointer has different properties when it points to a char than when it points to an int or a float. Once dereferenced, the type needs to be known. And for that, the declaration of a pointer needs to include the data type the pointer is going to point to.
The declaration of pointers follows this syntax:
type * name;
where type is the data type pointed to by the pointer. This type is not the type of the pointer itself, but the type of the data the pointer points to. For example:
int * number;
char * character;
double * decimals;
These are three declarations of pointers. Each one is intended to point to a different data type, but, in fact, all of them are pointers and all of them are likely going to occupy the same amount of space in memory (the size in memory of a pointer depends on the platform where the program runs). Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an int, the second one to a char, and the last one to a double. Therefore, although these three example variables are all of them pointers, they actually have different types: int*, char*, and double* respectively, depending on the type they point to.
Note that the asterisk (*) used when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator seen a bit earlier, but which is also written with an asterisk (*). They are simply two different things represented with the same sign.
Let's see an example on pointers:
firstvalue is 10
secondvalue is 20
Notice that even though neither firstvalue nor secondvalue are directly set any value in the program, both end up with a value set indirectly through the use of mypointer. This is how it happens:
First, mypointer is assigned the address of firstvalue using the address-of operator (&). Then, the value pointed to by mypointer is assigned a value of 10. Because, at this moment, mypointer is pointing to the memory location of firstvalue, this in fact modifies the value of firstvalue.
In order to demonstrate that a pointer may point to different variables during its lifetime in a program, the example repeats the process with secondvalue and that same pointer, mypointer.
Here is an example a little bit more elaborated:
firstvalue is 10
secondvalue is 20
Each assignment operation includes a comment on how each line could be read: i.e., replacing ampersands (&) by "address of", and asterisks (*) by "value pointed to by".
Notice that there are expressions with pointers p1 and p2, both with and without the dereference operator (*). The meaning of an expression using the dereference operator (*) is very different from one that does not. When this operator precedes the pointer name, the expression refers to the value being pointed, while when a pointer name appears without this operator, it refers to the value of the pointer itself (i.e., the address of what the pointer is pointing to).
Another thing that may call your attention is the line:
int * p1, * p2;
This declares the two pointers used in the previous example. But notice that there is an asterisk (*) for each pointer, in order for both to have type int* (pointer to int). This is required due to the precedence rules. Note that if, instead, the code was:
int * p1, p2;
p1 would indeed be of type int*, but p2 would be of type int. Spaces do not matter at all for this purpose. But anyway, simply remembering to put one asterisk per pointer is enough for most pointer users interested in declaring multiple pointers per statement. Or even better: use a different statemet for each variable.
The concept of arrays is related to that of pointers. In fact, arrays work very much like pointers to their first elements, and, actually, an array can always be implicitly converted to the pointer of the proper type. For example, consider these two declarations:
int myarray [20];
int * mypointer;
The following assignment operation would be valid:
mypointer = myarray;
After that, mypointer and myarray would be equivalent and would have very similar properties. The main difference being that mypointer can be assigned a different address, whereas myarray can never be assigned anything, and will always represent the same block of 20 elements of type int. Therefore, the following assignment would not be valid:
myarray = mypointer;
Let's see an example that mixes arrays and pointers:
10, 20, 30, 40, 50,
Pointers and arrays support the same set of operations, with the same meaning for both. The main difference being that pointers can be assigned new addresses, while arrays cannot.
In the chapter about arrays, brackets ([]) were explained as specifying the index of an element of the array. Well, in fact these brackets are a dereferencing operator known as offset operator. They dereference the variable they follow just as * does, but they also add the number between brackets to the address being dereferenced. For example:
a[5] = 0; // a [offset of 5] = 0
*(a+5) = 0; // pointed to by (a+5) = 0
<p.These two expressions are equivalent and valid, not only if a is a pointer, but also if a is an array. Remember that if an array, its name can be used just like a pointer to its first element.
Pointers can be initialized to point to specific locations at the very moment they are defined:
int myvar;
int * myptr = &myvar;
The resulting state of variables after this code is the same as after:
int myvar;
int * myptr;
myptr = &myvar;
When pointers are initialized, what is initialized is the address they point to (i.e., myptr), never the value being pointed (i.e., *myptr). Therefore, the code above shall not be confused with:
int myvar;
int * myptr;
*myptr = &myvar;
Which anyway would not make much sense (and is not valid code).
The asterisk (*) in the pointer declaration (line 2) only indicates that it is a pointer, it is not the dereference operator (as in line 3). Both things just happen to use the same sign: *. As always, spaces are not relevant, and never change the meaning of an expression.
Pointers can be initialized either to the address of a variable (such as in the case above), or to the value of another pointer (or array):
int myvar;
int *foo = &myvar;
int *bar = foo;
To conduct arithmetical operations on pointers is a little different than to conduct them on regular integer types. To begin with, only addition and subtraction operations are allowed; the others make no sense in the world of pointers. But both addition and subtraction have a slightly different behavior with pointers, according to the size of the data type to which they point.
When fundamental data types were introduced, we saw that types have different sizes. For example: char always has a size of 1 byte, short is generally larger than that, and int and long are even larger; the exact size of these being dependent on the system. For example, let's imagine that in a given system, char takes 1 byte, short takes 2 bytes, and long takes 4.
Suppose now that we define three pointers in this compiler:
char *mychar;
short *myshort;
long *mylong;
and that we know that they point to the memory locations 1000, 2000, and 3000, respectively.
Therefore, if we write:
++mychar;
++myshort;
++mylong;
mychar, as one would expect, would contain the value 1001. But not so obviously, myshort would contain the value 2002, and mylong would contain 3004, even though they have each been incremented only once. The reason is that, when adding one to a pointer, the pointer is made to point to the following element of the same type, and, therefore, the size in bytes of the type it points to is added to the pointer.
This is applicable both when adding and subtracting any number to a pointer. It would happen exactly the same if we wrote:
mychar = mychar + 1;
myshort = myshort + 1;
mylong = mylong + 1;
Regarding the increment (++) and decrement (--) operators, they both can be used as either prefix or suffix of an expression, with a slight difference in behavior: as a prefix, the increment happens before the expression is evaluated, and as a suffix, the increment happens after the expression is evaluated. This also applies to expressions incrementing and decrementing pointers, which can become part of more complicated expressions that also include dereference operators (*). Remembering operator precedence rules, we can recall that postfix operators, such as increment and decrement, have higher precedence than prefix operators, such as the dereference operator (*). Therefore, the following expression:
*p++
is equivalent to *(p++). And what it does is to increase the value of p (so it now points to the next element), but because ++ is used as postfix, the whole expression is evaluated as the value pointed originally by the pointer (the address it pointed to before being incremented).
Essentially, these are the four possible combinations of the dereference operator with both the prefix and suffix versions of the increment operator (the same being applicable also to the decrement operator):
A typical -but not so simple- statement involving these operators is:
*p++ = *q++;
Because ++ has a higher precedence than *, both p and q are incremented, but because both increment operators (++) are used as postfix and not prefix, the value assigned to *p is *q before both p and q are incremented. And then both are incremented. It would be roughly equivalent to:
*p = *q;
++p;
++q;
Like always, parentheses reduce confusion by adding legibility to expressions.
Pointers can be used to access a variable by its address, and this access may include modifying the value pointed. But it is also possible to declare pointers that can access the pointed value to read it, but not to modify it. For this, it is enough with qualifying the type pointed to by the pointer as const. For example:
Here p points to a variable, but points to it in a const-qualified manner, meaning that it can read the value pointed, but it cannot modify it. Note also, that the expression &y is of type int*, but this is assigned to a pointer of type const int*. This is allowed: a pointer to non-const can be implicitly converted to a pointer to const. But not the other way around! As a safety feature, pointers to const are not implicitly convertible to pointers to non-const.
One of the use cases of pointers to const elements is as function parameters: a function that takes a pointer to non-const as parameter can modify the value passed as argument, while a function that takes a pointer to const as parameter cannot.
11
21
31
Note that print_all uses pointers that point to constant elements. These pointers point to constant content they cannot modify, but they are not constant themselves: i.e., the pointers can still be incremented or assigned different addresses, although they cannot modify the content they point to.
And this is where a second dimension to constness is added to pointers: Pointers can also be themselves const. And this is specified by appending const to the pointed type (after the asterisk):
The syntax with const and pointers is definitely tricky, and recognizing the cases that best suit each use tends to require some experience. In any case, it is important to get constness with pointers (and references) right sooner rather than later, but you should not worry too much about grasping everything if this is the first time you are exposed to the mix of const and pointers. More use cases will show up in coming chapters.
To add a little bit more confusion to the syntax of const with pointers, the const qualifier can either precede or follow the pointed type, with the exact same meaning:
As with the spaces surrounding the asterisk, the order of const in this case is simply a matter of style. This chapter uses a prefix const, as for historical reasons this seems to be more extended, but both are exactly equivalent. The merits of each style are still intensely debated on the internet.
As pointed earlier, string literals are arrays containing null-terminated character sequences. In earlier sections, string literals have been used to be directly inserted into cout, to initialize strings and to initialize arrays of characters.
But they can also be accessed directly. String literals are arrays of the proper array type to contain all its characters plus the terminating null-character, with each of the elements being of type const char (as literals, they can never be modified). For example:
const char * foo = "hello";
This declares an array with the literal representation for "hello", and then a pointer to its first element is assigned to foo. If we imagine that "hello" is stored at the memory locations that start at address 1702, we can represent the previous declaration as:
Note that here foo is a pointer and contains the value 1702, and not 'h', nor "hello", although 1702 indeed is the address of both of these.
The pointer foo points to a sequence of characters. And because pointers and arrays behave essentially in the same way in expressions, foo can be used to access the characters in the same way arrays of null-terminated character sequences are. For example:
*(foo+4)
foo[4]
Both expressions have a value of 'o' (the fifth element of the array).
C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or even to other pointers). The syntax simply requires an asterisk (*) for each level of indirection in the declaration of the pointer:
This, assuming the randomly chosen memory locations for each variable of 7230, 8092, and 10502, could be represented as:
With the value of each variable represented inside its corresponding cell, and their respective addresses in memory represented by the value under them.
The new thing in this example is variable c, which is a pointer to a pointer, and can be used in three different levels of indirection, each one of them would correspond to a different value:
The void type of pointer is a special type of pointer. In C++, void represents the absence of type. Therefore, void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties).
This gives void pointers a great flexibility, by being able to point to any data type, from an integer value or a float to a string of characters. In exchange, they have a great limitation: the data pointed to by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason, any address in a void pointer needs to be transformed into some other pointer type that points to a concrete data type before being dereferenced.
One of its possible uses may be to pass generic parameters to a function. For example:
y, 1603
sizeof is an operator integrated in the C++ language that returns the size in bytes of its argument. For non-dynamic data types, this value is a constant. Therefore, for example, sizeof(char) is 1, because char has always a size of one byte.
In principle, pointers are meant to point to valid addresses, such as the address of a variable or the address of an element in an array. But pointers can actually point to any address, including addresses that do not refer to any valid element. Typical examples of this are uninitialized pointers and pointers to nonexistent elements of an array:
Neither p nor q point to addresses known to contain a value, but none of the above statements causes an error. In C++, pointers are allowed to take any address value, no matter whether there actually is something at that address or not. What can cause an error is to dereference such a pointer (i.e., actually accessing the value they point to). Accessing such a pointer causes undefined behavior, ranging from an error during runtime to accessing some random value.
But, sometimes, a pointer really needs to explicitly point to nowhere, and not just an invalid address. For such cases, there exists a special value that any pointer type can take: the null pointer value. This value can be expressed in C++ in two ways: either with an integer value of zero, or with the nullptr keyword:
int * p = 0;
int * q = nullptr;
Here, both p and q are null pointers, meaning that they explicitly point to nowhere, and they both actually compare equal: all null pointers compare equal to other null pointers. It is also quite usual to see the defined constant NULL be used in older code to refer to the null pointer value:
int * r = NULL;
NULL is defined in several headers of the standard library, and is defined as an alias of some null pointer constant value (such as 0 or nullptr).
Do not confuse null pointers with void pointers! A null pointer is a value that any pointer can take to represent that it is pointing to "nowhere", while a void pointer is a type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer, and the other to the type of data it points to.
C++ allows operations with pointers to functions. The typical use of this is for passing a function as an argument to another function. Pointers to functions are declared with the same syntax as a regular function declaration, except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name:
8
In the example above, minus is a pointer to a function that has two parameters of type int. It is directly initialized to point to the function subtraction:
int (* minus)(int,int) = subtraction;
In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input. On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete.
Dynamic memory is allocated using operator new. new is followed by a data type specifier and, if a sequence of more than one element is required, the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its syntax is:
pointer = new type
The first expression is used to allocate memory to contain one single element of type type. The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:
pointer = new type [number_of_elements]
int * foo;
foo = new int [5];
In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to foo (a pointer). Therefore, foo now points to a valid block of memory with space for five elements of type int.
Here, foo is a pointer, and thus, the first element pointed to by foo can be accessed either with the expression foo[0] or the expression *foo (both are equivalent). The second element can be accessed either with foo[1] or *(foo+1), and so on...
There is a substantial difference between declaring a normal array and allocating dynamic memory for a block of memory using new. The most important difference is that the size of a regular array needs to be a constant expression, and thus its size has to be determined at the moment of designing the program, before it is run, whereas the dynamic memory allocation performed by new allows to assign memory during runtime using any variable value as size.
The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, there are no guarantees that all requests to allocate memory using operator new are going to be granted by the system.
C++ provides two standard mechanisms to check if the allocation was successful:
One is by handling exceptions. Using this method, an exception of type bad_alloc is thrown when the allocation fails. Exceptions are a powerful C++ feature explained later in these tutorials. But for now, you should know that if this exception is thrown and it is not handled by a specific handler, the program execution is terminated.
This exception method is the method used by default by new, and is the one used in a declaration like:
foo = new int [5]; // if allocation fails, an exception is thrown
The other method is known as nothrow, and what happens when it is used is that when a memory allocation fails, instead of throwing a bad_alloc exception or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution normally.
This method can be specified by using a special object called nothrow, declared in header <new>, as argument for new:
foo = new (nothrow) int [5];
In this case, if the allocation of this block of memory fails, the failure can be detected by checking if foo is a null pointer:
This nothrow method is likely to produce less efficient code than exceptions, since it implies explicitly checking the pointer value returned after each and every allocation. Therefore, the exception mechanism is generally preferred, at least for critical allocations. Still, most of the coming examples will use the nothrow mechanism due to its simplicity.
In most cases, memory allocated dynamically is only needed during specific periods of time within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of operator delete, whose syntax is:
delete pointer;
delete[] pointer;
he first statement releases the memory of a single element allocated using new, and the second one releases the memory allocated for arrays of elements using new and a size in brackets ([]).
The value passed as argument to delete shall be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).
How many numbers would you like to type? 5
Enter number : 75
Enter number : 436
Enter number : 1067
Enter number : 8
Enter number : 32
You have entered: 75, 436, 1067, 8, 32,
Notice how the value within brackets in the new statement is a variable value entered by the user (i), not a constant expression:
p= new (nothrow) int[i];
There always exists the possibility that the user introduces a value for i so big that the system cannot allocate enough memory for it. For example, when I tried to give a value of 1 billion to the "How many numbers" question, my system could not allocate that much memory for the program, and I got the text message we prepared for this case (Error: memory could not be allocated).
It is considered good practice for programs to always be able to handle failures to allocate memory, either by checking the pointer value (if nothrow) or by catching the proper exception.
A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. Data structures can be declared in C++ using the following syntax:
struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
Where type_name is a name for the structure type, object_name can be a set of valid identifiers for objects that have the type of this structure. Within braces {}, there is a list with the data members, each one is specified with a type and a valid identifier as its name.
For example:
This declares a structure type, called product, and defines it having two members: weight and price, each of a different fundamental type. This declaration creates a new type (product), which is then used to declare three objects (variables) of this type: apple, banana, and melon. Note how once product is declared, it is used just like any other type.
Right at the end of the struct definition, and before the ending semicolon (;), the optional field object_names can be used to directly declare objects of the structure type. For example, the structure objects apple, banana, and melon can be declared at the moment the data structure type is defined:
In this case, where object_names are specified, the type name (product) becomes optional: struct requires either a type_name or at least one name in object_names, but not necessarily both.
It is important to clearly differentiate between what is the structure type name (product), and what is an object of this type (apple, banana, and melon). Many objects (such as apple, banana, and melon) can be declared from a single structure type (product).
Once the three objects of a determined structure type are declared (apple, banana, and melon) its members can be accessed directly. The syntax for that is simply to insert a dot (.) between the object name and the member name. For example, we could operate with any of these elements as if they were standard variables of their respective types:
Each one of these has the data type corresponding to the member they refer to: apple.weight, banana.weight, and melon.weight are of type int, while apple.price, banana.price, and melon.price are of type double.
Here is a real example with structure types in action:
Enter title: Alien
Enter year: 1979
My favorite movie is:
2001 A Space Odyssey (1968)
And yours is:
Alien (1979)
The example shows how the members of an object act just as regular variables. For example, the member yours.year is a valid variable of type int, and mine.title is a valid variable of type string.
But the objects mine and yours are also variables with a type (of type movies_t). For example, both have been passed to function printmovie just as if they were simple variables. Therefore, one of the features of data structures is the ability to refer to both their members individually or to the entire structure as a whole. In both cases using the same identifier: the name of the structure.
Because structures are types, they can also be used as the type of arrays to construct tables or databases of them:
Enter title: Blade Runner
Enter year: 1982
Enter title: The Matrix
Enter year: 1999
Enter title: Taxi Driver
Enter year: 1976
You have entered these movies:
Blade Runner (1982)
The Matrix (1999)
Taxi Driver (1976)
Like any other type, structures can be pointed to by its own type of pointers:
Here amovie is an object of structure type movies_t, and pmovie is a pointer to point to objects of structure type movies_t. Therefore, the following code would also be valid:
pmovie = &amovie;
The value of the pointer pmovie would be assigned the address of object amovie.
Now, let's see another example that mixes pointers and structures, and will serve to introduce a new operator: the arrow operator (->):
Enter title: Invasion of the body snatchers
Enter year: 1978
You have entered:
Invasion of the body snatchers (1978)
The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members. This operator serves to access the member of an object directly from its address. For example, in the example above:
pmovie->title
is, for all purposes, equivalent to:
(*pmovie).title
Both expressions, pmovie->title and (*pmovie).title are valid, and both access the member title of the data structure pointed by a pointer called pmovie. It is definitely something different than:
*pmovie.title
which is rather equivalent to:
*(pmovie.title)
This would access the value pointed by a hypothetical pointer member called title of the structure object pmovie (which is not the case, since title is not a pointer type). The following panel summarizes possible combinations of the operators for pointers and for structure members:
Expression | What is evaluated | Equivalent |
---|---|---|
a.b | Member b of object a | |
a->b | Member b of object pointed to by a | (*a).b |
*a.b | Value pointed to by member b of object a | *(a.b) |
Structures can also be nested in such a way that an element of a structure is itself another structure:
After the previous declarations, all of the following expressions would be valid:
(where, by the way, the last two expressions refer to the same member).
Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
Classes are defined using either keyword class or keyword struct, with the following syntax:
Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, which can either be data or function declarations, and optionally access specifiers.
Classes have the same format as plain data structures, except that they can also include functions and have these new things called access specifiers. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights for the members that follow them:
By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before any other access specifier has private access automatically. For example:
Declares a class (i.e., a type) called Rectangle and an object (i.e., a variable) of this class, called rect. This class contains four members: two data members of type int (member width and member height) with private access (because private is the default access level) and two member functions with public access: the functions set_values and area, of which for now we have only included their declaration, but not their definition.
Notice the difference between the class name and the object name: In the previous example, Rectangle was the class name (i.e., the type), whereas rect was an object of type Rectangle. It is the same relationship int and a have in the following declaration:
int a;
where int is the type name (the class) and a is the variable name (the object).
After the declarations of Rectangle and rect, any of the public members of object rect can be accessed as if they were normal functions or normal variables, by simply inserting a dot (.) between object name and member name. This follows the same syntax as accessing the members of plain data structures. For example:
rect.set_values (3,4);
myarea = rect.area();
The only members of rect that cannot be accessed from outside the class are width and height, since they have private access and they can only be referred to from within other members of that same class.
Here is the complete example of class Rectangle:
area: 12
This example reintroduces the scope operator (::, two colons), seen in earlier chapters in relation to namespaces. Here it is used in the definition of function set_values to define a member of a class outside the class itself.
Notice that the definition of the member function area has been included directly within the definition of class Rectangle given its extreme simplicity. Conversely, set_values it is merely declared with its prototype within the class, but its definition is outside it. In this outside definition, the operator of scope (::) is used to specify that the function being defined is a member of the class Rectangle and not a regular non-member function.
The scope operator (::) specifies the class to which the member being declared belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition. For example, the function set_values in the previous example has access to the variables width and height, which are private members of class Rectangle, and thus only accessible from other members of the class, such as this.
The only difference between defining a member function completely within the class definition or to just include its declaration in the function and define it later outside the class, is that in the first case the function is automatically considered an inline member function by the compiler, while in the second it is a normal (not-inline) class member function. This causes no differences in behavior, but only on possible compiler optimizations.
Members width and height have private access (remember that if nothing else is specified, all members of a class defined with keyword class have private access). By declaring them private, access from outside the class is not allowed. This makes sense, since we have already defined a member function to set values for those members within the object: the member function set_values. Therefore, the rest of the program does not need to have direct access to them. Perhaps in a so simple example as this, it is difficult to see how restricting access to these variables may be useful, but in greater projects it may be very important that values cannot be modified in an unexpected way (unexpected from the point of view of the object).
The most important property of a class is that it is a type, and as such, we can declare multiple objects of it. For example, following with the previous example of class Rectangle, we could have declared the object rectb in addition to object rect:
n this particular case, the class (type of the objects) is Rectangle, of which there are two instances (i.e., objects): rect and rectb. Each one of them has its own member variables and member functions.
Notice that the call to rect.area() does not give the same result as the call to rectb.area(). This is because each object of class Rectangle has its own variables width and height, as they -in some way- have also their own function members set_value and area that operate on the object's own member variables.
Classes allow programming using object-oriented paradigms: Data and functions are both members of the object, reducing the need to pass and carry handlers or other state variables as arguments to functions, because they are part of the object whose member is called. Notice that no arguments were passed on the calls to rect.area or rectb.area. Those member functions directly used the data members of their respective objects rect and rectb.
What would happen in the previous example if we called the member function area before having called set_values? An undetermined result, since the members width and height had never been assigned a value.
In order to avoid that, a class can include a special function called its constructor, which is automatically called whenever a new object of this class is created, allowing the class to initialize member variables or allocate storage.
This constructor function is declared just like a regular member function, but with a name that matches the class name and without any return type; not even void.
The Rectangle class above can easily be improved by implementing a constructor:
rect area: 12
rectb area: 30
The results of this example are identical to those of the previous example. But now, class Rectangle has no member function set_values, and has instead a constructor that performs a similar action: it initializes the values of width and height with the arguments passed to it.
Notice how these arguments are passed to the constructor at the moment at which the objects of this class are created:
Rectangle rect (3,4);
Rectangle rectb (5,6);
Constructors cannot be called explicitly as if they were regular member functions. They are only executed once, when a new object of that class is created.
Notice how neither the constructor prototype declaration (within the class) nor the latter constructor definition, have return values; not even void: Constructors never return values, they simply initialize the object.
Like any other function, a constructor can also be overloaded with different versions taking different parameters: with a different number of parameters and/or parameters of different types. The compiler will automatically call the one whose parameters match the arguments:
In the above example, two objects of class Rectangle are constructed: rect and rectb. rect is constructed with two arguments, like in the example before. But this example also introduces a special kind constructor: the default constructor. The default constructor is the constructor that takes no parameters, and it is special because it is called when an object is declared but is not initialized with any arguments. In the example above, the default constructor is called for rectb. Note how rectb is not even constructed with an empty set of parentheses - in fact, empty parentheses cannot be used to call the default constructor:
This is because the empty set of parentheses would make of rectc a function declaration instead of an object declaration: It would be a function that takes no arguments and returns a value of type Rectangle.
The way of calling constructors by enclosing their arguments in parentheses, as shown above, is known as functional form. But constructors can also be called with other syntaxes:
First, constructors with a single parameter can be called using the variable initialization syntax (an equal sign followed by the argument):
class_name object_name = initialization_value;
More recently, C++ introduced the possibility of constructors to be called using uniform initialization, which essentially is the same as the functional form, but using braces ({}) instead of parentheses (()):
class_name object_name { value, value, value, ... }
Optionally, this last syntax can include an equal sign before the braces.
Here is an example with four ways to construct objects of a class whose constructor takes a single parameter:
foo's circumference: 62.8319
An advantage of uniform initialization over functional form is that, unlike parentheses, braces cannot be confused with function declarations, and thus can be used to explicitly call default constructors:
The choice of syntax to call constructors is largely a matter of style. Most existing code currently uses functional form, and some newer style guides suggest to choose uniform initialization over the others, even though it also has its potential pitfalls for its preference of initializer_list as its type.
When a constructor is used to initialize other members, these other members can be initialized directly, without resorting to statements in its body. This is done by inserting, before the constructor's body, a colon (:) and a list of initializations for class members. For example, consider a class with the following declaration:
The constructor for this class could be defined, as usual, as:
Rectangle::Rectangle (int x, int y) { width=x; height=y; }
But it could also be defined using member initialization as:
Rectangle::Rectangle (int x, int y) : width(x) { height=y; }
Or even:
Rectangle::Rectangle (int x, int y) : width(x), height(y) { }
Note how in this last case, the constructor does nothing else than initialize its members, hence it has an empty function body.
For members of fundamental types, it makes no difference which of the ways above the constructor is defined, because they are not initialized by default, but for member objects (those whose type is a class), if they are not initialized after the colon, they are default-constructed.
Default-constructing all members of a class may or may always not be convenient: in some cases, this is a waste (when the member is then reinitialized otherwise in the constructor), but in some other cases, default-construction is not even possible (when the class does not have a default constructor). In these cases, members shall be initialized in the member initialization list. For example:
In this example, class Cylinder has a member object whose type is another class (base's type is Circle). Because objects of class Circle can only be constructed with a parameter, Cylinder's constructor needs to call base's constructor, and the only way to do this is in the member initializer list.
These initializations can also use uniform initializer syntax, using braces {} instead of parentheses ():
Objects can also be pointed to by pointers: Once declared, a class becomes a valid type, so it can be used as the type pointed to by a pointer. For example:
Rectangle * prect;
is a pointer to an object of class Rectangle. Similarly as with plain data structures, the members of an object can be accessed directly from a pointer by using the arrow operator (->). Here is an example with some possible combinations:
This example makes use of several operators to operate on objects and pointers (operators *, &, ., ->, []). They can be interpreted as:
expression | can be read as |
---|---|
*x | pointed to by x |
&x | address of x |
x.y | member y of object x |
x->y | member y of object pointed to by x |
(*x).y | member y of object pointed to by x (equivalent to the previous one) |
x[0] | first object pointed to by x |
x[1] | second object pointed to by x |
x[n] | (n+1 )th object pointed to by x |
Most of these expressions have been introduced in earlier chapters. Most notably, the chapter about arrays introduced the offset operator ([]) and the chapter about plain data structures introduced the arrow operator (->).
Classes can be defined not only with keyword class, but also with keywords struct and union.
The keyword struct, generally used to declare plain data structures, can also be used to declare classes that have member functions, with the same syntax as with keyword class. The only difference between both is that members of classes declared with the keyword struct have public access by default, while members of classes declared with the keyword class have private access by default. For all other purposes both keywords are equivalent in this context.
Conversely, the concept of unions is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold member functions. The default access in union classes is public.
Classes, essentially, define new types to be used in C++ code. And types in C++ not only interact with code by means of constructions and assignments. They also interact by means of operators. For example, take the following operation on fundamental types:
int a, b, c;
a = b + c;
Here, different variables of a fundamental type (int) are applied the addition operator, and then the assignment operator. For a fundamental arithmetic type, the meaning of such operations is generally obvious and unambiguous, but it may not be so for certain class types. For example:
struct myclass {
string product;
float price;
} a, b, c;
a = b + c;
Here, it is not obvious what the result of the addition operation on b and c does. In fact, this code alone would cause a compilation error, since the type myclass has no defined behavior for additions. However, C++ allows most operators to be overloaded so that their behavior can be defined for just about any type, including classes. Here is a list of all the operators that can be overloaded:
Overloadable operators |
---|
|
Operators are overloaded by means of operator functions, which are regular functions with special names: their name begins by the operator keyword followed by the operator sign that is overloaded. The syntax is:
type operator sign (parameters) { /*... body ...*/ }
For example, cartesian vectors are sets of two coordinates: x and y. The addition operation of two cartesian vectors is defined as the addition both x coordinates together, and both y coordinates together. For example, adding the cartesian vectors (3,1) and (1,2) together would result in (3+1,1+2) = (4,3). This could be implemented in C++ with the following code:
4,3
If confused about so many appearances of CVector, consider that some of them refer to the class name (i.e., the type) CVector and some others are functions with that name (i.e., constructors, which must have the same name as the class). For example:
The function operator+ of class CVector overloads the addition operator (+) for that type. Once declared, this function can be called either implicitly using the operator, or explicitly using its functional name:
Both expressions are equivalent.
The operator overloads are just regular functions which can have any behavior; there is actually no requirement that the operation performed by that overload bears a relation to the mathematical or usual meaning of the operator, although it is strongly recommended. For example, a class that overloads operator+ to actually subtract or that overloads operator== to fill the object with zeros, is perfectly valid, although using such a class could be challenging.
The parameter expected for a member function overload for operations such as operator+ is naturally the operand to the right hand side of the operator. This is common to all binary operators (those with an operand to its left and one operand to its right). But operators can come in diverse forms. Here you have a table with a summary of the parameters needed for each of the different operators than can be overloaded (please, replace @ by the operator in each case):
Expression | Operator | Member function | Non-member function |
---|---|---|---|
@a | + - * & ! ~ ++ -- | A::operator@() | operator@(A) |
a@ | ++ -- | A::operator@(int) | operator@(A,int) |
a@b | + - * / % ^ & | < > == != <= >= << >> && || , | A::operator@(B) | operator@(A,B) |
a@b | = += -= *= /= %= ^= &= |= <<= >>= [] | A::operator@(B) | - |
a(b,c...) | () | A::operator()(B,C...) | - |
a->b | -> | A::operator->() | - |
(TYPE) a | TYPE | A::operator TYPE() | - |
Where a is an object of class A, b is an object of class B and c is an object of class C. TYPE is just any type (that operators overloads the conversion to type TYPE).
Notice that some operators may be overloaded in two forms: either as a member function or as a non-member function: The first case has been used in the example above for operator+. But some operators can also be overloaded as non-member functions; In this case, the operator function takes an object of the proper class as first argument.
For example:
4,3
The keyword this represents a pointer to the object whose member function is being executed. It is used within a class's member function to refer to the object itself. One of its uses can be to check if a parameter passed to a member function is the object itself. For example:
yes, &a is b
It is also frequently used in operator= member functions that return objects by reference. Following with the examples on cartesian vector seen before, its operator= function could have been defined as:
In fact, this function is very similar to the code that the compiler generates implicitly for this class for operator=.
A class can contain static members, either data or functions.
A static data member of a class is also known as a "class variable", because there is only one common variable for all the objects of that same class, sharing the same value: i.e., its value is not different from one object of this class to another.
For example, it may be used for a variable within a class that can contain a counter with the number of objects of that class that are currently allocated, as in the following example:
6
7
In fact, static members have the same properties as non-member variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, they cannot be initialized directly in the class, but need to be initialized somewhere outside it. As in the previous example:
int Dummy::n=0;
Because it is a common variable value for all the objects of the same class, it can be referred to as a member of any object of that class or even directly by the class name (of course this is only valid for static members):
cout << a.n;
cout << Dummy::n;
These two calls above are referring to the same variable: the static variable n within class Dummy shared by all objects of this class.
Again, it is just like a non-member variable, but with a name that requires to be accessed like a member of a class (or an object).
Classes can also have static member functions. These represent the same: members of a class that are common to all object of that class, acting exactly as non-member functions but being accessed like members of the class. Because they are like non-member functions, they cannot access non-static members of the class (neither member variables nor member functions). They neither can use the keyword this.
When an object of a class is qualified as a const object:
const MyClass myobject;
The access to its data members from outside the class is restricted to read-only, as if all its data members were const for those accessing them from outside the class. Note though, that the constructor is still called and is allowed to initialize and modify these data members:
10
The member functions of a const object can only be called if they are themselves specified as const members; in the example above, member get (which is not specified as const) cannot be called from foo. To specify that a member is a const member, the const keyword shall follow the function prototype, after the closing parenthesis for its parameters:
int get() const {return x;}
Note that const can be used to qualify the type returned by a member function. This const is not the same as the one which specifies a member as const. Both are independent and are located at different places in the function prototype:
int get() const {return x;} // const member function const int< get() {return x;} // member function returning a const< const int< get() const {return x;} // const member function returning a const<
Member functions specified to be const cannot modify non-static data members nor call other non-const member functions. In essence, const members shall not modify the state of an object.
const objects are limited to access only member functions marked as const, but non-const objects are not restricted and thus can access both const and non-const member functions alike.
You may think that anyway you are seldom going to declare const objects, and thus marking all members that don't modify the object as const is not worth the effort, but const objects are actually very common. Most functions taking classes as parameters actually take them by const reference, and thus, these functions can only access their const members:
10
If in this example, get was not specified as a const member, the call to arg.get() in the print function would not be possible, because const objects only have access to const member functions.
Member functions can be overloaded on their constness: i.e., a class may have two member functions with identical signatures except that one is const and the other is not: in this case, the const version is called only when the object is itself const, and the non-const version is called when the object is itself non-const.
15
20
Just like we can create function templates, we can also create class templates, allowing classes to have members that use template parameters as types. For example:
template <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } };
The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to declare an object of this class to store two integer values of type int with the values 115 and 36 we would write:
mypair<int> myobject (115, 36);
This same class could also be used to create an object to store any other type, such as:
mypair<double> myfloats (3.0, 2.18);
The constructor is the only member function in the previous class template and it has been defined inline within the class definition itself. In case that a member function is defined outside the defintion of the class template, it shall be preceded with the template <...> prefix:
100
Notice the syntax of the definition of member function getmax:
template <class T>
T mypair<T>::getmax ()
Confused by so many T's? There are three T's in this declaration: The first one is the template parameter. The second T refers to the type returned by the function. And the third T (the one between angle brackets) is also a requirement: It specifies that this function's template parameter is also the class template parameter.
It is possible to define a different implementation for a template when a specific type is passed as template argument. This is called a template specialization. For example, let's suppose that we have a very simple class called mycontainer that can store one element of any type and that has just one member function called increase, which increases its value. But we find that when it stores an element of type char it would be more convenient to have a completely different implementation with a function member uppercase, so we decide to declare a class template specialization for that type:
// template specialization #include <iostream> using namespace std; // class template: template <class T> class mycontainer { T element; public: mycontainer (T arg) {element=arg;} T increase () {return ++element;} }; // class template specialization: template <> class mycontainer <char> { char element; public: mycontainer (char arg) {element=arg;} char uppercase () { if ((element>='a')&&(element<='z')) element+='A'-'a'; return element; } }; int main () { mycontainer<int> myint (7); mycontainer<char> mychar ('j'); cout << myint.increase() << endl; cout << mychar.uppercase() << endl; return 0; }
8
J
This is the syntax used for the class template specialization:
template <> class mycontainer <char> { ... };
First of all, notice that we precede the class name with template<> , including an empty parameter list. This is because all types are known and no template arguments are required for this specialization, but still, it is the specialization of a class template, and thus it requires to be noted as such.
But more important than this prefix, is the <char> specialization parameter after the class template name. This specialization parameter itself identifies the type for which the template class is being specialized (char). Notice the differences between the generic class template and the specialization:
template <class T> class mycontainer { ... };
template <> class mycontainer <char> { ... };
The first line is the generic template, and the second one is the specialization.
When we declare specializations for a template class, we must also define all its members, even those identical to the generic template class, because there is no "inheritance" of members from the generic template to the specialization.
Member function | typical form for class C : |
---|---|
Default constructor | C::C(); |
Destructor | C::~C(); |
Copy constructor | C::C (const C&); |
Copy assignment | C& operator= (const C&); |
Move constructor | C::C (C&&); |
Move assignment | C& operator= (C&&); |
Let's examine each of these:
The default constructor is the constructor called when objects of a class are declared, but are not initialized with any arguments.
If a class definition has no constructors, the compiler assumes the class to have an implicitly defined default constructor. Therefore, after declaring a class like this:
The compiler assumes that Example has a default constructor. Therefore, objects of this class can be constructed by simply declaring them without any arguments:
But as soon as a class has some constructor taking any number of parameters explicitly declared, the compiler no longer provides an implicit default constructor, and no longer allows the declaration of new objects of that class without arguments. For example, the following class:
Here, we have declared a constructor with a parameter of type int. Therefore the following object declaration would be correct:
But the following:
Would not be valid, since the class has been declared with an explicit constructor taking one argument and that replaces the implicit default constructor taking none.
Therefore, if objects of this class need to be constructed without arguments, the proper default constructor shall also be declared in the class. For example:
bar's content: Example
Here, Example3 has a default constructor (i.e., a constructor without parameters) defined as an empty block:
This allows objects of class Example3 to be constructed without arguments (like foo was declared in this example). Normally, a default constructor like this is implicitly defined for all classes that have no other constructors and thus no explicit definition is required. But in this case, Example3 has another constructor:
Example3 (const string& str);
And when any constructor is explicitly declared in a class, no implicit default constructors is automatically provided.
Destructors fulfill the opposite functionality of constructors: They are responsible for the necessary cleanup needed by a class when its lifetime ends. The classes we have defined in previous chapters did not allocate any resource and thus did not really require any clean up.
But now, let's imagine that the class in the last example allocates dynamic memory to store the string it had as data member; in this case, it would be very useful to have a function called automatically at the end of the object's life in charge of releasing this memory. To do this, we use a destructor. A destructor is a member function very similar to a default constructor: it takes no arguments and returns nothing, not even void. It also uses the class name as its own name, but preceded with a tilde sign (~):
bar's content: Example
On construction, Example4 allocates storage for a string. Storage that is later released by the destructor.
The destructor for an object is called at the end of its lifetime; in the case of foo and bar this happens at the end of function main.
When an object is passed a named object of its own type as argument, its copy constructor is invoked in order to construct a copy.
A copy constructor is a constructor whose first parameter is of type reference to the class itself (possibly const qualified) and which can be invoked with a single argument of this type. For example, for a class MyClass, the copy constructor may have the following signature:
If a class has no custom copy nor move constructors (or assignments) defined, an implicit copy constructor is provided. This copy constructor simply performs a copy of its own members. For example, for a class such as:
An implicit copy constructor is automatically defined. The definition assumed for this function performs a shallow copy, roughly equivalent to:
This default copy constructor may suit the needs of many classes. But shallow copies only copy the members of the class themselves, and this is probably not what we expect for classes like class Example4 we defined above, because it contains pointers of which it handles its storage. For that class, performing a shallow copy means that the pointer value is copied, but not the content itself; This means that both objects (the copy and the original) would be sharing a single string object (they would both be pointing to the same object), and at some point (on destruction) both objects would try to delete the same block of memory, probably causing the program to crash on runtime. This can be solved by defining the following custom copy constructor that performs a deep copy:
bar's content: Example
The deep copy performed by this copy constructor allocates storage for a new string, which is initialized to contain a copy of the original object. In this way, both objects (copy and original) have distinct copies of the content stored in different locations.
Objects are not only copied on construction, when they are initialized: They can also be copied on any assignment operation. See the difference:
Note that baz is initialized on construction using an equal sign, but this is not an assignment operation! (although it may look like one): The declaration of an object is not an assignment operation, it is just another of the syntaxes to call single-argument constructors.
The assignment on foo is an assignment operation. No object is being declared here, but an operation is being performed on an existing object; foo.
The copy assignment operator is an overload of operator= which takes a value or reference of the class itself as parameter. The return value is generally a reference to *this (although this is not required). For example, for a class MyClass, the copy assignment may have the following signature:
The copy assignment operator is also a special function and is also defined implicitly if a class has no custom copy nor move assignments (nor move constructor) defined.
But again, the implicit version performs a shallow copy which is suitable for many classes, but not for classes with pointers to objects they handle its storage, as is the case in Example5. In this case, not only the class incurs the risk of deleting the pointed object twice, but the assignment creates memory leaks by not deleting the object pointed by the object before the assignment. These issues could be solved with a copy assignment that deletes the previous object and performs a deep copy:
Or even better, since its string member is not constant, it could re-utilize the same string object:
Similar to copying, moving also uses the value of an object to set the value to another object. But, unlike copying, the content is actually transferred from one object (the source) to the other (the destination): the source loses that content, which is taken over by the destination. This moving only happens when the source of the value is an unnamed object.
Unnamed objects are objects that are temporary in nature, and thus haven't even been given a name. Typical examples of unnamed objects are return values of functions or type-casts.
Using the value of a temporary object such as these to initialize another object or to assign its value, does not really require a copy: the object is never going to be used for anything else, and thus, its value can be moved into the destination object. These cases trigger the move constructor and move assignments:
The move constructor is called when an object is initialized on construction using an unnamed temporary. Likewise, the move assignment is called when an object is assigned the value of an unnamed temporary:
Both the value returned by fn and the value constructed with MyClass are unnamed temporaries. In these cases, there is no need to make a copy, because the unnamed object is very short-lived and can be acquired by the other object when this is a more efficient operation.
The move constructor and move assignment are members that take a parameter of type rvalue reference to the class itself:
An rvalue reference is specified by following the type with two ampersands (&&). As a parameter, an rvalue reference matches arguments of temporaries of this type.
The concept of moving is most useful for objects that manage the storage they use, such as objects that allocate storage with new and delete. In such objects, copying and moving are really different operations:
- Copying from A to B means that new memory is allocated to B and then the entire content of A is copied to this new memory allocated for B.
- Moving from A to B means that the memory already allocated to A is transferred to B without allocating any new storage. It involves simply copying the pointer.
For example:
foo's content: Example
Compilers already optimize many cases that formally require a move-construction call in what is known as Return Value Optimization. Most notably, when the value returned by a function is used to initialize an object. In these cases, the move constructor may actually never get called.
Note that even though rvalue references can be used for the type of any function parameter, it is seldom useful for uses other than the move constructor. Rvalue references are tricky, and unnecessary uses may be the source of errors quite difficult to track.
The six special members functions described above are members implicitly declared on classes under certain circumstances:
Member function | implicitly defined: | default definition: |
---|---|---|
Default constructor | if no other constructors | does nothing |
Destructor | if no destructor | does nothing |
Copy constructor | if no move constructor and no move assignment | copies all members |
Copy assignment | if no move constructor and no move assignment | copies all members |
Move constructor | if no destructor, no copy constructor and no copy nor move assignment | moves all members |
Move assignment | if no destructor, no copy constructor and no copy nor move assignment | moves all members |
Notice how not all special member functions are implicitly defined in the same cases. This is mostly due to backwards compatibility with C structures and earlier C++ versions, and in fact some include deprecated cases. Fortunately, each class can select explicitly which of these members exist with their default definition or which are deleted by using the keywords default and delete, respectively. The syntax is either one of:
For example:
Here, Rectangle can be constructed either with two int arguments or be default-constructed (with no arguments). It cannot however be copy-constructed from another Rectangle object, because this function has been deleted. Therefore, assuming the objects of the last example, the following statement would not be valid:
It could, however, be made explicitly valid by defining its copy constructor as:
Which would be essentially equivalent to:
Note that, the keyword default does not define a member function equal to the default constructor (i.e., where default constructor means constructor with no parameters), but equal to the constructor that would be implicitly defined if not deleted. In general, and for future compatibility, classes that explicitly define one copy/move constructor or one copy/move assignment but not both, are encouraged to specify either delete or default on the other special member functions they don't explicitly define.
In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to "friends".
Friends are functions or classes declared with the friend keyword.
A non-member function can access the private and protected members of a class if it is declared a friend of that class. That is done by including a declaration of this external function within the class, and preceding it with the keyword friend:
24
The duplicate function is a friend of class Rectangle. Therefore, function duplicate is able to access the members width and height (which are private) of different objects of type Rectangle. Notice though that neither in the declaration of duplicate nor in its later use in main, function duplicate is considered a member of class Rectangle. It isn't! It simply has access to its private and protected members without being a member.
Typical use cases of friend functions are operations that are conducted between two different classes accessing private or protected members of both.
Similar to friend functions, a friend class is a class whose members have access to the private or protected members of another class:
16
In this example, class Rectangle is a friend of class Square allowing Rectangle's member functions to access private and protected members of Square. More concretely, Rectangle accesses the member variable Square::side, which describes the side of the square.
There is something else new in this example: at the beginning of the program, there is an empty declaration of class Square. This is necessary because class Rectangle uses Square (as a parameter in member convert), and Square uses Rectangle (declaring it a friend).
Friendships are never corresponded unless specified: In our example, Rectangle is considered a friend class by Square, but Square is not considered a friend by Rectangle. Therefore, the member functions of Rectangle can access the protected and private members of Square but not the other way around. Of course, Square could also be declared friend of Rectangle, if needed, granting such an access.
Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless explicitly specified.
Classes in C++ can be extended, creating new classes which retain characteristics of the base class. This process, known as inheritance, involves a base class and a derived class: The derived class inherits the members of the base class, on top of which it can add its own members.
For example, let's imagine a series of classes to describe two kinds of polygons: rectangles and triangles. These two polygons have certain common properties, such as the values needed to calculate their areas: they both can be described simply with a height and a width (or base).
This could be represented in the world of classes with a class Polygon from which we would derive the two other ones: Rectangle and Triangle:
The Polygon class would contain members that are common for both types of polygon. In our case: width and height. And Rectangle and Triangle would be its derived classes, with specific features that are different from one type of polygon to the other.
Classes that are derived from others inherit all the accessible members of the base class. That means that if a base class includes a member A and we derive a class from it with another member called B, the derived class will contain both member A and member B.
The inheritance relationship of two classes is declared in the derived class. Derived classes definitions use the following syntax:
class derived_class_name: public base_class_name
{ /*...*/ };
Where derived_class_name is the name of the derived class and base_class_name is the name of the class on which it is based. The public access specifier may be replaced by any one of the other access specifiers (protected or private). This access specifier limits the most accessible level for the members inherited from the base class: The members with a more accessible level are inherited with this level instead, while the members with an equal or more restrictive access level keep their restrictive level in the derived class.
20
10
The objects of the classes Rectangle and Triangle each contain members inherited from Polygon. These are: width, height and set_values.
The protected access specifier used in class Polygon is similar to private. Its only difference occurs in fact with inheritance: When a class inherits another one, the members of the derived class can access the protected members inherited from the base class, but not its private members.
By declaring width and height as protected instead of private, these members are also accessible from the derived classes Rectangle and Triangle, instead of just from members of Polygon. If they were public, they could be accessed just from anywhere.
We can summarize the different access types according to which functions can access them in the following way:
Access | public | protected | private |
---|---|---|---|
members of the same class | yes | yes | yes |
members of derived class | yes | yes | no |
not members | yes | no | no |
Where "not members" represents any access from outside the class, such as from main, from another class or from a function.
In the example above, the members inherited by Rectangle and Triangle have the same access permissions as they had in their base class Polygon:
This is because the inheritance relation has been declared using the public keyword on each of the derived classes:
This public keyword after the colon (:) denotes the most accessible level the members inherited from the class that follows it (in this case Polygon) will have from the derived class (in this case Rectangle). Since public is the most accessible level, by specifying this keyword the derived class will inherit all the members with the same levels they had in the base class.
With protected, all public members of the base class are inherited as protected in the derived class. Conversely, if the most restricting access level is specified (private), all the base class members are inherited as private.
For example, if daughter were a class derived from mother that we defined as:
This would set protected as the less restrictive access level for the members of Daughter that it inherited from mother. That is, all members that were public in Mother would become protected in Daughter. Of course, this would not restrict Daughter from declaring its own public members. That less restrictive access level is only set for the members inherited from Mother.
If no access level is specified for the inheritance, the compiler assumes private for classes declared with keyword class and public for those declared with struct.
Actually, most use cases of inheritance in C++ should use public inheritance. When other access levels are needed for base classes, they can usually be better represented as member variables instead.
In principle, a publicly derived class inherits access to every member of a base class except:
Even though access to the constructors and destructor of the base class is not inherited as such, they are automatically called by the constructors and destructor of the derived class.
Unless otherwise specified, the constructors of a derived class calls the default constructor of its base classes (i.e., the constructor taking no arguments). Calling a different constructor of a base class is possible, using the same syntax used to initialize member variables in the initialization list:
derived_constructor_name (parameters) : base_constructor_name (parameters) {...}
For example:
Notice the difference between which Mother's constructor is called when a new Daughter object is created and which when it is a Son object. The difference is due to the different constructor declarations of Daughter and Son:
A class may inherit from more than one class by simply specifying more base classes, separated by commas, in the list of a class's base classes (i.e., after the colon). For example, if the program had a specific class to print on screen called Output, and we wanted our classes Rectangle and Triangle to also inherit its members in addition to those of Polygon we could write:
Here is the complete example:
20
10
Before getting any deeper into this chapter, you should have a proper understanding of pointers and class inheritance. If you are not really sure of the meaning of any of the following expressions, you should review the indicated sections:
Statement: | Explained in: |
---|---|
int A::b(int c) { } | Classes |
a->b | Data structures |
class A: public B {}; | Friendship and inheritance |
One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature.
The example about the rectangle and triangle classes can be rewritten using pointers taking this feature into account:
20
10
Function main declares two pointers to Polygon (named ppoly1 and ppoly2). These are assigned the addresses of rect and trgl, respectively, which are objects of type Rectangle and Triangle. Such assignments are valid, since both Rectangle and Triangle are classes derived from Polygon.
Dereferencing ppoly1 and ppoly2 (with *ppoly1 and *ppoly2) is valid and allows us to access the members of their pointed objects. For example, the following two statements would be equivalent in the previous example:
But because the type of ppoly1 and ppoly2 is pointer to Polygon (and not pointer to Rectangle nor pointer to Triangle), only the members inherited from Polygon can be accessed, and not those of the derived classes Rectangle and Triangle. That is why the program above accesses the area members of both objects using rect and trgl directly, instead of the pointers; the pointers to the base class cannot access the area members.
Member area could have been accessed with the pointers to Polygon if area were a member of Polygon instead of a member of its derived classes, but the problem is that Rectangle and Triangle implement different versions of area, therefore there is not a single common version that could be implemented in the base class.
A virtual member is a member function that can be redefined in a derived class, while preserving its calling properties through references. The syntax for a function to become virtual is to precede its declaration with the virtual keyword:
20
10
0
In this example, all three classes (Polygon, Rectangle and Triangle) have the same members: width, height, and functions set_values and area.
The member function area has been declared as virtual in the base class because it is later redefined in each of the derived classes. Non-virtual members can also be redefined in derived classes, but non-virtual members of derived classes cannot be accessed through a reference of the base class: i.e., if virtual is removed from the declaration of area in the example above, all three calls to area would return zero, because in all cases, the version of the base class would have been called instead.
Therefore, essentially, what the virtual keyword does is to allow a member of a derived class with the same name as one in the base class to be appropriately called from a pointer, and more precisely when the type of the pointer is a pointer to the base class that is pointing to an object of the derived class, as in the above example.
A class that declares or inherits a virtual function is called a polymorphic class.
Note that despite of the virtuality of one of its members, Polygon was a regular class, of which even an object was instantiated (poly), with its own definition of member area that always returns 0.
Abstract base classes are something very similar to the Polygon class in the previous example. They are classes that can only be used as base classes, and thus are allowed to have virtual member functions without definition (known as pure virtual functions). The syntax is to replace their definition by =0 (an equal sign and a zero):
An abstract base Polygon class could look like this:
Notice that area has no definition; this has been replaced by =0, which makes it a pure virtual function. Classes that contain at least one pure virtual function are known as abstract base classes.
Abstract base classes cannot be used to instantiate objects. Therefore, this last abstract base class version of Polygon could not be used to declare objects like:
But an abstract base class is not totally useless. It can be used to create pointers to it, and take advantage of all its polymorphic abilities. For example, the following pointer declarations would be valid:
And can actually be dereferenced when pointing to objects of derived (non-abstract) classes. Here is the entire example:
// abstract base class #include <iostream> using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = ▭ Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << '\n'; cout << ppoly2->area() << '\n'; return 0; }
20
10
In this example, objects of different but related types are referred to using a unique type of pointer (Polygon*) and the proper member function is called every time, just because they are virtual. This can be really useful in some circumstances. For example, it is even possible for a member of the abstract base class Polygon to use the special pointer this to access the proper virtual members, even though Polygon itself has no implementation for this function:
20
10
Virtual members and abstract classes grant C++ polymorphic characteristics, most useful for object-oriented projects. Of course, the examples above are very simple use cases, but these features can be applied to arrays of objects or dynamically allocated objects.
Here is an example that combines some of the features in the latest chapters, such as dynamic memory, constructor initializers and polymorphism:
20
10
Notice that the ppoly pointers:
are declared being of type "pointer to Polygon", but the objects allocated have been declared having the derived class type directly (Rectangle and Triangle).
Implicit conversions are automatically performed when a value is copied to a compatible type. For example:
Here, the value of a is promoted from short to int without the need of any explicit operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions.
Converting to int from some smaller integer type, or to double from float is known as promotion, and is guaranteed to produce the exact same value in the destination type. Other conversions between arithmetic types may not always be able to represent the same value exactly:
Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This warning can be avoided with an explicit conversion.
For non-fundamental types, arrays and functions implicitly convert to pointers, and pointers in general allow the following conversions:
In the world of classes, implicit conversions can be controlled by means of three member functions:
For example:
The type-cast operator uses a particular syntax: it uses the operator keyword followed by the destination type and an empty set of parentheses. Notice that the return type is the destination type and thus is not specified before the operator keyword.
On a function call, C++ allows one implicit conversion to happen for each argument. This may be somewhat problematic for classes, because it is not always what is intended. For example, if we add the following function to the last example:
This function takes an argument of type B, but it could as well be called with an object of type A as argument:
This may or may not be what was intended. But, in any case, it can be prevented by marking the affected constructor with the explicit keyword:
Additionally, constructors marked with explicit cannot be called with the assignment-like syntax; In the above example, bar could not have been constructed with:
Type-cast member functions (those described in the previous section) can also be specified as explicit. This prevents implicit conversions in the same way as explicit-specified constructors do for the destination type.
C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion, known in C++ as type-casting. There exist two main syntaxes for generic type-casting: functional and c-like:
The functionality of these generic forms of type-casting is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that -while being syntactically correct- can cause runtime errors. For example, the following code compiles without errors:
The program declares a pointer to Addition, but then it assigns to it a reference to an object of another unrelated type using explicit type-casting:
Unrestricted explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or some other unexpected results. In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses. dynamic_cast <new_type> (expression) reinterpret_cast <new_type> (expression) static_cast <new_type> (expression) const_cast <new_type> (expression) The traditional type-casting equivalents to these expressions would be: (new_type) expression new_type (expression) but each one with its own special characteristics:
dynamic_cast can only be used with pointers and references to classes (or with void*). Its purpose is to ensure that the result of the type conversion points to a valid complete object of the destination pointer type.
This naturally includes pointer upcast (converting from pointer-to-derived to pointer-to-base), in the same way as allowed as an implicit conversion.
But dynamic_cast can also downcast (convert from pointer-to-base to pointer-to-derived) polymorphic classes (those with virtual members) if -and only if- the pointed object is a valid complete object of the target type. For example:
Null pointer on second type-cast.
Compatibility note: This type of dynamic_cast requires Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This needs to be enabled for runtime type checking using dynamic_cast to work properly with these types.The code above tries to perform two dynamic casts from pointer objects of type Base* (pba and pbb) to a pointer object of type Derived*, but only the first one is successful. Notice their respective initializations:
Even though both are pointers of type Base*, pba actually points to an object of type Derived, while pbb points to an object of type Base. Therefore, when their respective type-casts are performed using dynamic_cast, pba is pointing to a full object of class Derived, whereas pbb is pointing to an object of class Base, which is an incomplete object of class Derived.
When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown instead.
dynamic_cast can also perform the other implicit casts allowed on pointers: casting null pointers between pointers types (even between unrelated classes), and casting any pointer of any type to a void* pointer.
static_cast can perform conversions between pointers to related classes, not only upcasts (from pointer-to-derived to pointer-to-base), but also downcasts (from pointer-to-base to pointer-to-derived). No checks are performed during runtime to guarantee that the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, it does not incur the overhead of the type-safety checks of dynamic_cast.
This would be valid code, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.
Therefore, static_cast is able to perform with pointers to classes not only the conversions allowed implicitly, but also their opposite conversions.
static_cast is also able to perform all conversions allowed implicitly (not only those with pointers to classes), and is also able to perform the opposite of these. It can:
Additionally, static_cast can also perform the following:
reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.
It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it (such as intptr_t), is guaranteed to be able to be cast back to a valid pointer.
The conversions that can be performed by reinterpret_cast but not by static_cast are low-level operations based on reinterpreting the binary representations of the types, which on most cases results in code which is system-specific, and thus non-portable. For example:
This code compiles, although it does not make much sense, since now b points to an object of a totally unrelated and likely incompatible class. Dereferencing b is unsafe.
This type of casting manipulates the constness of the object pointed by a pointer, either to be set or to be removed. For example, in order to pass a const pointer to a function that expects a non-const argument:
sample text
The example above is guaranteed to work because function print does not write to the pointed object. Note though, that removing the constness of a pointed object to actually write to it causes undefined behavior.
typeid allows to check the type of an expression:
typeid (expression)
This operator returns a reference to a constant object of type type_info that is defined in the standard header <typeinfo>. A value returned by typeid can be compared with another value returned by typeid using operators == and != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.
a and b are of different types:
a is: int *
b is: int
When typeid is applied to classes, typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:
a is: class Base *
b is: class Base *
*a is: class Base
*b is: class Derived
Note: The string returned by member name of type_info depends on the specific implementation of your compiler and library. It is not necessarily a simple string with its typical type name, like in the compiler used to produce this output.
Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class Base *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object).
If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.
Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by transferring control to special functions called handlers.
To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing that portion of code in a try-block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.
An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block:
An exception occurred. Exception Nr. 20
The code under exception handling is enclosed in a try block. In this example this code simply throws an exception:
A throw expression accepts one parameter (in this case the integer value 20), which is passed as an argument to the exception handler.
The exception handler is declared with the catch keyword immediately after the closing brace of the try block. The syntax for catch is similar to a regular function with one parameter. The type of this parameter is very important, since the type of the argument passed by the throw expression is checked against it, and only in the case they match, the exception is caught by that handler.
Multiple handlers (i.e., catch expressions) can be chained; each one with a different parameter type. Only the handler whose argument type matches the type of the exception specified in the throw statement is executed.
If an ellipsis (...) is used as the parameter of catch, that handler will catch any exception no matter what the type of the exception thrown. This can be used as a default handler that catches all exceptions not caught by other handlers:
In this case, the last handler would catch any exception thrown of a type that is neither int nor char.
After an exception has been handled the program, execution resumes after the try-catch block, not after the throw statement!.
It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that an internal catch block forwards the exception to its external level. This is done with the expression throw; with no arguments. For example:
Older code may contain dynamic exception specifications. They are now deprecated in C++, but still supported. A dynamic exception specification follows the declaration of a function, appending a throw specifier to it. For example:
This declares a function called myfunction, which takes one argument of type char and returns a value of type double. If this function throws an exception of some type other than int, the function calls std::unexpected instead of looking for a handler or calling std::terminate.
If this throw specifier is left empty with no type, this means that std::unexpected is called for any exception. Functions with no throw specifier (regular functions) never call std::unexpected, but follow the normal path of looking for their exception handler.
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called std::exception and is defined in the <exception> header. This class has a virtual member function called what that returns a null-terminated character sequence (of type char *) and that can be overwritten in derived classes to contain some sort of description of the exception.
My exception happened.
We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this catches also classes derived from exception, like our myex object of type myexception.
All exceptions thrown by components of the C++ Standard library throw exceptions derived from this exception class. These are:
exception | description |
---|---|
bad_alloc | thrown by new on allocation failure |
bad_cast | thrown by dynamic_cast when it fails in a dynamic cast |
bad_exception | thrown by certain dynamic exception specifiers |
bad_typeid | thrown by typeid |
bad_function_call | thrown by empty function objects |
bad_weak_ptr | thrown by shared_ptr when passed a bad weak_ptr |
Also deriving from exception, header <exception> defines two generic exception types that can be inherited by custom exceptions to report errors:
exception | description |
---|---|
logic_error | error related to the internal logic of the program |
runtime_error | error detected during runtime |
A typical example where standard exceptions need to be checked for is on memory allocation:
The exception that may be caught by the exception handler in this example is a bad_alloc. Because bad_alloc is derived from the standard base class exception, it can be caught (capturing by reference, captures all related classes).
Preprocessor directives are lines included in the code of programs preceded by a hash sign (#). These lines are not program statements but directives for the preprocessor. The preprocessor examines the code before actual compilation of code begins and resolves all these directives before any code is actually generated by regular statements.
These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the preprocessor directive is ends. No semicolon (;) is expected at the end of a preprocessor directive. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash (\).
To define preprocessor macros we can use #define. Its syntax is:
#define identifier replacement
When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++ proper, it simply replaces any occurrence of identifier by replacement.
After the preprocessor has replaced TABLE_SIZE, the code becomes equivalent to:
#define can work also with parameters to define function macros:
This would replace any occurrence of getmax followed by two arguments by the replacement expression, but also replacing each argument by its identifier, exactly as you would expect if it was a function:
5
7
Defined macros are not affected by block structure. A macro lasts until it is undefined with the #undef preprocessor directive:
This would generate the same code as:
Function macro definitions accept two special operators (# and ##) in the replacement sequence:
The operator #, followed by a parameter name, is replaced by a string literal that contains the argument passed (as if enclosed between double quotes):
This would be translated into:
The operator ## concatenates two arguments leaving no blank spaces between them:
This would also be translated into:
Because preprocessor replacements happen before any C++ syntax check, macro definitions can be a tricky feature. But, be careful: code that relies heavily on complicated macros become less readable, since the syntax expected is on many occasions different from the normal expressions programmers expect in C++.
These directives allow to include or discard part of the code of a program if a certain condition is met.
#ifdef allows a section of a program to be compiled only if the macro that is specified as the parameter has been defined, no matter which its value is. For example:
In this case, the line of code int table[TABLE_SIZE]; is only compiled if TABLE_SIZE was previously defined with #define, independently of its value. If it was not defined, that line will not be included in the program compilation.
#ifndef serves for the exact opposite: the code between #ifndef and #endif directives is only compiled if the specified identifier has not been previously defined. For example:
In this case, if when arriving at this piece of code, the TABLE_SIZE macro has not been defined yet, it would be defined to a value of 100. If it already existed it would keep its previous value since the #define directive would not be executed.
The #if, #else and #elif (i.e., "else if") directives serve to specify some condition to be met in order for the portion of code they surround to be compiled. The condition that follows #if or #elif can only evaluate constant expressions, including macro expressions. For example:
Notice how the entire structure of #if, #elif and #else chained directives ends with #endif.
The behavior of #ifdef and #ifndef can also be achieved by using the special operators defined and !defined respectively in any #if or #elif directive:
When we compile a program and some error happens during the compiling process, the compiler shows an error message with references to the name of the file where the error happened and a line number, so it is easier to find the code generating the error.
The #line directive allows us to control both things, the line numbers within the code files as well as the file name that we want that appears when an error takes place. Its format is:
#line number "filename"
Where number is the new line number that will be assigned to the next code line. The line numbers of successive lines will be increased one by one from this point on.
"filename" is an optional parameter that allows to redefine the file name that will be shown. For example:
This code will generate an error that will be shown as error in file "assigning variable", line 20.
This directive aborts the compilation process when it is found, generating a compilation error that can be specified as its parameter:
This example aborts the compilation process if the macro name __cplusplus is not defined (this macro name is defined by default in all C++ compilers).
This directive has been used assiduously in other sections of this tutorial. When the preprocessor finds an #include directive it replaces it by the entire content of the specified header or file. There are two ways to use #include:
In the first case, a header is specified between angle-brackets <>. This is used to include headers provided by the implementation, such as the headers that compose the standard library (iostream, string,...). Whether the headers are actually files or exist in some other form is implementation-defined, but in any case they shall be properly included with this directive.
The syntax used in the second #include uses quotes, and includes a file. The file is searched for in an implementation-defined manner, which generally includes the current path. In the case that the file is not found, the compiler interprets the directive as a header inclusion, just as if the quotes ("") were replaced by angle-brackets (<>).
This directive is used to specify diverse options to the compiler. These options are specific for the platform and the compiler you use. Consult the manual or the reference of your compiler for more information on the possible parameters that you can define with #pragma.
If the compiler does not support a specific argument for #pragma, it is ignored - no syntax error is generated.
The following macro names are always defined (they all begin and end with two underscore characters, _):
macro | value |
---|---|
__LINE__ | Integer value representing the current line in the source code file being compiled. |
__FILE__ | A string literal containing the presumed name of the source file being compiled. |
__DATE__ | A string literal in the form "Mmm dd yyyy" containing the date in which the compilation process began. |
__TIME__ | A string literal in the form "hh:mm:ss" containing the time at which the compilation process began. |
__cplusplus | An integer value. All C++ compilers have this constant defined to some value. Its value depends on the version of the standard supported by the compiler:
|
__STDC_HOSTED__ | 1 if the implementation is a hosted implementation (with all standard headers available)0 otherwise. |
The following macros are optionally defined, generally depending on whether a feature is available:
macro | value |
---|---|
__STDC__ | In C: if defined to 1 , the implementation conforms to the C standard.In C++: Implementation defined. |
__STDC_VERSION__ | In C:
|
__STDC_MB_MIGHT_NEQ_WC__ | 1 if multibyte encoding might give a character a different value in character literals |
__STDC_ISO_10646__ | A value in the form yyyymmL , specifying the date of the Unicode standard followed by the encoding of wchar_t characters |
__STDCPP_STRICT_POINTER_SAFETY__ | 1 if the implementation has strict pointer safety (see get_pointer_safety ) |
__STDCPP_THREADS__ | 1 if the program can have more than one thread |
Particular implementations may define additional constants.
For example:
This is the line number 7 of file /home/jay/stdmacronames.cpp.
Its compilation began Nov 1 2005 at 10:12:29.
The compiler gives a __cplusplus value of 1
C++ provides the following classes to perform output and input of characters to/from files:
These classes are derived directly or indirectly from the classes istream and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therefore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:
[file example.txt]
Writing this to a file.
This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead.
But let's go step by step:
The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream (i.e., an object of one of these classes; in the previous example, this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.
In order to open a file with a stream object we use its member function open:
open (filename, mode);
Where filename is a string representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
ios::in | Open for input operations. |
ios::out | Open for output operations. |
ios::binary | Open in binary mode. |
ios::ate | Set the initial position at the end of the file. If this flag is not set, the initial position is the beginning of the file. |
ios::app | All output operations are performed at the end of the file, appending the content to the current content of the file. |
ios::trunc | If the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one. |
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open:
Each of the open member functions of classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:
class | default mode parameter |
---|---|
ofstream | ios::out |
ifstream | ios::in |
fstream | ios::in | ios::out |
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open member function (the flags are combined).
For fstream, the default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream is generally to open a file, these three classes include a constructor that automatically calls the open member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conduct the same opening operation in our previous example by writing:
Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to member is_open. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:
When we are finished with our input and output operations on a file we shall close it so that the operating system is notified and its resources become available again. For that, we call the stream's member function close. This member function takes flushes the associated buffers and closes the file:
Once this member function is called, the stream object can be re-used to open another file, and the file is available again to be opened by other processes.
In case that an object is destroyed while still associated with an open file, the destructor automatically calls the member function close.
Text file streams are those where the ios::binary flag is not included in their opening mode. These files are designed to store text and thus all values that are input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.
Writing operations on text files are performed in the same way we operated with cout:
[file example.txt]
This is a line.
This is another line.
Reading from a file can also be performed in the same way that we did with cin:
This is a line.
This is another line.
This last example reads a text file and prints out its content on the screen. We have created a while loop that reads the file line by line, using getline. The value returned by getline is a reference to the stream object itself, which when evaluated as a boolean expression (as in this while-loop) is true if the stream is ready for more operations, and false if either the end of the file has been reached or if some other error occurred.
The following member functions exist to check for specific states of a stream (all of them return a bool value):
bad()
Returns true if a reading or writing operation fails. For example, in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true. Note that good and bad are not exact opposites (good checks more state flags at once).
The member function clear() can be used to reset the state flags.
All i/o streams objects keep internally -at least- one internal position:
ifstream, like istream, keeps an internal get position with the location of the element to be read in the next input operation.
ofstream, like ostream, keeps an internal put position with the location where the next element has to be written.
Finally, fstream, keeps both, the get and the put position, like iostream.
These internal stream positions point to the locations within the stream where the next reading or writing operation is performed. These positions can be observed and modified using the following member functions:
tellg() and tellp()
These two member functions with no parameters return a value of the member type streampos, which is a type representing the current get position (in the case of tellg) or the put position (in the case of tellp).
seekg() and seekp()
These functions allow to change the location of the get and put positions. Both functions are overloaded with two different prototypes. The first form is:
seekg ( position );
seekp ( position );
Using this prototype, the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is streampos, which is the same type as returned by functions tellg and tellp.
The other form for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );
Using this prototype, the get or put position is set to an offset value relative to some specific point determined by the parameter direction. offset is of type streamoff. And direction is of type seekdir, which is an enumerated type that determines the point from where offset is counted from, and that can take any of the following values:
ios::beg | offset counted from the beginning of the stream |
ios::cur | offset counted from the current position |
ios::end | offset counted from the end of the stream |
The following example uses the member functions we have just seen to obtain the size of a file:
size is: 40 bytes.
Notice the type we have used for variables begin and end:
streampos is a specific type used for buffer and file positioning and is the type returned by file.tellg(). Values of this type can safely be subtracted from other values of the same type, and can also be converted to an integer type large enough to contain the size of the file.
These stream positioning functions use two particular types: streampos and streamoff. These types are also defined as member types of the stream class:
Type | Member type | Description |
---|---|---|
streampos | ios::pos_type | Defined as fpos<mbstate_t> .It can be converted to/from streamoff and can be added or subtracted values of these types. |
streamoff | ios::off_type | It is an alias of one of the fundamental integral types (such as int or long long ). |
Each of the member types above is an alias of its non-member equivalent (they are the exact same type). It does not matter which one is used. The member types are more generic, because they are the same on all stream objects (even on streams using exotic types of characters), but the non-member types are widely used in existing code for historical reasons.
For binary files, reading and writing data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data and data is likely not formatted in lines.
File streams include two member functions specifically designed to read and write binary data sequentially: write and read. The first one (write) is a member function of ostream (inherited by ofstream). And read is a member function of istream (inherited by ifstream). Objects of class fstream have both. Their prototypes are:
write ( memory_block, size );
read ( memory_block, size );
Where memory_block is of type char* (pointer to char), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.
the entire file content is in memory
In this example, the entire file is read and stored in a memory block. Let's examine how this is done:
First, the file is open with the ios::ate flag, which means that the get pointer will be positioned at the end of the file. This way, when we call to member tellg(), we will directly obtain the size of the file.
Once we have obtained the size of the file, we request the allocation of a memory block large enough to hold the entire file:
Right after that, we proceed to set the get position at the beginning of the file (remember that we opened the file with this pointer at the end), then we read the entire file, and finally close it:
At this point we could operate with the data obtained from the file. But our program simply announces that the content of the file is in memory and then finishes.
When we operate with file streams, these are associated to an internal buffer object of type streambuf. This buffer object may represent a memory block that acts as an intermediary between the stream and the physical file. For example, with an ofstream, each time the member function put (which writes a single character) is called, the character may be inserted in this intermediate buffer instead of being written directly to the physical file with which the stream is associated.
The operating system may also define other layers of buffering for reading and writing to files.
When the buffer is flushed, all the data contained in it is written to the physical medium (if it is an output stream). This process is called synchronization and takes place under any of the following circumstances:
C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development of .Net Framework.
C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures.
The following reasons make C# a widely used professional language:
Although C# constructs closely follow traditional high-level languages, C and C++ and being an object-oriented programming language. It has strong resemblance with Java, it has numerous strong programming features that make it endearing to a number of programmers worldwide.
Following is the list of few important features of C#:
We have set up the C# Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.
Try the following example using our online compiler available at CodingGround
For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.
In this chapter, we will discuss the tools required for creating C# programming. We have already mentioned that C# is part of .Net framework and is used for writing .Net applications. Therefore, before discussing the available tools for running a C# program, let us understand how C# relates to the .Net framework.
The .Net framework is a revolutionary platform that helps you to write the following types of applications:
The .Net framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages such as C#. Following are some of the components of the .Net framework:
For the jobs each of these components perform, please see ASP.Net - Introduction, and for details of each component, please consult Microsoft's documentation.
Microsoft provides the following development tools for C# programming
The last two are freely available from Microsoft official website. Using these tools, you can write all kinds of C# programs from simple command-line applications to more complex applications. You can also write C# source code files using a basic text editor, like Notepad, and compile the code into assemblies using the command-line compiler, which is again a part of the .NET Framework.
Visual C# Express and Visual Web Developer Express edition are trimmed down versions of Visual Studio and has the same appearance. They retain most features of Visual Studio. In this tutorial, we have used Visual C# 2010 Express.
You can download it from Microsoft Visual Studio. It gets installed automatically on your machine.
Note: You need an active internet connection for installing the express edition.
Although the.NET Framework runs on the Windows operating system, there are some alternative versions that work on other operating systems. Mono is an open-source version of the .NET Framework which includes a C# compiler and runs on several operating systems, including various flavors of Linux and Mac OS.
The stated purpose of Mono is not only to be able to run Microsoft .NET applications cross-platform, but also to bring better development tools for Linux developers. Mono can be run on many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris, and UNIX.
Before we study basic building blocks of the C# programming language, let us look at a bare minimum C# program structure so that we can take it as a reference in upcoming chapters.
A C# program consists of the following parts:
Let us look at a simple code that prints the words "Hello World":
When this code is compiled and executed, it produces the following result:
Hello World
Let us look at the various parts of the given program:
If you are using Visual Studio.Net for compiling and executing C# programs, take the following steps:
You can compile a C# program by using the command-line instead of the Visual Studio IDE:
C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, are said to be in the same class.
For example, let us consider a Rectangle object. It has attributes such as length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating the area, and displaying details.
Let us look at implementation of a Rectangle class and discuss C# basic syntax:
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75
The first statement in any C# program is
The using keyword is used for including the namespaces in the program. A program can include multiple using statements.
The class keyword is used for declaring a class.
Comments are used for explaining code. Compilers ignore the comment entries. The multiline comments in C# programs start with /* and terminates with the characters */ as shown below:
Single-line comments are indicated by the '//' symbol. For example,
Variables are attributes or data members of a class, used for storing data. In the preceding program, the Rectangle class has two member variables named length and width.
Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display.
In the preceding program, the class ExecuteRectangle contains the Main() method and instantiates the Rectangle class.
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows:
The varibles in C#, are categorized into the following types:
Value type variables can be assigned a value directly. They are derived from the class System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.
The following table lists the available value types in C# 2010:
Type | Represents | Range | Default Value |
---|---|---|---|
bool | Boolean value | True or False | False |
byte | 8-bit unsigned integer | 0 to 255 | 0 |
char | 16-bit Unicode character | U +0000 to U +ffff | '\0' |
decimal | 128-bit precise decimal values with 28-29 significant digits | (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 | 0.0M |
double | 64-bit double-precision floating point type | (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 | 0.0D |
float | 32-bit single-precision floating point type | -3.4 x 1038 to + 3.4 x 1038 | 0.0F |
int | 32-bit signed integer type | -2,147,483,648 to 2,147,483,647 | 0 |
long | 64-bit signed integer type | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 0L |
sbyte | 8-bit signed integer type | -128 to 127 | 0 |
short | 16-bit signed integer type | -32,768 to 32,767 | 0 |
uint | 32-bit unsigned integer type | 0 to 4,294,967,295 | 0 |
ulong | 64-bit unsigned integer type | 0 to 18,446,744,073,709,551,615 | 0 |
ushort | 16-bit unsigned integer type | 0 to 65,535 | 0 |
To get the exact size of a type or a variable on a particular platform, you can use the sizeof method. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:
When the above code is compiled and executed, it produces the following result:
Size of int: 4
he reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.
You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.
Syntax for declaring a dynamic type is:
For example,
Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.
The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms: quoted and @quoted.
For example,
A @quoted string literal looks as follows:
The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++.
Syntax for declaring a pointer type is:
For example,
We will discuss pointer types in the chapter 'Unsafe Codes'.
Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms:
The following example shows an explicit type conversion:
When the above code is compiled and executed, it produces the following result:
5673
C# provides the following built-in type conversion methods:
Sr.No | Methods & Description |
---|---|
1 | ToBoolean
Converts a type to a Boolean value, where possible. |
2 | ToByte
Converts a type to a byte. |
3 | ToChar
Converts a type to a single Unicode character, where possible. |
4 | ToDateTime
Converts a type (integer or string type) to date-time structures. |
5 | ToDecimal
Converts a floating point or integer type to a decimal type. |
6 | ToDouble
Converts a type to a double type. |
7 | ToInt16
Converts a type to a 16-bit integer. |
8 | ToInt32
Converts a type to a 32-bit integer. |
9 | ToInt64
Converts a type to a 64-bit integer. |
10 | ToSbyte
Converts a type to a signed byte type. |
11 | ToSingle
Converts a type to a small floating point number. |
12 | ToString
Converts a type to a string. |
13 | ToType
Converts a type to a specified type. |
14 | ToUInt16
Converts a type to an unsigned int type. |
15 | ToUInt32
Converts a type to an unsigned long type. |
16 | ToUInt64
Converts a type to an unsigned big integer. |
The following example converts various value types to string type:
When the above code is compiled and executed, it produces the following result:
75
53.005
2345.7652
True
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
The basic value types provided in C# can be categorized as:
Type | Example |
---|---|
Integral types | sbyte, byte, short, ushort, int, uint, long, ulong, and char |
Floating point types | float and double |
Decimal types | decimal |
Boolean types | true or false values, as assigned |
Nullable types | Nullable data types |
C# also allows defining other value types of variable such as enum and reference types of variables such as class, which we will cover in subsequent chapters.
Syntax for variable definition in C# is:
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas.
Some valid variable definitions are shown here:
You can initialize a variable at the time of definition as:
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is:
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as:
Some examples are:
int d = 3, f = 5; /* initializing d and f. */ byte z = 22; /* initializes z. */ double pi = 3.14159; /* declares an approximation of pi. */ char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.
The following example uses various types of variables:
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable.
For example,
The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.
There are two kinds of expressions in C#:
Variables are lvalues and hence they may appear on the left-hand side of an assignment. Numeric literals are rvalues and hence they may not be assigned and can not appear on the left-hand side. Following is a valid C# statement:
But following is not a valid statement and would generate compile-time error:
10 = 20;
The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.
An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals:
Following are other examples of various types of Integer literals:
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
Here are some examples of floating-point literals:
While representing in decimal form, you must include the decimal point, the exponent, or both; and while representing using exponential form you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\t'), or a universal character (such as '\u02C0').
There are certain characters in C# when they are preceded by a backslash. The have special meaning and they are used to represent like newline (\n) or tab (\t). Here, is a list of some of such escape sequence codes:
Escape sequence | Meaning |
---|---|
\\ | \ character |
\' | ' character |
\" | " character |
\? | ? character |
\a | Alert or bell |
\b | Backspace |
\f | Form feed |
\n | Newline |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\xhh . . . | Hexadecimal number of one or more digits |
Following is the example to show few escape sequence characters:
When the above code is compiled and executed, it produces the following result:
Hello World
String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating the parts using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
Constants are defined using the const keyword. Syntax for defining a constant is:
The following program demonstrates defining and using a constant in your program:
When the above code is compiled and executed, it produces the following result:
Enter Radius:
3
Radius: 3, Area: 28.27431
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C# has rich set of built-in operators and provides the following type of operators:
This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other operators one by one.
Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20 then:
Show Examples
Operator | Description | Example |
---|---|---|
+ | Adds two operands | A + B = 30 |
- | Subtracts second operand from the first | A - B = -10 |
* | Multiplies both operands | A * B = 200 |
/ | Divides numerator by de-numerator | B / A = 2 |
% | Modulus Operator and remainder of after an integer division | B % A = 0 |
++ | Increment operator increases integer value by one | A++ = 11 |
-- | Decrement operator decreases integer value by one | A-- = 9 |
Following table shows all the relational operators supported by C#. Assume variable A holds 10 and variable B holds 20, then:
Show Examples
Operator | Description | Example |
---|---|---|
== | Checks if the values of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value true and variable B holds Boolean value false, then:
Show Examples
Operator | Description | Example |
---|---|---|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is true. |
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows:
p | q | p & q | p | q | p ^ q |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:
Show Examples
Operator | Description | Example |
---|---|---|
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) = 12, which is 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) = 61, which is 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) = 49, which is 0011 0001 |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) = 61, which is 1100 0011 in 2's complement due to a signed binary number. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 = 240, which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 = 15, which is 0000 1111 |
There are following assignment operators supported by C#:
Show Examples
Operator | Description | Example |
---|---|---|
= | Simple assignment operator, Assigns values from right side operands to left side operand | C = A + B assigns value of A + B into C |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator | C &= 2 is same as C = C & 2 |
^= | bitwise exclusive OR and assignment operator | C ^= 2 is same as C = C ^ 2 |
|= | bitwise inclusive OR and assignment operator | C |= 2 is same as C = C | 2 |
There are few other important operators including sizeof, typeof and ? : supported by C#.
Show Examples
Operator | Description | Example |
---|---|---|
sizeof() | Returns the size of a data type. | sizeof(int), returns 4. |
typeof() | Returns the type of a class. | typeof(StreamReader); |
& | Returns the address of an variable. | &a; returns actual address of the variable. |
* | Pointer to a variable. | *a; creates pointer named 'a' to a variable. |
? : | Conditional Expression | If Condition is true ? Then value X : Otherwise value Y |
is | Determines whether an object is of a certain type. | If( Ford is Car) // checks if Ford is an object of the Car class. |
as | Cast without raising an exception if the cast fails. | Object obj = new StringReader("Hello");
StringReader r = obj as StringReader; |
Operator precedence determines the grouping of terms in an expression. This affects evaluation of an expression. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators are evaluated first.
Show Examples
Category | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Decision making structures requires the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most of the programming languages:
C# provides following types of decision making statements. Click the following links to check their detail.
Statement | Description |
---|---|
An if statement consists of a boolean expression followed by one or more statements. | |
An if statement can be followed by an optional else statement, which executes when the boolean expression is false. | |
You can use one if or else if statement inside another if or else if statement(s). | |
A switch statement allows a variable to be tested for equality against a list of values. | |
You can use one switch statement inside another switch statement(s). |
We have covered conditional operator ? : in previous chapter which can be used to replace if...else statements. It has the following general form:
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
There may be a situation, when you need to execute a block of code several number of times. In general, the statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or a group of statements multiple times and following is the general from of a loop statement in most of the programming languages:
C# provides following types of loop to handle looping requirements. Click the following links to check their detail.
Loop Type | Description |
---|---|
It repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body. | |
It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. | |
It is similar to a while statement, except that it tests the condition at the end of the loop body | |
You can use one or more loop inside any another while, for or do..while loop. |
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C# provides the following control statements. Click the following links to check their details.
Control Statement | Description |
---|---|
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. | |
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but programmers more commonly use the for(;;) construct to signify an infinite loop.
Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details.
Abstraction and encapsulation are related features in object oriented programming.
Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction.
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers:
Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
The following example illustrates this:
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle class, named r.
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
The following example illustrates this:
When the above code is compiled and executed, it produces the following result:
Enter Length:
4.4
Enter Width:
3.3
Length: 4.4
Width: 3.3
Area: 14.52
In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r.
Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. We will discuss this in more details in the inheritance chapter.
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
The following program illustrates this:
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, notice that the member function GetArea() is not declared with any access specifier. Then what would be the default access specifier of a class member if we don't mention any? It is private.
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main.
To use a method, you need to:
When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows:
Following are the various elements of a method:
Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance of the class.
You can call a method using the name of the method. The following example illustrates this:
When the above code is compiled and executed, it produces the following result:
Max value is : 200
You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.
When the above code is compiled and executed, it produces the following result:
Max value is : 200
A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:
When the above code is compiled and executed, it produces the following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
When method with parameters is called, you need to pass the parameters to the method. There are three ways that parameters can be passed to a method:
Mechanism | Description |
---|---|
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. | |
This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument. | |
This method helps in returning more than one value. |
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<<bool> variable. Syntax for declaring a nullable type is as follows:
The following example demonstrates use of nullable data types:
When the above code is compiled and executed, it produces the following result:
Nullables at Show: , 45, , 3.14157
A Nullable boolean value:
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this:
When the above code is compiled and executed, it produces the following result:
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To declare an array in C#, you can use the following syntax:
where
For example,
Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array. For example,
You can assign values to individual array elements, by using the index number, like:
You can assign values to the array at the time of declaration, as shown:
You can also create and initialize an array, as shown:
You may also omit the size of the array, as shown:
You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location:
When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example,
The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays:
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
In the previous example, we used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array.
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
There are following few important concepts related to array which should be clear to a C# programmer:
Concept | Description |
---|---|
C# supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. | |
C# supports multidimensional arrays, which are arrays of arrays. | |
You can pass to the function a pointer to an array by specifying the array's name without an index. | |
This is used for passing unknown number of parameters to a function. | |
Defined in System namespace, it is the base class to all arrays, and provides various properties and methods for working with arrays. |
You can create string object using one of the following methods:
The following example demonstrates this:
When the above code is compiled and executed, it produces the following result:
Full Name: Rowan Atkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
The String class has the following two properties:
Sr.No | Property |
---|---|
1 | Chars
Gets the Char object at a specified position in the current String object. |
2 | Length
Gets the number of characters in the current String object. |
The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods:
Sr.No | Methods |
---|---|
1 | public static int Compare(string strA, string strB)
Compares two specified string objects and returns an integer that indicates their relative position in the sort order. |
2 | public static int Compare(string strA, string strB, bool ignoreCase )
Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true. |
3 | public static string Concat(string str0, string str1)
Concatenates two string objects. |
4 | public static string Concat(string str0, string str1, string str2)
Concatenates three string objects. |
5 | public static string Concat(string str0, string str1, string str2, string str3)
Concatenates four string objects. |
6 | public bool Contains(string value)
Returns a value indicating whether the specified String object occurs within this string. |
7 | public static string Copy(string str)
Creates a new String object with the same value as the specified string. |
8 | public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters. |
9 |
public bool EndsWith(string value)
Determines whether the end of the string object matches the specified string. |
10 |
public bool Equals(string value)
Determines whether the current String object and the specified String object have the same value. |
11 |
public static bool Equals(string a, string b)
Determines whether two specified String objects have the same value. |
12 |
public static string Format(string format, Object arg0)
Replaces one or more format items in a specified string with the string representation of a specified object. |
13 |
public int IndexOf(char value)
Returns the zero-based index of the first occurrence of the specified Unicode character in the current string. |
14 |
public int IndexOf(string value)
Returns the zero-based index of the first occurrence of the specified string in this instance. |
15 |
public int IndexOf(char value, int startIndex)
Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position. |
16 |
public int IndexOf(string value, int startIndex)
Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position. |
17 |
public int IndexOfAny(char[] anyOf)
Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. |
18 |
public int IndexOfAny(char[] anyOf, int startIndex)
Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position. |
19 |
public string Insert(int startIndex, string value)
Returns a new string in which a specified string is inserted at a specified index position in the current string object. |
20 |
public static bool IsNullOrEmpty(string value)
Indicates whether the specified string is null or an Empty string. |
21 |
public static string Join(string separator, params string[] value)
Concatenates all the elements of a string array, using the specified separator between each element. |
22 |
public static string Join(string separator, string[] value, int startIndex, int count)
Concatenates the specified elements of a string array, using the specified separator between each element. |
23 |
public int LastIndexOf(char value)
Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object. |
24 |
public int LastIndexOf(string value)
Returns the zero-based index position of the last occurrence of a specified string within the current string object. |
25 |
public string Remove(int startIndex)
Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string. |
26 |
public string Remove(int startIndex, int count)
Removes the specified number of characters in the current string beginning at a specified position and returns the string. |
27 |
public string Replace(char oldChar, char newChar)
Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string. |
28 |
public string Replace(string oldValue, string newValue)
Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string. |
29 |
public string[] Split(params char[] separator)
Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. |
30 |
public string[] Split(char[] separator, int count)
Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return. |
31 |
public bool StartsWith(string value)
Determines whether the beginning of this string instance matches the specified string. |
32 |
public char[] ToCharArray()
Returns a Unicode character array with all the characters in the current string object. |
33 | public char[] ToCharArray(int startIndex, int length)
Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length. |
34 |
public string ToLower()
Returns a copy of this string converted to lowercase. |
35 |
public string ToUpper()
Returns a copy of this string converted to uppercase. |
36 |
public string Trim()
Removes all leading and trailing white-space characters from the current String object. |
You can visit MSDN library for the complete list of methods and String class constructors.
The following example demonstrates some of the methods mentioned above:
Comparing Strings:When the above code is compiled and executed, it produces the following result:
This is test and This is text are not equal.
When the above code is compiled and executed, it produces the following result:
The sequence 'test' was found.
When the above code is compiled and executed, it produces the following result:
San Pedro
When the above code is compiled and executed, it produces the following result:
Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.
For example, here is the way you can declare the Book structure:
The following program shows the use of the structure:
When the above code is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
You have already used a simple structure named Books. Structures in C# are quite different from that in traditional C or C++. The C# structures have the following features:
Classes and Structures have the following basic differences:
In the light of the above discussions, let us rewrite the previous example:
When the above code is compiled and executed, it produces the following result:
Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700
An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.
C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
The general syntax for declaring an enumeration is:
Where,
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example:
The following example demonstrates use of enum variable:
When the above code is compiled and executed, it produces the following result:
Monday: 1
Friday: 5
When you define a class, you define a blueprint for a data type. This does not actually define any data, but it does define what the class name means. That is, what an object of the class consists of and what operations can be performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class.
A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. Following is the general form of a class definition:
The following example illustrates the concepts discussed so far:
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
A member function of a class is a function that has its definition or its prototype within the class definition similar to any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class:
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
A class constructor is a special member function of a class that is executed whenever we create new objects of that class.
A constructor has exactly the same name as that of class and it does not have any return type. Following example explains the concept of constructor:
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
A default constructor does not have any parameter but if you need, a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example:
When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6
A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope. A destructor has exactly the same name as that of the class with a prefixed tilde (~) and it can neither return a value nor can it take any parameters.
Destructor can be very useful for releasing memory resources before exiting the program. Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor:
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Object is being deleted
We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.
The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.
The following example demonstrates the use of static variables:
When the above code is compiled and executed, it produces the following result:
Variable num for s1: 6
Variable num for s2: 6
You can also declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created. The following example demonstrates the use of static functions:
When the above code is compiled and executed, it produces the following result:
Variable num: 3
One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on.
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.
The syntax used in C# for creating derived classes is as follows:
Consider a base class Shape and its derived class Rectangle:
When the above code is compiled and executed, it produces the following result:
Total area: 35
The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list.
The following program demonstrates this:
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program demonstrates this:
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Base class PaintCost public interface PaintCost { int getCost(int area); } // Derived class class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area)); Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following result:
Total area: 35
Total paint cost: $2450
The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are:
We discuss operator overloading in next chapter.
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
The following example shows using function print() to print different data types:
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.
Here are the rules about abstract classes:
The following program demonstrates an abstract class:
When the above code is compiled and executed, it produces the following result:
Rectangle class area :
Area: 70
When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this:
When the above code is compiled and executed, it produces the following result:
Rectangle class area:
Area: 70
Triangle class area:
Area: 25
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list.>
>
For example, go through the following function:
The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.
The following program shows the complete implementation:
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
The following table describes the overload ability of the operators in C#:
Operators | Description |
---|---|
+, -, !, ~, ++, -- | These unary operators take one operand and can be overloaded. |
+, -, *, /, % | These binary operators take one operand and can be overloaded. |
==, !=, <, >, <=, >= | The comparison operators can be overloaded |
&&, || | The conditional logical operators cannot be overloaded directly. |
+=, -=, *=, /=, %= | The assignment operators cannot be overloaded. |
=, ., ?:, ->, new, is, sizeof, typeof | These operators cannot be overloaded. |
In the light of the above discussions, let us extend the preceding example, and overload few more operators:
When the above code is compiled and executed, it produces the following result:
Box 1: (6, 7, 5)
Box 2: (12, 13, 10)
Volume of Box1 : 210
Volume of Box2 : 1560
Box 3: (18, 20, 15)
Volume of Box3 : 5400
Box1 is not greater than Box2
Box1 is less than Box2
Box1 is not greater or equal to Box2
Box1 is less or equal to Box2
Box1 is not equal to Box2
Box3 is equal to Box4
An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.
Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities.
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration:
The following example demonstrates implementation of the above interface:
When the above code is compiled and executed, it produces the following result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:
The following program demonstrates use of namespaces:
When the above code is compiled and executed, it produces the following result:
Inside first_space
Inside second_space
The using keyword states that the program is using the names in the given namespace. For example, we are using the System namespace in our programs. The class Console is defined there. We just write:
We could have written the fully qualified name as:
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code:
Let us rewrite our preceding example, with using directive:
When the above code is compiled and executed, it produces the following result:
Inside first_space Inside second_space
You can define one namespace inside another namespace as follows:
You can access members of nested namespace by using the dot (.) operator as follows:
When the above code is compiled and executed, it produces the following result:
Inside first_space
Inside second_space
The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).
C# compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In C# the preprocessor directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros. A preprocessor directive must be the only instruction on a line.
The following table lists the preprocessor directives available in C#:
Preprocessor Directive | Description. |
---|---|
#define | It defines a sequence of characters, called symbol. |
#undef | It allows you to undefine a symbol. |
#if | It allows testing a symbol or symbols to see if they evaluate to true. |
#else | It allows to create a compound conditional directive, along with #if. |
#elif | It allows creating a compound conditional directive. |
#endif | Specifies the end of a conditional directive. |
#line | It lets you modify the compiler's line number and (optionally) the file name output for errors and warnings. |
#error | It allows generating an error from a specific location in your code. |
#warning | It allows generating a level one warning from a specific location in your code. |
#region | It lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor. |
#endregion | It marks the end of a #region block. |
The #define preprocessor directive creates symbolic constants.
#define lets you define a symbol such that, by using the symbol as the expression passed to the #if directive, the expression evaluates to true. Its syntax is as follows:
The following program illustrates this:
When the above code is compiled and executed, it produces the following result:
PI is defined
You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.
Syntax for conditional directive is:
Where, symbol is the name of the symbol you want to test. You can also use true and false or prepend the symbol with the negation operator.
The operator symbol is the operator used for evaluating the symbol. Operators could be either of the following:
ou can also group symbols and operators with parentheses. Conditional directives are used for compiling code for a debug build or when compiling for a specific configuration. A conditional directive beginning with a #if directive must explicitly be terminated with a #endif directive.
The following program demonstrates use of conditional directives:
When the above code is compiled and executed, it produces the following result:
DEBUG and VC_V10 are defined
A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.
There are various categories of characters, operators, and constructs that lets you to define regular expressions. Click the follwoing links to find these constructs.
The Regex class is used for representing a regular expression. It has the following commonly used methods:
Sr.No | Methods |
---|---|
1 |
public bool IsMatch(string input)
Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string. |
2 | public bool IsMatch(string input, int startat)
Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string. |
3 | public static bool IsMatch(string input, string pattern)
Indicates whether the specified regular expression finds a match in the specified input string. |
4 |
public MatchCollection Matches(string input)
Searches the specified input string for all occurrences of a regular expression. |
5 | public string Replace(string input, string replacement)
In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string. |
6 |
public string[] Split(string input)
Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor. |
For the complete list of methods and properties, please read the Microsoft documentation on C#.
The following example matches words that start with 'S':
When the above code is compiled and executed, it produces the following result:
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
The following example matches words that start with 'm' and ends with 'e':
When the above code is compiled and executed, it produces the following result:
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
When the above code is compiled and executed, it produces the following result:
Original String: Hello World
Replacement String: Hello World
This example replaces extra white space:
An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.
Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs.
Hence the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
Exception Class | Description |
---|---|
System.IO.IOException | Handles I/O errors. |
System.IndexOutOfRangeException | Handles errors generated when a method refers to an array index out of range. |
System.ArrayTypeMismatchException | Handles errors generated when type is mismatched with the array type. |
System.NullReferenceException | Handles errors generated from deferencing a null object. |
System.DivideByZeroException | Handles errors generated from dividing a dividend with zero. |
System.InvalidCastException | Handles errors generated during typecasting. |
System.OutOfMemoryException | Handles errors generated from insufficient free memory. |
System.StackOverflowException | Handles errors generated from stack overflow. |
C# provides a structured solution to the exception handling in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.
These error handling blocks are implemented using the try, catch, and finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs:
When the above code is compiled and executed, it produces the following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
You can also define your own exception. User-defined exception classes are derived from the Exception class. The following example demonstrates this:
When the above code is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as:
file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).
The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace:
I/O Class | Description |
---|---|
BinaryReader | Reads primitive data from a binary stream. |
BinaryWriter | Writes primitive data in binary format. |
BufferedStream | A temporary storage for a stream of bytes. |
Directory | Helps in manipulating a directory structure. |
DirectoryInfo | Used for performing operations on directories. |
DriveInfo | Provides information for the drives. |
File | Helps in manipulating files. |
FileInfo | Used for performing operations on files. |
FileStream | Used to read from and write to any location in a file. |
MemoryStream | Used for random access to streamed data stored in memory. |
Path | Performs operations on path information. |
StreamReader | Used for reading characters from a byte stream. |
StreamWriter | Is used for writing characters to a stream. |
StringReader | Is used for reading from a string buffer. |
StringWriter | Is used for writing into a string buffer. |
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows:
For example, we create a FileStream object F for reading a file named sample.txt as shown:
Parameter | Description |
---|---|
FileMode | The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
|
FileAccess | FileAccess enumerators have members: Read, ReadWrite and Write. |
FileShare | FileShare enumerators have the following members:
|
The following program demonstrates use of the FileStream class:
When the above code is compiled and executed, it produces the following result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
The preceding example provides simple file operations in C#. However, to utilize the immense powers of C# System.IO classes, you need to know the commonly used properties and methods of these classes.
Topic and Description |
---|
Reading from and Writing into Text files It involves reading from and writing into text files. The StreamReader and StreamWriter class helps to accomplish it. |
Reading from and Writing into Binary files It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class helps to accomplish this. |
Manipulating the Windows file system It gives a C# programamer the ability to browse and locate Windows files and directories. |