Cooper Alvin - Computer Programming - Learn Any Programming Language in 2 Hours (2018)
Cooper Alvin - Computer Programming - Learn Any Programming Language in 2 Hours (2018)
Table Of Contents
Computer Programming
This Book Includes:
Table Of Contents
HTML & CSS
Introduction
Chapter 1: Overview
Basic HTML Document
Tags in HTML
Document Structure
The <DOCTYPE> Declaration
Chapter 2: Basic Tags
Headings
Paragraph
Line Break
Centering Content
Horizontal Lines
Preformatted Tag
Non-Breaking Spaces
Elements in HTML
Chapter 3: Attributes
Core Attributes
Internationalization Attributes
Generic Attributes
Align
Valign
Bgcolor
Background
ID
Class
Width
Height
Title
Chapter 4: Formatting
Bold Text
Italic Text
Underlined Text
Strike Text
Monospaced Text
Superscript Text
Subscript Text
Inserted Text
Deleted Text
Larger Text
Small Text
Grouping Content
Chapter 5: Phrase Tags
Emphasized Text
Marked Text
Strong Text
Text Abbreviation
Acronym Element
Text Direction
Chapter 6: Meta Tags
How to Add Metatags
Name
Content
Scheme
http-equiv
Specifying Keywords
Document Description
Document Revision Date
Refreshing Document
Page Redirection
How to Set Cookies
How to Set Author Name
Chapter 7: Comments
Valid and Invalid
Multi-line Comments
Conditional Comments
The Comment Tag
How to Incorporate Comments in Script Code
How to Comment Style Sheets
Chapter 8: Images
Inserting Images
Setting the Height and Width of Images
How to Set the Border of Image
How to Align Images
Chapter 9: Tables
Heading
Attributes for Cellspacing and Cellpadding
Rowspan and Colspan
Setting Background for Tables
Setting Height and Width of Tables
Caption
Header, Footer and Body of Table
Chapter 10: Lists
Unordered Lists
Ordered Lists
Definition Lists
Chapter 11: Links
Text Links
self
top
parent
targetframe
Image Links
Chapter 12: Cascading Style Sheets
Internal Style Sheet
External Style Sheets
Inline Style Sheet
Internal Style Sheet
External Style Sheets
Inline Style Sheet
Conclusion
Java
Introduction
Chapter 1: Getting Started With Java
Requirements to Get Started
Getting a Local Setup Ready
Windows
Linux/FreeBSD/Unix/Solaris
Chapter 2: Writing Your First Java Program
Identifiers
Modifiers
Variables
Arrays
Enums
Keywords
Comments
Blank Lines
Implementing Inheritance
Interfaces
Chapter 3: Data Types
Primitive Data Types
byte
short
int
long
float
double
boolean
char
Reference Data Types
Java Literals
Chapter 4: Variables
Local Variables
Instance Variables
Static Variables
Modifier Types
Chapter 5: Operators
Arithmetic Operators
Addition (+)
Multiplication (*)
Subtraction (-)
Division (/)
Modulus (%)
Increment (++)
Decrement (--)
Relational Operators
NOT EQUAL TO (!=)
EQUAL TO (==)
GREATER THAN (>)
LESS THAN (<)
GREATER THAN OR EQUAL TO
LESS THAN OR EQUAL TO
Bitwise Operators
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise COMPLEMENT (~)
LEFT SHIFT (<<)
RIGHT SHIFT (>>)
ZERO FILL RIGHT SHIFT (>>>)
Logical Operators
Logical AND
Logical OR
Logical NOT
Assignment Operators
Simple Assignment Operator (=)
Add AND Assignment Operator (+=)
Subtract AND Assignment Operator (-=)
Multiply AND Assignment Operator (*=)
Divide AND Assignment Operator (/=)
Modulus AND Assignment Operator (/=)
Left Shift AND Assignment Operator (<<=)
Right Shift AND Assignment Operator (>>=)
Bitwise AND Assignment Operator (&=)
Bitwise XOR AND Assignment Operator (^=)
Bitwise Inclusive OR and Assignment Operator (|=)
Operator Precedence
Right to Left
Left to Right
Chapter 6: Objects and Classes
Creating Objects
Constructors
Variable Arguments
Implementing Methods
Calling a Method
Method Overloading
Making Use of Command Line Arguments
The finalize () Method
Declaration Rules for Source File
Chapter 7: Decision Making
If statement
If else statement
Nested if statement
Switch
Conditional Operator
Chapter 8: Loop Control
Loop statements
break
continue
For Loop Implementation
While Loop Implementation
Do While Loop Implementation
Enhanced For Loop
Chapter 9: File Handling
Byte Streams
Character Streams
Standard Streams
Chapter 10: Exception Handling
Checked Exceptions
Unchecked Exceptions
Errors
Exception Hierarchy
public String getMessage()
public Throwable getCause()
public String toString()
public void printStackTrace()
public StackTraceElement [] getStackTrace()
public Throwable fillInStackTrace()
Catching Exceptions
Implementing Multiple Catch Blocks
Keywords: Throw/Throws
Finally Block
User-defined Exceptions
Conclusion
Javascript
Introduction
Chapter 1: Basics of JavaScript
ECMA-262 Specification for JavaScript
Server-Client Interactions
JavaScript vs. Traditional CGI Server-Side Scripting
Development Tools
Chapter 2: Syntax
Type
Language
Writing Your First JavaScript
Line Breaks and Whitespaces
Optional Use of Semicolons
Case Sensitivity
Writing Comments
Chapter 3: Enabling JavaScript in Browsers
Internet Explorer (IE)
Firefox
Chrome
Programming in JavaScript for Non-JavaScript Browsers
Chapter 4: Placement of JavaScript in Files
Writing JavaScript into External Files
Chapter 5: Variables
Boolean
Strings
Numbers
Declaration and Initialization of Variables
Scope of Variables
Local Variable
Global Variable
Names of Variables
Keywords or Reserved Words in JavaScript
Chapter 6: Operators
Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Increment (++)
Decrement (--)
Comparison Operators
Equal (==)
Not Equal (!=)
Greater Than (>)
Less Than (<)
Greater Than Or Equal To (>=)
Less Than Or Equal To (<=)
Logical Operators
Local AND (&&)
Local OR (||)
Local NOT (!)
Bitwise Operators
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Left Shift (<<)
Right Shift (>>)
Right Shift With Zero (>>>)
Assignment Operators
Simple Assignment (=)
Add and Assignment (+=)
Subtract and Assignment (-=)
Multiply and Assignment (*=)
Divide and Assignment (*=)
Modulus and Assignment (%=)
Miscellaneous Operators
Chapter 7: Decision Making
The if statement
The if else statement
The if else if statement
Switch
Conditional Operator
Chapter 8: Loop Constructs
While Loop
Do…While Loop
For Loop
For…In Loop
Controlling the Loop
Break Statement
Continue Statement
Labels for Controlling Loop Flow
Chapter 9: Functions
Defining a Function
Calling a Function
Dealing With Function Parameters
Return Statement
Void Keyword
Chapter 10: Events
onClick Event Type
onSubmit Event Type
Onmouseover and Onmouseout
Chapter 11: Cookies
How Cookies Work
Domain
Expires
Name-Value
Secure
Path
Storing Cookies
Reading Cookies
Setting Expiry Date
How to Delete a Cookie
Chapter 12: Page Redirection
Working of Page Redirection
Chapter 13: Dialog Boxes
Dialog Box for Alert Messages
Dialog Boxes for Confirmation
Dialog Boxes for Prompt
Chapter 14: Page Printing
Conclusion
SQL
Introduction
Chapter 1: Overview of SQL
What is SQL?
The Process
Commands
CREATE
ALTER
DROP
SELECT
DELETE
UPDATE
INSERT
GRANT
REVOKE
Chapter 2: Introduction to RDBMS
Table
Fields
Record
Null Value
Constraints in SQL
NOT NULL
DEFAULT
UNIQUE
PRIMARY Key
FOREIGN Key
CHECK
INDEX
Data Integrity
Entity Integrity
Domain Integrity
Referential Integrity
User-defined Integrity
Normalization
Chapter 3: Knowing Databases
MySQL
MS SQL Server
Oracle
MS Access
Chapter 4: Syntax
SELECT Statement
SQL WHERE Clause
DISTINCT Clause
AND/OR Clause
BETWEEN Clause
IN Clause
ORDER BY Clause
LIKE Clause
COUNT Clause
GROUP BY Clause
HAVING Clause
CREATE TABLE Statement
CREATE INDEX Statement
DROP TABLE Statement
SQL DROP INDEX Statement
SQL TRUNCATE TABLE Statement
SQL DESC Statement
SQL ALTER TABLE Statement (Rename)
SQL ALTER TABLE Statement
SQL INSERT INTO Statement
SQL DELETE Statement
SQL UPDATE Statement
SQL CREATE DATABASE Statement
SQL USE Statement
SQL DROP DATABASE Statement
SQL ROLLBACK Statement
SQL COMMIT Statement
Chapter 5: Data Types
Exact Numeric
Approximate Numeric
Data and Time
Character Strings
Unicode Character Strings
Binary
Miscellaneous Data types
timestamp
sql_variant
cursor
xml
uniqueidentifier
table
Chapter 6: Operators
Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Comparison Operators
Equal (==)
Not Equal (!= and <>)
Greater Than (>)
Less Than (<)
Greater Than Or Equal To (>=)
Less Than Or Equal To (<=)
Not Less Than (!<)
Not Greater Than (!>)
Logical Operators
ALL
ANY
BETWEEN
AND
OR
EXISTS
LIKE
IN
NOT
UNIQUE
IS NULL
Chapter 7: Expressions
Boolean Expressions
Numeric Expression
Date Expressions
Chapter 8: Working With Databases
Create Database
Drop Database
Select Database
Chapter 9: Working With Tables
Create Table
Drop Table
Inserting Records Into Tables
Selecting Records From Tables
Where Clause
Updating Records
Deleting Records
Chapter 10: Conjunctive Operators
The AND Operator
The OR Operator
Chapter 11: LIKE Clause
WHERE EMP_SAL LIKE ‘400%’
WHERE EMP_SAL LIKE ‘%400%’
WHERE EMP_SAL LIKE ‘_400%’
WHERE EMP_SAL LIKE ‘2_%_%’
WHERE EMP_SAL LIKE ‘%4’
WHERE EMP_SAL LIKE ‘_4%3’
WHERE EMP_SAL LIKE ‘2____7’
Chapter 12: TOP Clause
Chapter 13: ORDER BY Clause
Chapter 14: GROUP BY Clause
Chapter 15: DISTINCT Keyword
SELECT DISTINCT col1, col2,.....colN FROM t_name WHERE [cond];
SELECT NAME FROM CUST;
SELECT DISTINCT NAME FROM CUST;
SELECT DISTINCT NAME FROM CUST ORDER BY NAME;
Chapter 16: Joins
Inner Join
SQL Left Join
SQL Full Join
Self Join
Cartesian Join
Conclusion
Python
Introduction
Chapter 1: Overview
History
Key Features
Easy to read, learn and maintain
Availability of Standard Library
Hardware Portability
Allows Interaction Between Developer and Interpreter
Scalable
GUI Programming
Databases
Extendable
Other Features
Chapter 2: Environmental Setup
Local Setup
Getting Python
Installing Python
Unix/Linux
Windows
Macintosh
Setting the PATH
Unix/Linux
Setting Path Using CSH Shell
Setting Path Using Bash Shell
Setting Path Using SH or KSH Shell
Windows
Environment Variables
PYTHONPATH
PYTHONSTARTUP
PYTHONCASEOK
PYTHONHOME
Running Python
Interactive Interpreter
From Command Line
Chapter 3: Basic Syntax
First Python Program
Identifiers in Python
Reserved Words
Lines and Indentation
Multiple Line Statements
The Use of Quotations
Comments
Blank Lines
Waiting for User
Many Statements on One Line
Suites
Command Line Arguments
Chapter 4: Variables
Assigning Values to Variables
Multiple Assignment
Standard Data Types in Python
Numbers
int
float
long
complex
Strings
Lists
Tuples
Dictionary
Data Type Conversion
int(x, [,base])
long(x, [,base])
float(x)
complex(real [,imag])
str(x)
repr(x)
eval(str)
tuple(s)
list(s)
set(s)
dict(d)
frozenset(s)
chr(x)
unichr(x)
ord(x)
hex(x)
oct(x)
Chapter 5: Operators
Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Exponent (**)
Floor Division (//)
Relational Operators
Equal To (==)
Not Equal To (!=)
Not Equal To (<>)
Greater Than (>)
Less Than (<)
Greater Than Or Equal To (>=)
Less Than Or Equal To (<=)
Assignment Operators
Equal To (=)
Add and Assignment (+=)
Subtract and Assignment (-=)
Multiply and Assignment (*=)
Divide and Assignment (/=)
Modulus and Assignment (%=)
Exponent and Assignment (**=)
Floor and Assignment (//=)
Logical Operators
Logical AND
Logical OR
Logical NOT
Bitwise Operators
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise COMPLEMENT (~)
LEFT SHIFT (<<)
RIGHT SHIFT (>>)
Membership Operators
In Operator
Not In Operator
Identity Operators
Is Operator
Is Not Operator
Operator Precedence in Python
Chapter 6: Decision Making
If statement
If-else statement
Nested if statements
Single Statement Suites
Chapter 7: Loops
While Loop
For Loop
Nested Loops
Control Statements
Break
Continue
Pass
Chapter 8: Functions
Defining a Function
Calling a Function
Passing Data to Functions by Value and Reference
Function Arguments
Anonymous Functions
Return Statement
Scope of Variables
Chapter 9: Modules
The import Statement
The from…import Statement
The from…import * Statement
Locating Modules
Scoping and Namespaces
The dir() Function
The locals() and globals() Functions
The reload() Function
Packages
Conclusion
PHP
Introduction
Chapter 1: Overview
Characteristics and Uses
First PHP Program
Environmental Setup
Web Server
Database
PHP Parser
Installing Parser for PHP
Chapter 2: Syntax
Escaping to PHP
Canonical PHP Tags
Short-Open (SGML-style) Tags
ASP-style Tags
HTML Script Tags
Comments in PHP
Executing a PHP Script
Chapter 3: Variables
Booleans
Integers
Doubles
Strings
NULL
Arrays
Objects
Resources
Scope of Variables
Giving Names to Variables
Chapter 4: Constants
Constant Function
Difference Between Constants and Variables
Magic Constants
Chapter 5: Operators
Arithmetic Operators
Addition (+)
Multiplication (*)
Subtraction (-)
Division (/)
Modulus (%)
Increment (++)
Decrement (--)
Comparison Operators
NOT EQUAL TO (!=)
EQUAL TO (==)
GREATER THAN (>)
LESS THAN (<)
GREATER THAN OR EQUAL TO (>=)
LESS THAN OR EQUAL TO (<=)
Logical Operators
And
Or
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
Assignment Operators
Simple Assignment Operator (=)
Add AND Assignment Operator (+=)
Subtract AND Assignment Operator (-=)
Multiply AND Assignment Operator (*=)
Divide AND Assignment Operator (/=)
Modulus AND Assignment Operator (%=)
Conditional Operator (?:)
Operator Precedence
Right to Left
Left to Right
Chapter 6: Decision Making
The if…else Statement
The else if Statement
Switch Statement
Chapter 7: Loops
The for Statement
The while Statement
The do…while Statement
The foreach Statement
The break Statement
The continue Statement
Chapter 8: Arrays
Numeric Array
Associative Arrays
Multi-dimensional Arrays
Chapter 9: Strings
Concatenating Strings
Finding String Length
Finding Character or String in a String
Chapter 10: Functions
How to Create Functions in PHP
Giving Input to Functions
Returning Values from Functions
Giving Function Parameters Default Values
Dynamic Function Calls
Chapter 11: Files in PHP
The include() Function
The require() Function
File I/O
Chapter 12: Web Concepts
Identification of Browser and Platform
Random Display of Images
HTML Forms
Browser Redirection
Chapter 13: GET and POST Methods
The GET Method
The POST Method
The $_REQUEST Variable
Conclusion
C++
Introduction
Chapter 1: Overview
The ANSI Standard
Why C++?
Environment Setup
Chapter 2: Syntax
A C++ Program
Identifiers
Keywords
Classes and Objects
Chapter 3: Data Types
Built-in Data Types
Boolean
Character
Integer
Floating Point
Double Floating Point
Valueless
Wide Character
Typedef Declarations
Enumerated Data Types
Chapter 4: Variables
Rvalues and Lvalues
Scope of Variables
Type Qualifiers
Storage Classes
Auto Class
Register Class
Static Class
Extern Class
Mutable Class
Chapter 5: Constants or Literals
Integer Literals
Floating Point Literals
Boolean Literals
Character Literals
String Literals
Declaring and Defining Constants or Literals
Chapter 6: Operators
Arithmetic Operators
Addition (+)
Multiplication (*)
Subtraction (-)
Division (/)
Modulus (%)
Increment (++)
Decrement (--)
Relational Operators
NOT EQUAL TO (!=)
EQUAL TO (==)
GREATER THAN (>)
LESS THAN (<)
GREATER THAN OR EQUAL TO (>=)
LESS THAN OR EQUAL TO (<=)
Bitwise Operators
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise COMPLEMENT (~)
LEFT SHIFT (<<)
RIGHT SHIFT (>>)
Logical Operators
Logical AND
Logical OR
Logical NOT
Assignment Operators
Simple Assignment Operator (=)
Add AND Assignment Operator (+=)
Subtract AND Assignment Operator (-=)
Multiply AND Assignment Operator (*=)
Divide AND Assignment Operator (/=)
Modulus AND Assignment Operator (%=)
Left Shift AND Assignment Operator (<<=)
Right Shift AND Assignment Operator (>>=)
Bitwise AND Assignment Operator (&=)
Bitwise XOR AND Assignment Operator (^=)
Bitwise Inclusive OR and Assignment Operator (|=)
Miscellaneous Operators
sizeof
Conditional Operator (?:)
condition?a:y;
Comma Operator (,)
Dot (.) and Arrow (->)
Cast
Pointer Operator (& and *)
Operator Precedence
Right to Left
Left to Right
Chapter 7: Loop Constructs
For Loop
While Loop
Do…While Loop
Nested Loop
Loop Control Statements
Break
Continue
Goto
The Infinite Loop
Chapter 8: Decision Making
If statement
If else statement
Nested if statements
Switch statement
Nested switch statements
Chapter 9: Functions
Implementing Functions
Declaring and Defining a Function
Calling a Function
Call by Value
Call by Pointer
Call by Reference
Setting Default Values for Parameters
Chapter 10: Numbers
Performing Mathematical Functions
double cos(double)
double sin(double)
double tan(double)
double log(double)
double pow(double, double)
double hypot(double, double)
double sqrt(double)
int abs(int)
double fabs(double)
double floor(double)
Random Numbers
Chapter 11: Arrays
Declaring Arrays
Initializing Arrays
Accessing Elements of Array
Chapter 12: Strings
C-Style Strings
strcpy (s1, s2)
strcat (s1, s2)
strlen(s)
strcmp (s1, s2)
strchr (s, ch)
strstr (s1, s2)
String Class
Conclusion
C#
Introduction
Chapter 1: Getting Started
The .NET Framework
Integrated Development Environment for C#
Chapter 2: Program Structure
Sample Program
Compiling and Executing Programs
Chapter 3: Syntax
The using Keyword
The class Keyword
Writing Comments in C#
Members of the Class
Creating Objects
Identifiers
Keywords
Chapter 4: Data Types
Value Type
Bool
Byte
Char
Decimal
Double
Float
Int
Long
Sbyte
Short
Uint
Ulong
Ushort
Reference Type Variables
Object Type
Dynamic Type
String Type
Pointer Type
Type Conversion
Type Conversion Methods
Chapter 5: Variables
Integral Types
Floating Point Types
Decimal Types
Boolean Types
Nullable Types
Defining Variables
Rvalue and Lvalue Expressions
Chapter 6: Constants and Literals
Integer Literals
Floating Point Literals
Character Literals
String Literals
Declaring and Defining Constants or Literals
Chapter 7: Operators
Arithmetic Operators
Addition (+)
Multiplication (*)
Subtraction (-)
Division (/)
Modulus (%)
Increment (++)
Decrement (--)
Relational Operators
NOT EQUAL TO (!=)
EQUAL TO (==)
GREATER THAN (>)
LESS THAN (<)
GREATER THAN OR EQUAL TO (>=)
LESS THAN OR EQUAL TO (<=)
Logical Operators
Logical AND
Logical OR
Logical NOT
Bitwise Operators
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise COMPLEMENT (~)
LEFT SHIFT (<<)
RIGHT SHIFT (>>)
Assignment Operators
Simple Assignment Operator (=)
Add AND Assignment Operator (+=)
Subtract AND Assignment Operator (-=)
Multiply AND Assignment Operator (*=)
Divide AND Assignment Operator (/=)
Modulus AND Assignment Operator (%=)
Left Shift AND Assignment Operator (<<=)
Right Shift AND Assignment Operator (>>=)
Bitwise AND Assignment Operator (&=)
Bitwise XOR AND Assignment Operator (^=)
Bitwise Inclusive OR and Assignment Operator (|=)
Miscellaneous Operators
sizeof
typeof
Pointer Operator (& and *)
Conditional Operator (?:)
Is Operator
As Operator
Operator Precedence
Chapter 8: Decision Making
If Statement
If Else Statement
Nested If Statements
Switch Statement
Nested Switch Statements
Conditional Operator
Chapter 9: Loops
For Loop
While Loop
Do…While Loop
Nested Loop
Loop Control Statements
Break
Continue
Goto
The Infinite Loop
Chapter 10: Classes and Objects
Defining a Class
Encapsulation in C#
Constructors and Destructors
Static Members of Class
Chapter 11: Arrays
Declaring Arrays
Initializing Arrays
Assigning Values
Accessing Elements
Foreach Loop
Arrays in C#
Chapter 12: Strings
Creating Strings
String Class in C#
Length
Chars
Conclusion
Introduction
The most popular programming language for developing webpages for the Web is HTML or Hyper
Text Markup Language. Berners-Lee created it in the year 1991. However, the first published version
of the programming language was HTML 2.0, which was published four years later in the year 1995.
One of the most widely used and major versions of the programming language is HTML 4.01 and
presently we are using HTML-5. This version was published in 2012.
HTML is the programming language of use for web developers and designers. It is also a prerequisite
language for JavaScript and CSS. Therefore, anyone who is aspiring to work on website development
and designing must have basic knowledge of HTML. This book is designed for beginners with no
previous knowledge of the language. It shall help you attain a higher level of expertise in the
programming language.
With that said, there are a few things that you must know and have some basic knowledge about.
These include the Linux or Windows operating system. Besides this, you must be acquainted with a
text editor like notepad in Windows or VIM in Linux. Besides this, basic knowledge of computer
operations like creating files, directories and an understanding of image file formats like PNG and
JPEG, shall be a major plus point.
Lastly, we hope that you will be able to attain the set learning objectives for HTML with the help of
this book and it will help you create the awesome websites that you plan to make in the future. HTML
is the base language that uses several other programming constructs like CSS and JavaScript to get
more out of basic webpages. This book shall cover the basics of HTML and CSS. You can take this
learning forward by learning advanced HTML, JavaScript and PHP. We welcome you to the world of
the web and wish you a journey full of creativity and adventure.
The fullform of HTML is Hyper Text Markup Language. It would not be wrong to state that it is the
base language for website development all around the world. If you are working in the website
designing and development sector, knowledge of HTML is a must!
In order to understand the language better, let us understand the words that make the acronym HTML.
It is a well known fact that webpages are linked to each other. The link that is available on a webpage
and which takes you to another webpage is called hypertext. The phrase markup language refers to the
fact that HTML marks up webpages with the help of tags. These tags are interpreted by the browser to
understand how the webpage needs to be displayed.
The intent behind the development of this programming language was to create a generic structure for
documents by classifying its content into categories like header, paragraph, table, image, list and
footer, in addition to many others. It was primarily created for the research community to facilitate
sharing of documents and easy understanding of the same.
Learning HTML is all about learning the different tags available in this programming language and
how each of them behaves with a different set of attribute values.
As a convention set by the World Wide Web Consortium, lower case must be used for specifying tags.
This convention was set from HTML 4 onwards.
Document Structure
The typical structure of a document is as follows –
<html>
<head>Header related tags appear here</head>
<body>Body related tags appear here</body>
</html>
Now that we know how to declare the document type of a document, let us look at the other tags that
are commonly used in a HTML webpage. The basic tags for defining a document have been described
in this chapter for your reference.
Headings
In order to give a document’s body, the required structure, it must be divided into headings,
paragraphs, lists, tables and images. HTML supports six levels of headings, which can be defined
using the tags, <h1>, <h2>,<h3>,<h4>,<h5> and <h6>.
All these different heading levels have a different font size, which decreases as the level increases.
Moreover, every time a heading tag is encountered, by default, the browser adds a line before and
after the heading. Sample document that demonstrates the difference in heading levels is given below.
<!DOCTYPE html>
<html>
<head>
<title>Headings Demo</title>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
</body>
</html>
The webpage corresponding to this code is as follows –
Paragraph
In order to create paragraphs in HTML, the <p></p> tags are used. Anything that appears within these
tags is formatted according to paragraph guidelines of HTML. As is obvious, <p> is the opening tag
and </p> is the closing tag.
<!DOCTYPE html>
<html>
<head>
<title>Paragraph Demo</title>
</head>
<body>
<p>Paragraph 1</p>
<p> Paragraph 2</p>
<p> Paragraph 3</p>
</body>
</html>
The webpage corresponding to this code shall look like this –
Line Break
Whenever the <br /> tag is encountered, the text that succeeds this tag is displayed on the next line.
This tag is also referred to as an empty element because nothing has to appear between the opening
and closing tags, therefore; a single tag is used.
Please note that there should be a space between the characters br and /. If you miss out the space,
older browsers will not be able to comprehend the tag. Moreover, if you miss out the forward slash
(/), the tag will be considered invalid by XHTML.
<!DOCTYPE html>
<html>
<head>
<title>Line Break Demo</title>
</head>
<body>
<p>Hey<br />This is the next line.<br />Thanks<br />This is also on the next line</p>
</body>
</html>
The webpage corresponding to this code is shown below –
Centering Content
In order to bring the content to the center of the element, which holds true for table cells, the <center>
tag may be used. Sample code to demonstrate the behavious of this tag is given below –
<!DOCTYPE html>
<html>
<head>
<title>Centering Content Demo</title>
</head>
<body>
<p>Not the center! </p>
<center>
<p>Centered!</p>
</center>
</body>
</html>
The webpage corresponding to this code is given below –
Horizontal Lines
In order to different between sections of a document, you might like to draw lines that separate them.
Using the <hr /> tag, such horizontal lines can be created. This tag creates a horizontal line from the
place where it is used to the right margin of the webpage. Sample code to demonstrate the behavior of
this tag is given below –
<!DOCTYPE html>
<html>
<head>
<title>Horizontal Line Demo</title>
</head>
<body>
<p>Section 1</p>
<hr />
<p>Section 2</p>
</body>
</html>
The webpage corresponding to this code is shown below –
Like the line break tag (<br />), the hr tag is also an empty element. So, there are no opening and
closing tags. Moreover, no text goes between the tags. It is important to note here that there must be a
space between hr and / or else some of the browsers may not be able to recognize this tag for your
webpage. The tag <hr> without the forward slash is considered invalid by XHTML.
Preformatted Tag
In some cases, you don’t want the browser to display the webpage as it is written in the HTML
document. The preformatted tag can be used to preserve the formatting of the document. Therefore, the
text that appears between <pre> and </pre> retains the formatting that it receives from the source
document. Sample code to demonstrate the behavior of this tag is given below –
<!DOCTYPE html>
<html>
<head>
<title>Preformatted Tag Demo</title>
</head>
<body>
<pre>
function demoFunction( str_Text ){
alert (str_Text)
}
</pre>
</body>
</html>
The webpage corresponding to this code is shown below –
If you remove the <pre> and </pre> tags, the output will appear something like this –
Non-Breaking Spaces
In case you don’t want the client browser to break your text on the basis of character limit on lines,
you can use non-breaking spaces or  . Sample code to demonstrate the behavior of this tag is
given below –
<!DOCTYPE html>
<html>
<head>
<title>Nonbreaking Spaces Demo</title>
</head>
<body>
<p>Demo: "12 Angry Men."</p>
</body>
</html>
The webpage corresponding to this code is shown below –
Elements in HTML
The starting tag that can include other tags for defining a document is referred to as an element.
Moreover, if other elements are included, then the tag will have a corresponding closing tag as well.
For example, <p> has a closing tag </p> while <br /> doesn’t have a closing tag. Elements that don’t
have a closing tag are also called void elements.
An HTML document can be seen as a tree of HTML elements. This tree can be used to visualize how
the HTML page will be displayed and what kind of content can be placed in which part of the HTML
document. This may make you wonder as to then, what is the difference between HTML tags and
elements. An element begins with a tag and ends with a tag. Therefore, the entity that is created using
a set of tags is an element.
For instance, if <p> is the opening tag and </p> is the closing tag, then the element created as result
is the paragraph element. HTML allows nesting of elements. In other words, you can have one
element inside another elements and many elements enclosed inside a single element. In the sample
code given below, the element head has the element title while the element body has the elements, h1
and p. Moreover, the element h1 has the element i and the element p has the element u.
<!DOCTYPE html>
<html>
<head>
<title>Nested Elements Demo</title>
</head>
<body>
<h1>Text is <i>italic</i> heading</h1>
<p>Text is <u>underlined</u> paragraph</p>
</body>
</html>
The webpage corresponding to this code shall look something like this –
Chapter 3: Attributes
So far, you are already seen the use of tags. However, in most of the examples already given in this
book, tags are used in their simplest forms. All tags also have attributes associated with them.
Attributes contain some extra bit of information that can be used to customize the behavior of the tag
according to the needs of the programmer.
An attribute is a characteristic of the element concerned that can be customized by the developer
accorsing to application needs. It is typically present inside the opening tag of the HTML element.
Moreover, an attribute consists of two parts namely, name and value.
The name of the element is used to refer to the property or characteristic that you wish to set. For
example, the <p> element has an attribute align, which is used to change the alignment of text that is
present in this element. Therefore, align is the name of the element and any changes required on part
of this characteristic must be done upon reference to this name.
The value of the characteristic is the property value that you wish to set and want the system to use for
this element. As a rule, value is always enclosed within quotation marks. Considering the example of
the characteristic name ‘align’, it can hold the values left, right and center.
It is important to mention here that values are not sensitive to case and CENTER or center will be
understood by the system as the value “center”. With that said, the standard or convention followed
for specifying values recommends the use of lower case values. Sample code to demonstrate how this
works is given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Attribute Demo</title>
</head>
<body>
<p align = "center">Center aligned!</p>
<p align = "left">Left aligned!</p>
<p align = "right">Right aligned!</p>
</body>
</html>
The webpage corresponding to this code shall look like this –
Core Attributes
Some attributes are used by a majority of the HTML elements and are thus referred to as core
elements. These attributes include class, title, id, and style. The element ‘id’ is used for unique
identification of any HTML element inside a HTML page. This attribute is typically used in scenarios
where the webpage has multiple elements of the same name. Here is an example that shows how the
id attribute can be used to identify between two different paragraph elements.
<p id = "css">CSS</p>
<p id = "html"> HTML</p>
The suggested title for an element can be given using the title attribute. This attribute can be declared
in the same manner as the id attribute is done. The manner in which this attribute shall behave largely
depends on the concerned element. In most cases, the title is displayed when the cursor’s tooltip
hovers over the element or while it is loading. Sample code to demonstrate how this attribute works
is given below.
<!DOCTYPE html>
<html>
<head>
<title>Attribute Demo</title>
</head>
<body>
<h3 title = "This is HTML!">Example</h3>
</body>
</html>
The webpage corresponding to this code is shown in the image attached below.
When the cursor is hovered over ‘Example’, the given title is displayed alongside the cursor.
One of the major requirements when creating a webpage is to associate webpages to style sheets. The
class attribute is used for performing this operation. A detailed discussion on style sheets in given in
one of the later chapters. HTML allows association of a webpage to multiple style sheets. Each of
these style sheets can be specified using a comma-separated list. Example of how this attribute can be
used is given below for your reference.
class = "className1 className2 className3"
In order to specify CSS rules for the contents of an element, the style attribute may be used.
<!DOCTYPE html>
<html>
<head>
<title>Demo Style Attribute</title>
</head>
<body>
<p style = "font-family:arial; color:#FF0000;">Sample</p>
</body>
</html>
The webpage for the given code shall look like this. Do not bother much about the details of CSS and
the rules associated with the same. We shall look deeper into them once we discuss Cascading Style
Sheets in details.
Internationalization Attributes
Most XHTML elements supports three internationalization attributes, which include dir, lang and
xml:lang. the direction of text flow can be specified using the dir attribute. This attribute can hold
only two values, which are ltr and rtr. The former indicates that the text will flow from the left to right
direction. On the other hand, the latter indicates that the text flows from right to left as in the case of
languages like Arabic and Hebrew.
Sample code to demonstrate the working of this attribute is given below for your reference.
<!DOCTYPE html>
<html dir = "rtl">
<head>
<title>Display Directions</title>
</head>
<body>Left to Right</body>
</html>
The webpage corresponding to this code is shown below.
The position of the attribute determines its scope of control. For instance, if the tag is used within the
html tag, then the text flow direction is accordingly set for the whole document. On the other hand, if
the tag is used within a specific element of the document, then the direction is set for that element.
Webpages can be created in different languages. Therefore, in order to tell the browser as to, which
language the current webpage is using, the ‘lang’ attribute is used. It is important to mention here that
this attribute was kept and not removed just to maintain backward compatibility as it has already been
replaced with xml:lang in XHTML documents. Sample code to demonstrate the working of this
attribute has been provided below.
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Attribute lang Demo</title>
</head>
<body>English</body>
</html>
The webpage corresponding to this page will look like this –
As mentioned previously, the ‘lang’ attribute has been replaced with xml:lang, which is presently the
standard attribute for mentioning webpage language.
Generic Attributes
Apart from the attributes explained above, there are some other attributes as well that can be used wit
many if the HTML tags. These attributes are as follows –
Align
This attribute can take three values namely left, right and center, and is typically used to align the
contents of an HTML element.
Valign
This attribute is used for vertical alignment of tags in an HTML element. It can take the values –
bottom, middle and top.
Bgcolor
The background color for an element can be changed using the bgcolor tag. It can take numeric,
hexadecimal and RGB values of colors.
Background
HTML also allows you to place an image behind the element using the background tag. This tag takes
the URL corresponding to the image as value.
ID
This attribute is used to define an ID that can further be used with CSS.
Class
This attribute is used to classify an element that can further be used with CSS.
Width
The width of images, tables and cells of table can be specified using the width attribute. It accepts
numeric values.
Height
The height of images, tables and cells of table can be specified using the width attribute. It accepts
numeric values.
Title
This attribute allows the developer to set the pop-title of elements.
Chapter 4: Formatting
The most common formatting options that most of us are familiar with are bold, underlined and
italics. These are some of the ways in which the appearance of text can be altered for different user
experiences and perceptions. HTML and XHTML support several forms of text formatting, which
shall be discussed in detail in this chapter.
Bold Text
In order to bold text, the <b>…</b> tags are used. Any content that lies between the opening and
closing tag is formatted accordingly. Sample code to illustrate how these tags work is given below
for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Bold Text Demo</title>
</head>
<body>
<p>Example: <b>Bold</b> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Italic Text
In order to italicize text, the <i>…</i> tags are used. Any content that lies between the opening and
closing tag is formatted accordingly. Sample code to illustrate how these tags work is given below
for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Italic Text Demo</title>
</head>
<body>
<p>Example: <i>Italic</i> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Underlined Text
In order to underline text, the <u>…</u> tags are used. Any content that lies between the opening and
closing tag is formatted accordingly. Sample code to illustrate how these tags work is given below
for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Underline Text Demo</title>
</head>
<body>
<p>Example: <u>Underline</u> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Strike Text
In order to strike text, the <strike>…</strike> tags are used. Any content that lies between the
opening and closing tag is formatted accordingly. Sample code to illustrate how these tags work is
given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Strike Text Demo</title>
</head>
<body>
<p>Example: <strike>Strike</strike> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Monospaced Text
In order to bold text, the <tt>…</tt> tags are used. Any content that lies between the opening and
closing tag is formatted accordingly. Sample code to illustrate how these tags work is given below
for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Monospaced Text Demo</title>
</head>
<body>
<p>Example: <tt>Monospaced</tt> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Superscript Text
In order to format text as superscript, the <sup>…</sup> tags are used. Any content that lies between
the opening and closing tag is formatted accordingly. Sample code to illustrate how these tags work is
given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Superscript Text Demo</title>
</head>
<body>
<p>Example: <sup>Superscript</sup> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Subscript Text
In order to format text for it to appear as subscript, the <sub>…</sub> tags are used. Any content that
lies between the opening and closing tag is formatted accordingly. Sample code to illustrate how
these tags work is given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Subscript Text Demo</title>
</head>
<body>
<p>Example: <sub>Subscript</sub> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Inserted Text
In order to format text so as it appears as inserted text, the <ins>…</ins> tags are used. Any content
that lies between the opening and closing tag is formatted accordingly. Sample code to illustrate how
these tags work is given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Inserted Text Demo</title>
</head>
<body>
<p>I want to learn <del>Java</del> <ins>HTML</ins></p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Deleted Text
In order to format text so as it appears as deleted text, the <del>…</del> tags are used. Any content
that lies between the opening and closing tag is formatted accordingly. Its usage has been been
demonstrated in the previous example.
Larger Text
In order to format text so as it appears as larger text, the <big>…</big> tags are used. Any content
that lies between the opening and closing tag is formatted Any content that lies between the opening
and closing tag is formatted in such a manner that its font size is larger than that of other text in the
same HTML document. Sample code to illustrate how these tags work is given below for your
reference.
<!DOCTYPE html>
<html>
<head>
<title>Larger Text Demo</title>
</head>
<body>
<p>Example: <big>Big</big> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Small Text
In order to format text so as it appears as smaller text, the <big>…</big> tags are used. Any content
that lies between the opening and closing tag is formatted Any content that lies between the opening
and closing tag is formatted in such a manner that its font size is smaller than that of other text in the
same HTML document. Sample code to illustrate how these tags work is given below for your
reference.
<!DOCTYPE html>
<html>
<head>
<title>Smaller Text Demo</title>
</head>
<body>
<p>Example: <small>Small</small> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Grouping Content
An HTML document can be organized into sections and sub-sections using the <div>…</div> and
<span>…</span> tags. For instance, all the tags that belong to the footnotes section can be put
together inside a <div>…</div> to indicate that they are all part of the footnotes section. Moreover,
then you may apply specific formatting rules to that division or section. This allows you to have more
control over the formatting of different sections of the HTML document. The sample code given
below demonstrates the behavior of the <div> tags.
<!DOCTYPE html>
<html>
<head>
<title>Div Demo</title>
</head>
<body>
<div id = "main" align = "middle" >
<a href = "/index.htm">HOME</a> |
</div>
<div id = "other" align = "left" bgcolor = "white">
<h5>Text</h5>
<p>Extra content…</p>
</div>
</body>
</html>
The webpage corresponding to this code is shown below –
While <div> is used to group elements together, <span> is used to group inline elements together. for
instance, a part of a paragraph can be grouped to behave differently. Sample code given below
illustrates how span differs from div.
<!DOCTYPE html>
<html>
<head>
<title>Span Demo</title>
</head>
<body>
<p>Example: <span style = "color:green">span 1</span> and <span style = "color:red">span
2</span> text.</p>
</body>
</html>
The webpage corresponding to the code is shown below.
Chapter 5: Phrase Tags
Phrase tags are similar to formatting tags. However, they are more specific in their functionality and
scope of usage. In this chapter, we shall discuss phrase tags and see examples of how they can be
used to achieve different effects.
Emphasized Text
In order to emphasize text, the <em>…</em> tags are used. Any content that lies between the opening
and closing tag is formatted accordingly. Sample code to illustrate how these tags work is given
below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Emphasized Text Demo</title>
</head>
<body>
<p>Example: <em>emphasized</em> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Marked Text
In order to mark text in yellow color, the <mark>…</mark> tags are used. Any content that lies
between the opening and closing tag is formatted accordingly. Sample code to illustrate how these
tags work is given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Marked Text Demo</title>
</head>
<body>
<p>Example: <mark>marked</mark> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Strong Text
In order to indicate that some text is strong or important, the <strong>…</strong> tags are used. Any
content that lies between the opening and closing tag is formatted accordingly. Sample code to
illustrate how these tags work is given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Strong Text Demo</title>
</head>
<body>
<p>Example: <strong>strong</strong> text.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Text Abbreviation
In order to abbreviate text, the <abbr>…</abbr> tags are used. Any content that lies between the
opening and closing tag is formatted accordingly. However, the full version of the abbreviation must
be specified using the title attribute. Sample code to illustrate how these tags work is given below for
your reference.
<!DOCTYPE html>
<html>
<head>
<title>Text Abbreviation Demo</title>
</head>
<body>
<p>My Subject’s name is <abbr title = "Computer Science">CS</abbr>.
</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Acronym Element
In order to indicate that the text concerned is an acronym, the <acronym> element is used. Any content
that lies between the opening and closing tag is formatted accordingly. It is important to mention here
that most browsers do not change the appearance of text indicated as acronym. Sample code to
illustrate how these tags work is given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Acronym Demo</title>
</head>
<body>
<p>Example: <acronym>XHTML</acronym>.</p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Text Direction
In order to override the default direction of text, the <bdo>…</bdo> tags are used. Sample code to
illustrate the behavior of these tags is given below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Text Direction Demo</title>
</head>
<body>
<p>Left to right.</p>
<p><bdo dir = "rtl">Right to left.</bdo></p>
</body>
</html>
The webpage corresponding to this code shall look like the image shown below.
Chapter 6: Meta Tags
In order to specify the metadata of an HTML document, the metadata tags needs to be specified.
Metadata includes a variety of information about the document. Some of the properties that are
commonly specified using these tags include author, document author and expiry date.
The tag used for specifying such additional information about the document is <meta>. It is important
to mention here that this tag does not have a closing tag and is also called an empty element. The
attributes of the tag are used for specifying the required information.
Multiple metatags may be included in an HTML document to specify additional information. A key
point to note here is that the presence or absence of metatags has no difference on the appearance of
the page.
Specifying Keywords
Search engines make use of keywords to index documents and they accordingly appear in search
results. The keywords for a document can be specified using the <meta> tag. Sample code to illustrate
how this can be done is given below.
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Demo</title>
<meta name = "keywords" content = "sample, HTML, Metadata" />
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Document Description
Another way in which search engines index documents and make them appear in search results is by
scanning their document description. In order to set the document description, this tag can be used.
Sample code to illustrate how this can be done is given below.
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Demo</title>
<meta name = "keywords" content = "HTML, sample, Metadata" />
<meta name = "description" content = "This is demo for meta tags." />
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Refreshing Document
The <meta> tags may also be usred to specify the browser as to in how much time, the browser must
refresh the page. This can be done in the following manner. the sample code given below instructs the
browser to refresh the webpage in every 5 seconds.
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Demo</title>
<meta name = "keywords" content = "HTML, sample, Metadata" />
<meta name = "description" content = "Sample Page." />
<meta name = "revised" content = "Sample, 5/10/2017" />
<meta http-equiv = "refresh" content = "5" />
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Page Redirection
There may be programming scenario, which may require you to redirect an existing page to another
page. The <meta> tags allows you to perform this function. Moreover, it also allows you to specify
the time in seconds after which the redirection must occur. The sample code given below
demonstrates how this function can be performed. It instructs the browser to perform redirection after
5 seconds.
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Demo</title>
<meta name = "keywords" content = "HTML, sample, Metadata" />
<meta name = "description" content = "Sample Page." />
<meta name = "revised" content = "Sample, 5/10/2017" />
<meta http-equiv = "refresh" content = "5; url = http://www.google.com" />
</head>
<body>
<p>Hello World!</p>
</body>
</html>
The concept of comments is same in HTML as in any other programming language. The compiler
ignores the piece of code that is marked as a comment. It is meant only for code management and
maintainability. The developer writes comments while writing code so that in case any other
developer needs to edit this code, he or she must be able to understand the code easily, thus
contributing to code readability and usability.
As a rule, an HTML comment is placed inside <!-- … -->. Any piece of text that lies between the
starting sign and closing sign is considered a comment. Sample code to illustrate how a typical
comment looks like in HTML is given below.
<!DOCTYPE html>
<html>
<head>
<!-- Header -->
<title>Document title</title>
</head>
<!-- Header Ends -->
<body>
<p>Document body</p>
</body>
</html>
Multi-line Comments
HTML provides support for multi-line comments as well. In fact, multi-line comments can also be
declared using the same syntax as single line comments. The starting of the comment must be
preceded by <!-- and the same must end with -->. Sample code to show you how this work is
provided below –
<!DOCTYPE html>
<html>
<head>
<title>Multiline Comments Demo</title>
</head>
<body>
<!-- This is a multiline comment. This is a multiline comment. This is a multiline
comment. This is a multiline comment. -->
<p>Document body</p>
</body>
</html>
Conditional Comments
Although HTML provides support for conditional comments, only Internet Explorer (IE) recognizes
them. Moreover, they are supported only on versions of IE that have come after IE5. These elements
are particularly useful in situations such as the ones that require you to put a different style sheet for
different browser. Sample implementation to demonstrate how conditional comments can be provided
in HTML is given below.
<!DOCTYPE html>
<html>
<head>
<title>Conditional Comment Demo</title>
<!--[if IE 6]> IE6: <![endif]--> </head>
<body>
<p>Document body…</p>
</body>
</html>
Graphics and images are an essential part of any webpage. In fact, it is the best way to depict
complex concepts. This chapter discusses how images can be effectively used as part of webpages to
enhance the look and functionality of the same.
Inserting Images
An image can be inserted into an HTML document using <img> tag. The syntax of using this tag is
given below –
<img src = "URL of image" list of attributes />
As it is evident from the syntax, the img tag is an empty tag. In other words, it does not have a closing
tag. Sample code to illustrate how this tag works is provided below.
<!DOCTYPE html>
<html>
<head>
<title>HTML Image Demo</title>
</head>
<body>
<p>Document body…</p>
<img src = "/html/images/sample.png" alt = "Sample" />
</body>
</html>
HTML supports GIF, PNG and JPEG/JPG formats. If you face trouble getting this tag right on your
web browser, do not forget to check the path of the source file and its name. HTML is case sensitive
in this regard and naming the file incorrectly is one of the commonest mistakes that people make
while inserting or using an image file. The alt attribute given as part of the <img> tag is used to
specify the text that must be displayed in case the image fails to load.
Tables are one of the fundamental elements using for arranging and organizing data. HTML allows
developer to arrage text, links, images and other tables into the row-column format. The tag used for
this purpose is the <table> tag.
Furthermore, rows can be created using <tr> tag while columns can be created using <td> tag. It is
important to mention here that <td> elements are created under <tr> and are left aligned, by default.
The sample code provided below shows a standard HTML table.
<!DOCTYPE html>
<html>
<head>
<title>Tables Demo</title>
</head>
<body>
<table border = "1">
<tr>
<td>Row1, Column1</td>
<td>Row1, Column2</td>
</tr>
<tr>
<td>Row2, Column1</td>
<td>Row2, Column2</td>
</tr>
</table>
</body>
</html>
The webpage corresponding to this code shall look like this –
As you can see in the code given above, the border attribute is set to 1 and hence, a border is seen in
the table thence created. If the border value is set to 0, the table will have no border.
Heading
The <th> tag can be used to give the table header. The tag shall appear in place of the <td> cell tags.
Although, HTML allows you to place the table header in any row of the table, the placement of the
same in the first row makes most sense. The standard format of a heading defined using the <th> tag is
center aligned and bold. Sample code to illustrate how a table header can be defined is provided
below.
<!DOCTYPE html>
<html>
<head>
<title>Table Header Demo</title>
</head>
<body>
<table border = "1">
<tr>
<th>Employee Name</th>
<th>Employee Salary</th>
</tr>
<tr>
<td>Jacob</td>
<td>20000</td>
</tr>
<tr>
<td>Jack</td>
<td>9000</td>
</tr>
</table>
</body>
</html>
The webpage corresponding to this code is shown below for your reference.
As mentioned previously, background attribute may also be used to set the background of the table or
a cell to an image. The sample code provided below gives a demonstration of how you can do this.
<!DOCTYPE html>
<html>
<head>
<title>Setting Table Background Demo</title>
</head>
<body>
<table border = "1" bordercolor = "green" background = "/images/sample.png">
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
<tr>
<td rowspan = "2">Row1 Cell1</td>
<td>Row1 Cell2</td>
<td>Row1 Cell3</td>
</tr>
<tr>
<td>Row2 Cell2</td>
<td>Row2 Cell3</td>
</tr>
<tr>
<td colspan = "3">Row3 Cell1</td>
</tr>
</table>
</body>
</html>
Caption
The table caption appears on top of the table and is a description of the table. Although, this tag has
been deprecated in newer versions of XHTML and HTML, we have included it here for the same of
comprehensiveness. Sample code for setting the table caption is provided below.
<!DOCTYPE html>
<html>
<head>
<title>Demo Table Caption</title>
</head>
<body>
<table border = "1" width = "100%">
<caption>TABLE CAPTION</caption>
<tr>
<td>row1, column1</td>
<td>row1, column2</td>
</tr>
<tr>
<td>row2, column1</td>
<td>row2, column2</td>
</tr>
</table>
</body>
</html>
The webpage corresponding to this code is shown below for your reference.
In continuation to the elements provided by HTML to arrage elements, we now move on to lists,
which are elements that are used for giving list of information. Lists may be ordered, unordered or
definition lists. Unordered lists are defined using <ul> tag and is displayed in the form of bullets.
On the other hand, ordered lists are defined using <ol> tag and appears in the form of numbered list.
Lastly, definition lists arrange items as they would have been arranged in a dictionary. This chapter
discusses lists in more detail.
Unordered Lists
When a list of items do not have specific order to follow, the list is referred to as an unordered list.
These lists are created using <ul> tag and when displayed, each item in the list is preceded by a
bullet. Sample implementation of an unordered list is provided below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Unordered List</title>
</head>
<body>
<ul>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ul>
</body>
</html>
The webpage corresponding to this code is shown below –
You can alter the appearance of the list by changing the type of bullets that are displayed. This can be
done with the help of type attribute. The type attribute can take three values namely circle, disc and
square. The default value is disc. Let us see how the appearance of the list varies with change in type.
The sample code given below uses the value of type as circle.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Unordered List</title>
</head>
<body>
<ul type=”circle”>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ul>
</body>
</html>
The webpage corresponding to this code is shown below –
Now if we change the value of type to square, the code will change in the following manner.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Unordered List</title>
</head>
<body>
<ul type=”square”>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ul>
</body>
</html>
The webpage corresponding to this code is shown below –
Although, the default value of type is disc, you can explicitly mention it and the code will look like
this.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Unordered List</title>
</head>
<body>
<ul type=”disc”>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ul>
</body>
</html>
The output of the code will be same as the first image of this chapter. You can execute this code to
show how it behaves.
Ordered Lists
In order to create numbered lists or ordered lists, HTML provides the <ol> tag. The numbering of the
elements begin with 1 and for each element, the number is increased by 1. The elements of the list are
specified using the tag <li>. Sample code to demonstrate how an ordered list can be created is
provided below –
<!DOCTYPE html>
<html>
<head>
<title>Demo: Ordered List</title>
</head>
<body>
<ol>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ol>
</body>
</html>
The webpage corresponding to this code is shown below –
By default, the ordered list is created as a sequence of numbers, each preceding an element of the list.
However, the type of numerals may be changed using the type attribute. Other options available
include “I” (upper-case numerals), “i” (lower-case numerals), “A” (upper-case letters) and “a”
(lower-case letters). The default value, corresponding the numbers is “1”.
Let us see how the appearance of the list changes with change in the value of type. The sample code
given below uses the value “I”.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Ordered List</title>
</head>
<body>
<ol type=I>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ol>
</body>
</html>
The webpage corresponding to this code is shown below –
HTML allows developers to create two types of links namely, text links and image links. The first
type of link or text links are text, which when clicked upon redirects control to another webpage. On
the other hand, in image links, the text is replaced with an image and when the user clicks on the
image, control is accordingly redirected. We shall discuss both these types of links in this chapter.
Text Links
Hyperlinks or links that connect various webpages together to form the web of Internet is the heart of
HTML. With that said, it is not necessary that a link may take control to another page. Instead, it may
also redirect control to another part of the same page. Therefore, hyperlinks, basically, allow users to
navigate through websites.
In order to create a link, HTML provides the <a>…</a> tag, which is also called the anchor tag. The
text that is supposed to appear on the screen for the link is placed between the opening and closing
tags. However, the link to which control has to be redirected if the user clicks on the text is given as
part of the href attribute. Standard format for using the anchor tag is given below.
<a href = "Source URL" ... lis-of-attributes>Text</a>
Sample code to demonstrate how the anchor tag can be used as part of the
HTML document is provided below.
<!DOCTYPE html>
<html>
<head>
<title>Hyperlink Demo</title>
</head>
<body>
<p>Sample:: </p>
<a href = "https://www.google.com">Click Here to Visit Google</a>
</body>
</html>
The webpage corresponding to this code is shown below –
The opening of the linked document can be controlled using the target attribute. For example, if the
value of target is set to _blank, then the linked document opens in a new tab or window. Other options
include –
self
This value allows opening of the HTML document in the same frame.
top
This value allows opening of the HTML document in the full body of the window.
parent
This value allows opening of the HTML document in the parent frame.
targetframe
This value allows opening of the HTML document in the specified targetframe.
The target attribute can be specified in the <a> tag in a manner shown below.
<!DOCTYPE html>
<html>
<head>
<title>Hyperlink Demo</title>
</head>
<body>
<p>Sample:: </p>
<a href = "https://www.google.com" target=”_self”>Click Here to Visit Google</a>
</body>
</html>
As you have already seen in the last few examples, we have provided the complete path of the linked
webpage. However, if you are linking the text to a webpage of the same website, then you don’t have
to provide the complete URL. In order to provide just the base path of all the links, the <base> tag
must be used in the header of the HTML document.
The use of this tag instructs the browser to concatenate the provided base path with the relative path
to get the complete URL of the linked document. The sample code provided below demonstrates the
use of <base> tag.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Base Tag</title>
<base href = "https://www.abc.com/">
</head>
<body>
<p>Example::</p>
<a href = "/html/index.htm" target = "_blank">Click on the link</a>
</body>
</html>
HTML also allows programmers to link text to different sections of the same webpage. The best way
to perform this is with the help of title and id attributes. However, HTML also provides name
attribute for this purpose. This attribute has been included in this book for the sake of
comprehensiveness as it has been deprecated in HTML5. Therefore, its use is not recommended.
Linking different sections of a webpage using name attribute is a two-step process. firstly, you need to
create a link to the part of webpage that you wish to link and give it a name using the <a> tag. This
can be done in the following manner –
<h1>Text Link<a name = "top"></a></h1>
The second step is to create a hyperlink, which takes you to the part of the webpage you had
previously named.
<a href = "/html/html_text_links.htm#top">Top of Page</a>
An important aesthetic aspects of links is that they must appear different from other text so that the
user knows that it is a link and clicking on the same will take him or her to another webpage or
another part of the same webpage. This is perhaps the reason why most people prefer to change the
colour of links, visited links and active links with the help of vlink, alink and link attributes of the
<body> tag. Sample code to illustrate how you can play around with the color of the links is provided
below.
<!DOCTYPE html>
<html>
<head>
<title>Hyperlink Demo</title>
<base href = "https://www.google.com/">
</head>
<body alink = "#54A250" link = "#040404" vlink = "#F40633">
<p>Example</p>
<a href = "/html/index.htm" target = "_blank" >Sample Text</a>
</body>
</html>
Create a webpage with this code and see for yourself how the linksbehave now.
Image Links
We have already seen how navigation between different webpages can be established using text links.
However, there may be programming scenarios where you may require image links or images, which
upon clicking on them, redirects the user to another webpage. A common usage of this concept lies in
advertising where a click on the ad banner of a company takes you to its website. A combination of
<a> and <img> tags is required to create an image link. The sample code provided below shows how
an image link can be created.
<!DOCTYPE html>
<html>
<head>
<title>Image Link Demo</title>
</head>
<body>
<p>Example::</p>
<a href = "https://www.google.com" target = "_self">
<img src = "/images/googlelogo.png" alt = "Google" border = "0"/>
</a>
</body>
</html>
Be sure to upload the logo image at the specified location or give the exact source URL of the image
that is to be used as a link before testing this webpage .
Chapter 12: Cascading Style Sheets
Cascading Style Sheets, which are also popularly referred to as CSS defines the style or appearance
of the HTML document, in print, and on screen. Since the time the World Wide Web Consortium was
founded in the year 1994, the use of CSS has been immensely and actively promoted.
All the styling attributes that are specified as part of HTML tags can easily and effectively specified
as part of CSS. Moreover, many style properties can be specified easily. All you need to do is specify
the name of the property and its value. These two must be separated with a colon (:). Besides this,
different properties must be separated with a semi-colon (;).
In order to help you understand the concept of CSS in HTML, let us take an HTML document that uses
the tag <font>. It is important to mention here that this tag has been deprecated in HTML5. However,
we have used it here to help you understand how style attributes can be easily replaced and more
effectively implemented using CSS. Therefore, we are not recommending the use of font tag. We have
just used it for learning purposes.
<!DOCTYPE html>
<html>
<head>
<title>Demo: CSS</title>
</head>
<body>
<p>
<font color = "green" size = "5">Hey, how are you?</font>
</p>
</body>
</html>
The code of this webpage can alternatively be written in the following manner –
<!DOCTYPE html>
<html>
<head>
<title>Demo: CSS</title>
</head>
<body>
<p style = "color:green; font-size:24px;" >Hey, how are you?</p>
</body>
</html>
CSS can be used in one of the three possible ways explained below –
Internal Style Sheet
In this method, the style sheet for the document is specified in the header section of the HTML
document using the <style> tag.
External Style Sheets
In this method, a separate style sheet with the extension .css must be created and then, this file is
included in the HTML document using the <link> tag.
Inline Style Sheet
This method describes the style attributes directly in the tag with the help of style attribute. The
sample code, given above, uses inline style sheet.
Each of these methods for embedding CSS in HTML are discussed in detail below.
Conclusion
Now that we have come to the end of this book, we hope you have attained basic knowledge of
HTML and CSS so much so that you can create basic webpages and style them using CSS sheets. To
get a better hang of this programming language, you must run the sample codes and edit them to check
if you are able to understand the basic concepts of HTML. You can also design webpages that use
multiple elements like tables, lists, images and links, as a project, to summarize your learning from
this book.
In order to become an expert website developer or designer, the knowledge of HTML and CSS must
be complemented with other state-of-the-art technologies that are available in the market today. Some
of the programming languages that are embedded in HTML to improve the functionality of basic
HTML webpages are JavaScript and PHP.
Modern day website development have come a long way from the simple HTML and CSS webpages.
With that said, HTML and CSS still remain the foundations on which all these technologies stand. You
can take the lessons learnt in this book further by going through advanced HTML & CSS lessons, after
which you can graduate to complex programming paradigms like PHP and JavaScript. We hope you
enjoyed this book and welcome any feedback that you may have to make this book better.
Java
Introduction
Java is a cross-platform, high-level language that was developed by Sun Microsystems under the
leadership of James Gosling. The first version of this language was released in 1995 in the form of
Java 1.0 [J2SE]. Since then, Java has come a long way and we are presently working on Java 8.
Besides this, several versions of Java like J2ME (Java for mobile applications) and J2EE (Java for
enterprise applications) have also released. Java was released as open source software under GNU
GPL by Sun in 2006. The process of this transformation was completed in 2007.
This book is a beginner’s course on Java fundamentals. Therefore, it has been created keeping in
mind that the reader has little to know background knowledge about Java. However, a little
background of programming languages shall be helpful for better understanding. Through this course,
we hope to instill the basics of programming in the reader from the perspective and with special
focus on Java.
Before you begin, it is good for you to understand that programming concepts are generic and apply
well to a range of programming languages. Therefore, if you work towards building programming
concepts instead of learning syntax, you will be able to learn many programming languages with
minimal effort. Focus on the concept instead of the syntax!
Before we move on to Java programming, let us give you a brief background of Java, the
programming language, and the prerequisites of learning this programming language. One of the most
important features of this programming language is that it is cross-platform. This is evident from the
fact that Java was first advertised with the tagline ‘Write Once, Run Anywhere’. So, all you need to
do is write a code, compile it and then you can run it on any system, be it Windows, Unix, Linux or
Macintosh.
Besides the above-mentioned, other features of Java include –
Platform independent
Object oriented
Simple
Secure
Portable
Architecture-independent
Interpreted
Robust
Distributed
Multithreaded
Dynamic
High Performance
Java implements object-oriented programming principles. Therefore, a Java program is a class file
that upon execution creates a set of objects. These objects communicate with each other by means of
methods. Some of the terms that you will commonly encounter in the Java terminology have been
explained below –
The foundation element of a Java program is Class . It is simply a template that defines the
state and behavior of an object.
The state of the object is defined by Variables and the behavior is described by Methods .
Therefore, a class includes variables and methods. It is important to mention here that each
object created using a class has its own set of variables and thus, variables are also called
Instance Variables .
When we instantiate a class, we create an Object , which is the second fundamental element
of Java programming.
In order to help you understand this concept, let us take an example. Suppose we create a class called
car. Car is a general term for all four-wheeled small vehicles. However, every car has a different set
of specifications like brand, color, engine, transmission type and features. These features can be
modified. For example, you may get the color changed or a feature enhanced.
Therefore, car is a template (or in our case a class) but specific cars are objects or instances of this
class. The set of specifications are variables and any initilizations or manipulations that we perform
on these variables are done using methods.
This example can also be best used to understand the object oriented principles of encapsulation and
abstraction. The class encapsulates variables and methods into it. So, as the user, you are dealing
with only the class car and its implementation is hidden from you. This is how Java implements
abstraction.
The best way to learn programming is by writing programs. So, we have given you a sample program
below for you to try. We will also use this program to explain the basic syntax of java programming
language.
public class SampleJavaProgram {
/* This program will print Hello World! on the screen */
public static void main(String []args) {
System.out.println("Hello World!"); // statement for print
}
}
In order to write, compile and run this program, you need to follow the instructions given below –
Using any text editor, create a text file and copy this code into the same.
Save the file as SampleJavaProgram.java
Compile and run the code using the IDE. For manual execution, you need to type the
following commands:
javac SampleJavaProgram.java
java SampleJavaProgram
The first command will create a class file from the java file while the second command will execute
the program to give the desired result. A sample run of the code has been illustrated in the image
shown below.
If you have reached so far, you have successfully executed your first java program. Now it is time to
inspect the program to see how we wrote it and why it gave the result that it did.
Firstly, writing a program in Java requires you to follow some conventions. These are listed below –
Java is a case-sensitive language. In other words, class and Class are two different words
for Java. Be careful when you are using keywords or any other elements in the program.
As a convention, the first letter of every word of the class name is supposed to be capital.
For example, if the name of the class is Car, the ‘C’ is supposed to be capital. On the other
hand, if the name of the class is SportsCar, then S and C must be capital as both of them are
first letters of the two words that form the name of the class.
Method names also follow a capitalization convention according to which the first letter of
the method name must be small in case. However, if the name if made from more than one
word, then except for the first word, every other word’s first letter must be capital. For
example, if the method’s name is add, then ‘a’ must be small, but if the method’s name is
addNumbers, then ‘a’ will be small and ‘N’ will be capital.
The name of the java file must be same as the name of the class, followed by .java extension.
For example, if the name of your class is SampleApplication, then the name of the java file
must be SampleApplication.java. Also remember that the case of the letter must also match.
If you do not fulfill any of these requirements, you will not be able to compile the program.
The execution of a java program begins with the main method. Therefore, every Java
program must have a main method and the main method in java programming is defined as
public static void main(String args[])
But again, if your program doesn’t have a main method, the program will not run.
Identifiers
Any programming language is made up of English language words. Some of these words are a part of
the syntax of the programming language while others like variable names and the user defines names
of classes and methods. The words that are a part of the syntax are called keywords. On the other
hand, all user-defined names are called identifiers.
There are some important things to know and remember about Java. These include –
Names given to identifiers can begin with alphabets (lower case or upper case) and special
characters – underscore (_) and currency ($). This also means that an identifier’s name
cannot begin with a number of any other special character.
The use of a defined keyword as an identifier is not allowed.
Lastly, always remember that Java is case-sensitive and icount and Icount are two different
identifiers.
Modifiers
Classes, methods and variables can be modified only using modifiers. There are two types of
modifiers, which are as follows –
Non-access Modifiers – strictfp, abstract, final
Access Modifiers − public, default, private, protected
Access modifiers determine how the class, method or variable can be accessed and who all have the
permission to access them. Other modifiers, which do not work on similar lines are classified as non-
access modifiers.
Variables
Java supports three types of variables namely class variable, local variables and instance variables.
Class variables are also called static variables while instance variables have been termed as non-
static variables.
Arrays
A collection of elements of the same type is called an array. Java supports array objects of different
types.
Enums
There are some variables that can hold only a few values. As a programmer, you may wish to restrict
such variables from taking any other value. One such variable is gender, which can have only a
selective number of values. Enums allows you to implement such variables. The use of enums is an
error-reduction strategy and it was introduced in Java 5.0. It is possible to define enum inside a class
or outside it. Moreover, enums can have constructors, variables and methods.
Keywords
The words that are part of the Java programming language and cannot be used as identifiers are called
keywords. These keywords are –
While volatile
Comments
In java, there is support for single-line and multi-line comments. Single line comments start with //
while multi-line comments start with /* and end with */. You can look for these comments in the
sample code given above.
Blank Lines
Any line that has a comment or no characters or whitespace characters is not considered by Java. It is
simply ignored.
Implementing Inheritance
The inheritance characteristic of object-oriented programming is implemented in Java using the
concept of deriving a new class from an existing class. This allows you to reuse existing code. The
existing class is called a superclass while the derived class is referred to as a derived class.
Interfaces
In case two objects need to communicate with each other, then a protocol of communication needs to
be established between these objects. This protocol of communication is called an interface. This
concept is usually used in the implementation of the inheritance concept. An interface is used to
define the methods that a subclass must have. However, it is the subclass that implements those
methods.
Chapter 3: Data Types
When we declare variables, we basically block space in the memory and give it a reference name so
that we can access it later and manipulate its contents. The amount of memory reserved for a variable
depends on the data type given at the time of declaration. Therefore, by giving different data types to
variables, you can reserve different amounts of memory for the variable in the memory. There are two
main types in Java, which are primitive datatypes and object datatypes.
Java Literals
Literal is used to represent a fixed value. They are declared like variables and have a data type.
Sample declaration of a literal is –
char x = ‘X’;
You may notice integers and float with different bases. As a rule, any literal value that has 0, as prefix
is octal numbers while if 0x prefix indicates hexadecimal numbers. If you are working with strings,
then string literals are always defined as sequence of characters enclosed within double inverted
commas. Another set of characters that you will work with is escape characters. A list of escape
characters has been given below –
Carriage Return (\r)
Newline (\n)
Backspace (\b)
Formfeed (\f)
Tab (\t)
Space (\s)
Single quote (\’)
Double quote (\”)
Hexadecimal character (\uxxxx)
Octal character (\ddd)
Backslash (\\)
Chapter 4: Variables
The simplest definition of a variable is that it is a name given to some memory area. However, there
are many types of variables, which Java supports. On the basis of the type of variable, the following
parameters are determined –
Size of memory blocked for the variable.
Layout of the blocked memory.
Operations that can be performed on the variable.
Range of values that the variable can hold.
As a rule, every variable needs to be declared before use. The standard statement for variable
declaration is –
data_type variable_name;
Here, data_type is the data type of the variable while variable_name is the identifier used for the
variable. If you are using multiple variables of the same type, you can club them in the same statement
by specifying the name of the variables in a comma-separated manner. As mentioned previously, Java
supports three types of variables namely, class variable, instance variable and local variables. This
chapter explains these variable types in detail.
Local Variables
Variables that are declared inside a method or block of code are local to the scope and are called
local variables. The variable is created as and when it is declared and defined in the block.
Moreover, the variable is destroyed once the scope of the block gets over. Variables of this type
cannot make use of access modifiers (described later in this chapter).
Since, this type of variable is alive only within the scope of the method or block, it can only be
accessed within this block of code. Internally, local variables are created at the stack-level. So, when
they are created, they are pushed onto stack and as soon as the block finishes execution, the stack is
emptied. Lastly, the default value for local variables is garbage. So, these variables have to be
initialized for use.
Sample code to illustrate the working of local variables has been given below. It implements a local
variable ageP in the method is the class, which is accessed from the main method.
public class LVDemo {
public void puppyAge() {
int ageP = 0;
ageP = ageP + 10;
System.out.println("Age of the puppy is : " + ageP);
}
public static void main(String args[]) {
LVDemo testObj = new LVDemo();
testObj.puppyAge();
}
}
The output of this code has been illustrated in the image shown below.
Instance Variables
Variables that are created as part of the class, but do not lie within the scope of any method or
constructor are referred to as instance variable. The reason why these variables are called instance
variables is that they are created only once the object is created using that class. Therefore, these
variables are created for every object instantiated for this class using the new keyword.
Moreover, these variables are destroyed as soon as the object is deleted or the program execution
terminates. These variables can be accessed from the method or constructors implemented for this
class. It would not wrong to state that instance variables are class-level variables that can make use
of access modifiers.
These variables have default values. For instance, the default values for all numbers is 0 and that for
boolean if false. The object references created as reference variables are initialized as NULL. While
declaration of variables is a must, assignment can be done inside the methods or constructors. If you
are working inside the same class, you can directly access the variable by its name. However, if you
wish to access it from any static method, then you will need to access it using the format –
object_name.variable_name
Sample code has been given below to help you understand this concept better. This class implements
a class for employees and initializes the variables of the class using initialization methods.
import java.io.*;
public class demoEmployee {
public String nameEmp;
private double salaryEmp;
public demoEmployee (String initName) {
nameEmp = initName;
}
public void initSalary(double initSal) {
salaryEmp = initSal;
}
public void printEmployee() {
System.out.println("Employee Name = " + nameEmp );
System.out.println("Employee Salary = " + salaryEmp);
}
public static void main(String args[]) {
demoEmployee empObj = new demoEmployee("James");
empObj.initSalary(5000);
empObj.printEmployee();
}
}
The output of this code has been illustrated in the image shown below.
Static Variables
Any variable that is declared with the keyword static and is placed within the class, but outside the
methods, constructors or any other code block inside the class. Only one copy of this variable is
maintained for the whole class irrespective of the number of objects that may be created for this
class. Therefore, these variables are also referred to as class variable.
As a recommendation, these variables must not be used. However, there may be scenarios that require
such an implementation. However, whenever such variables are used, you must use them as constants,
for which values cannot be changed. These variables are created when the program execution starts.
However, they are destroyed only once the program’s execution terminates.
Class variables are visible for all elements of the class. Therefore, their visibility is similar to that of
instance variables. In fact, the default values for class variables are also same as that of instance
variables. The access to these variables can be made using the following statement –
class_name.variable_name
Sample code for implementation of static variables is given below.
import java.io.*;
public class SVDemo {
private static double salaryEmp;
public static final String DEPARTMENTEMP = "DevRD ";
public static void main(String args[]) {
salaryEmp = 1000;
System.out.println(DEPARTMENTEMP + "Salary = " + salaryEmp);
}
}
The output of the code can be seen in the image shown below.
Modifier Types
The behavior and access to the variables can be modified using modifiers. There are two main types
of modifier types namely access modifiers and non-access modifiers.
Access control modifiers
Java supports several access levels and each of this level has a corresponding keyword for
it. These include –
Public
Accessible to everyone
Private
Accessible to the class
Protected
Accessible to the class and its subclasses
Default
If no keyword is mentioned, the variable is accessible to the package.
Non-access modifiers
There are other modifiers, which are also available in Java. These include –
Static
Final
Abstract
Volatile and synchronized
Chapter 5: Operators
Variables can be manipulated using operators. There are six classes of operators supported by Java.
Each of these classes has been discussed in detail below.
Arithmetic Operators
All mathematical operations are performed using operators that fall under the category of arithmetic
operators. List of supported operators have been given below.
Addition (+)
This operator performs addition between two numbers. If a and b are two variable holding 5 and 6
respectively. Then, c = a+b, will yield c = 11.
Multiplication (*)
This operator performs multiplication between two numbers. If a and b are two variable holding 5
and 6 respectively. Then, c = a*b, will yield c = 30.
Subtraction (-)
This operator performs subtraction between two numbers. If a and b are two variable holding 5 and 6
respectively. Then, c = a-b, will yield c = -1.
Division (/)
This operator performs addition between two numbers. If a and b are two variable holding 10 and 5
respectively. Then, c = a/b, will yield c = 2.
Modulus (%)
This operator returns the remainder left after dividing the two numbers. If a and b are two variable
holding 10 and 5 respectively. Then, c = a%b, will yield c = 0.
Increment (++)
This operator adds 1 to the value of the variable. If a is a variable holding the value 1, then a++ will
yield the value 2.
Decrement (--)
This operator reduces 1 from the value of the variable. If a is a variable holding the value 1, then a--
will yield the value 0.
Relational Operators
All operations involving comparison are performed using relational operators. A list of the operators
supported by this programming language is given below –
NOT EQUAL TO (!=)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns FALSE else it return TRUE.
EQUAL TO (==)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns TRUE else it return FALSE.
GREATER THAN (>)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than the second operand, it returns TRUE else it return FALSE.
LESS THAN (<)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than the second operand, it returns TRUE else it return FALSE.
GREATER THAN OR EQUAL TO
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than or equal to the second operand, it returns TRUE else it return FALSE.
LESS THAN OR EQUAL TO
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than or equal to the second operand, it returns TRUE else it return FALSE.
Bitwise Operators
The only difference between normal operators and bitwise operators is that these operators perform
operations bit-by-bit. Moreover, these operators can be applied on byte, int, short, long and char. The
list of bitwise operators supported in Java include –
Bitwise AND (&)
This operator works on two operands and the output for each set of input bits is 1 if both the inputs
are one else the output is zero.
Bitwise OR (|)
This operator works on two operands and the output for each set of input bits is 1 if one or both of the
inputs is one else the output is zero.
Bitwise XOR (^)
This operator works on two operands and the output for each set of input bits is 1 only if one of the
inputs is one else the output is zero.
Bitwise COMPLEMENT (~)
This operator works on a single operand and negates the values from 0 to 1 and from 1 to 0.
LEFT SHIFT (<<)
This operator works on two operands. The bits of the left operand are shifted left. The number of
places is equal to the number specified as value for the second operand.
RIGHT SHIFT (>>)
This operator works on two operands. The bits of the left operand are shifted right by the number
specified as value for the second operand.
ZERO FILL RIGHT SHIFT (>>>)
This operator works on two operands. The bits of the left operand are shifted right by the number
specified as value for the second operand. Moreover, 0 replaces the bits that are shifted.
In order to understand how bitwise operations take place, let us take an example. Assume two
variables, a and b, having the values 60 and 13 respectively. The binary equivalent of a and b are as
follows –
a = 00111100
b = 00001101
Using the AND truth table according to which the output is 1 only if both the inputs are 1.
Correspondingly, the output of a&b = 00001100. Similarly other bitwise operations can also be
performed.
Logical Operators
All the logical operations in Java are performed using logical operators. The list of operators
supported by this programming language is given below.
Logical AND
This operator works on two operands. If both the operands are non-zero, the expression returns
TRUE else it returns FALSE.
Logical OR
This operator works on two operands. If one or both the operands are non-zero, the expression
returns TRUE else it returns FALSE.
Logical NOT
This operator works on one operand. If the operand is zero, this expression returns TRUE else it
returns FALSE.
Assignment Operators
The list of assignment operators supported by Java include –
Simple Assignment Operator (=)
This operator assigns the value computed by the right hand side to the variable on the left hand side. If
a, b and c are three variable and the expression is c = a+b, then the value of addition of a and b is
assigned to c.
Add AND Assignment Operator (+=)
This operator assigns the value computed by the addition of right hand side and left hand side to the
variable on the left hand side. If a and c are two variable and the expression is c += a, then the value
of addition of a and c is assigned to c.
Subtract AND Assignment Operator (-=)
This operator assigns the value computed by the subtraction of right hand side from left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c -= a, then the
value of c-a is assigned to c.
Multiply AND Assignment Operator (*=)
This operator assigns the value computed by the multiplication of right hand side and left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c *= a, then the
value of c*a is assigned to c.
Divide AND Assignment Operator (/=)
This operator assigns the value computed by the division of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c /= a, then the value
of c/a is assigned to c.
Modulus AND Assignment Operator (/=)
This operator assigns the value computed by the modulus of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c %= a, then the value
of c%a is assigned to c.
Left Shift AND Assignment Operator (<<=)
If a and c are two variable and the expression is c <<= a, then the value of c<<a is assigned to c.
Right Shift AND Assignment Operator (>>=)
If a and c are two variable and the expression is c >>= a, then the value of c>>a is assigned to c.
Bitwise AND Assignment Operator (&=)
If a and c are two variable and the expression is c &= a, then the value of c&a is assigned to c.
Bitwise XOR AND Assignment Operator (^=)
If a and c are two variable and the expression is c ^= a, then the value of c^a is assigned to c.
Bitwise Inclusive OR and Assignment Operator (|=)
If a and c are two variable and the expression is c |= a, then the value of c|a is assigned to c.
Operator Precedence
If an expression uses multiple operators, then operator precedence rules are used to determine the
order to execution of operations. The precedence of operators in terms of whether they will be
evaluated from right to left or left to right is defined for groups of operators in the following manner –
Right to Left
Unary
Conditional
Assignment
Left to Right
Postfix
Multiplicative
Additive
Shift
Relational
Equality
Bitwise AND
Bitwise XOR
Bitwise OR
Logical AND
Logical OR
For example, if we have to evaluate the expression a = 3 + 5 * 5, then multiplication is performed
before addition. Therefore, a = 28 instead of 40.
Chapter 6: Objects and Classes
To start with, let us understand the concept of classes and objects. Class is a template, which is used
to create objects. Objects are real entities that interact and form the core element of the Java program.
Three types of variables can exist in a class. Firstly, variables are defined inside the class, but
outside the method. Such variables are defined for each object and are termed as instance variables.
Besides this, variables can exist inside the method block of the class. These variables are private to
the method and are local variables. Any variable that is declared within a class, outside the method
block, using the word static is called class variable.
Creating Objects
Evidently, as the class is a template, you will need to create objects using this template. In order to
create objects, the keyword ‘ new’ is used. Creation of an object involves three steps. The first step is
to declare a variable for the object. The second step is to create an object using the new keyword.
Lastly, the object needs to be initialized using the constructor for the class.
\In case you omit the third step, Java uses the default constructor method for object initialization. All
these three steps are combined into one statement for object creation. For example, we have a class
DemoClass and we wish to create an object O1, then this can be done using the statement –
DemoClass O1 = new DemoClass
The variables and methods of the class for which the object is created can be accessed using ‘.’
operator. Therefore, if we have a class DemoCO with the variable x and we create an object O1, then
we can access x using the following statement: O1.x.
Constructors
When you get down to creating classes and objects, the first thing that you will need to do is initialize
the object. Java has a dedicated method implementation for initialization, which is called constructor.
These elements are implemented like methods, but they carry the same name as the class and have no
return type.
So, where can you use a constructor? You can use it whenever you are creating an object of a class
and you need to initialize some parameters or perform some function that is common to all the objects
of the class. For example, if you create a class called rectangle. You can create a constructor to
initialize the length and breadth of the rectangle.
If you don’t define a constructor, Java uses the default constructor for your program. This constructor
program initializes the value of all the parameters of the class to zero. So, if you have created a class,
your program will have an active constructor irrespective of whether you define it explicitly or not.
Let us now create a class with an explicit constructor and see how the concept works.
class SampleClass1 {
int i;
SampleClass1() {
i = 100;
}
}
public class DemoSampleClass1 {
public static void main(String args[]) {
SampleClass1 c1 = new SampleClass1();
SampleClass1 c2 = new SampleClass1();
System.out.println(c1.i + "\n" + c2.i);
}
}
The screenshot shown below illustrates the code and the output generated for the code upon
execution. In order to run this code, you need to create two files, each with the name of the class it
contains.
In the example shown above, we gave the parameter static values. However, your program may
require dynamic initialization of parameters. For this, you need to implement parameterized
constructors. Such constructors accept the value in the form of a parameter to the constructor method.
Sample implementation has been given below.
class SampleClass2 {
int i;
SampleClass2(int x) {
i = x;
}
}
public class DemoSampleClass2 {
public static void main(String args[]) {
SampleClass2 c1 = new SampleClass2(100);
SampleClass2 c2 = new SampleClass2(200);
System.out.println(c1.i + "\n" + c2.i);
}
}
The output for this code has been illustrated in the image shown below.
In reference to the implementation of constructors, a keyword is specifically used. This keyword is
the ‘ this’ keyword. It is used to refer to the object of the class under consideration. With the help of
this keyword, variables of the class can be accessed inside the constructor or methods. The use of this
keyword has been illustrated in the code given below.
class SampleClass3 {
int i;
SampleClass3(int i) {
this.i = i;
}
}
public class DemoSampleClass2 {
public static void main(String args[]) {
SampleClass3 c1 = new SampleClass3(200);
SampleClass3 c2 = new SampleClass3(200);
System.out.println(c1.i + "\n" + c2.i);
}
}
Upon execution, this code gives the following output –
Variable Arguments
In some programs, there may be a requirement where you don’t know the exact number of arguments
that the main method will give during execution. To allow dynamicity of this level, var-args or
variable arguments are used. Var-args are declared in the method parameter using the syntax:
<type>…<var_name>
The var_name given in the variable declaration is an array that contains all the variable values sent
by the main method while executing. Before implementing this concept, you need to remember two
things –
Only one var-args can be implemented per method.
If the method has other arguments (regular in nature), these arguments must appear before the
var-args. In other words, var-args must be the last argument in a method.
A sample implementation of this concept is given below.
public class DemoVarargs {
public static void main(String args[]) {
printNum(56.5, 3, 34, 2, 3);
printNum(new double[]{2, 1, 3});
}
public static void printNum( double... number) {
if (number.length == 0) {
System.out.println("No argument passed");
return;
}
double resultNum = number[0];
for (int x = 1; x < number.length; x++)
if (number[x] > resultNum)
resultNum = number[x];
System.out.println("The maximum value in the number set is " + resultNum);
}
}
The output for the code is illustrated in the image shown below.
Implementing Methods
A group of instructions that are used for performing an operation is referred to as a method. You can
see that the print statement in most of the programs shown above calls a method system.out.println().
This method prints the string supplied to it on the screen.
Just like this inbuilt method, the developer can also create methods specific to the problem statement.
User defined methods may or may not have parameters and may or may not return values. The
standard statements for creating a method is –
public static int methodDemo (int i, int j) {
/*body*/
}
Here, methodDemo is the name of the method and i and j are int parameters that this method accepts.
The logic for the method implementation is given inside the curly brackets. Besides this, you shall
also notice three words written in the function declaration – public, static and int. Here, int is the
return type of the method while public static is the modifier. This sample method can be modified to
suit the requirements of the developer.
A sample code for method implementation is presented below –
public static int minCalDemo (int num1, int num2) {
int minVal;
if (num1 > num2)
minVal = num2;
else
minVal = num1;
return minVal;
}
This method determines which value is the smallest between the two parametric values supplied to it
and returns this result to the calling method. Now that you have an idea about methods and how they
are implemented, it is time we discuss about how these methods are used in the overall code.
Calling a Method
A method needs to be called or invoked for it to be used. As you can see in the sample code given
above, the method is performing some computation and returning the result of the computation. Such a
method returns a value whose return type is already specified in the method declaration. Apart from
this, another type of method also exists. Such methods do not return anything and are popularly
referred to as methods with no return value.
When a program calls a methods, the control moves from the program to the method and the same
starts executing. Once a return statement is encountered, the control is transferred back to the calling
program. In the absence of a return statement, the control is automatically transferred back once a
closing brace of te method is encountered. This is usually the case for methods that have no return
value.
For methods that return a value, the return type is mentioned in the method declaration. On the other
hand, for methods that do not return nothing, the return type is void. In order to call the method we
implemented above, the following statement needs to appear somewhere in the calling program.
int result;
result = minCalDemo(5, 6);
Since the method returns an int value, this value needs to be gathered in an int variable (result). The
call for the method gives the two parametric values desired by the method. This type of method
calling is also called parametric method calling or passing parameters by value.
You may come across situations where you may have parameters of different types and many
parameters in number. In such cases, be sure to give the parameter values in the desired order to
avoid any uninvited compilation or runtime errors.
Method Overloading
It is possible to have methods with the same name, but different parameters. When a method is called,
the system detects the method with the parameter type and number given in the calling statement and
transfers control to the corresponding method. This form of method implementation is called method
overloading. Do not confuse this concept with overriding. In method overriding, the method name,
parameters and number of parameters are also same.
In order to understand this concept, let us take an example –
public class overloadingDemo {
public static void main(String[] args) {
int x = 34;
int y = 56;
double z = 10.5;
double u = 7.8;
int resultxy = minCalDemo(x, y);
double resultzu = minCalDemo(z, u);
System.out.println("Min Value (Integers) = " + resultxy);
System.out.println("Min Value (Double) = " + resultzu);
}
public static int minCalDemo (int num1, int num2) {
int minVal;
if (num1 > num2)
minVal = num2;
else
minVal = num1;
return minVal;
}
public static double minCalDemo (double num1, double num2) {
double minVal;
if (num1 > num2)
minVal = num2;
else
minVal = num1;
return minVal;
}
}
The code implements two methods with the same name minCalDemo with two different parameter
types. One of the methods uses two parameters of int type and has the return type int. On the other
hand, the other method implementation uses double parameters and returns a double. The output for
this code has been illustrated in the image shown below.
The decision making structures are used in situations where a set of instructions have to be executed
if the condition is true and another set of instructions have to be executed when the condition is
determined to be false. There are several constructs available in Java for programming such
scenarios. These structures include –
If statement
This statement is used in situations where a condition needs to be tested and if the condition is found
true, the block of code that follows this statement needs to be executed. The syntax for this construct
is –
if(condition){
/*Body*/
}
Sample implementation for this construct is given below –
public class ifDemo {
public static void main(String args[]) {
int i = 10;
int j = 1;
if(i>j){
System.out.print(i);
}
}
}
The output of this code upon execution is as follows –
If else statement
This statement is used in situations where a condition needs to be tested and if the condition is found
true, the block of code that follows this statement needs to be executed else the block of code that
follows the else statement is executed. The syntax for this construct is –
if(condition){
/*Body*/
}
else(
/*Body*/
}
Sample implementation for this construct is given below –
public class ifElseDemo {
public static void main(String args[]) {
int i = 1;
int j = 0;
if(i>j){
System.out.print(i);
}
else{
System.out.print(j);
}
}
}
The output of this code upon execution is as follows –
Nested if statement
This statement is used in situations where a condition needs to be tested and if the condition is found
true, the block of code that follows this statement needs to be executed else the next condition is
tested. If this condition is found true, the block of code corresponding to the if statement for this
condition is executed. If none of the conditions are found true, the block of code that follows the else
statement is executed. Multiple conditions can be tested using the nested if statements. The syntax for
this construct is –
if(condition1) {
/*Body*/
}
else if (condition2) (
/*Body*/
}
else {
/*Body*/
}
Sample implementation for this construct is given below –
public class nestedIfDemo {
public static void main(String args[]) {
int i = 0;
int j = 0;
if(i>j){
System.out.print(i);
}
else if(j>i) {
System.out.print(j);
}
else {
System.out.print("Equal");
}
}
}
The output of this code upon execution is as follows –
Switch
If you have a variable and different blocks of code need to be executed for different values of that
variable, the ideal construct that can be used is the switch statement. The syntax for this construct is –
switch(variable){
case <value1>:
/*body*/
break;
case <value2>:
/*body*/
break;
case <value3>:
/*body*/
break;
default:
/*body*/
break;
}
Sample implementation for this construct is given below –
public class switchDemo {
public static void main(String args[]) {
int i = 5;
switch (i) {
case 0:
System.out.print(0);
break;
case 2:
System.out.print(2);
break;
case 5:
System.out.print(5);
break;
default:
System.out.print(999);
break;
}
}
}
The output of this code upon execution is as follows –
Conditional Operator
Java also supports the conditional operator, which is also known as the ?: operator. This operator is
used to replace the ‘if else’ construct. Its syntax is as follows –
Expression1 ? Expression2 : Expression3
Here, Expression1 is the condition that is to be tested. If the condition is true, Expression2 is
executed else Expression3 is executed.
Chapter 8: Loop Control
There are several situations that require you to iterate the same set of instructions a number of times.
For instance, if you need to sort a set of numbers, you will need to scan and rearrange the set several
times to get the desired arrangement. This flow of execution is known as loop control.
Simply, a loop is a construct that allows execution of a block of code many times. Java supports
several constructs that can be used for implementing loops. These include while loop, for loop and do
while loop.
A while loop executes a block of code iteratively until the condition specified for the while
loop is true. The moment this condition fails, while loop stops.
For loop allows the programmer to manipulate the condition and loop variable in the same
construct. Therefore, you can initialize a loop variable, increment/decrement it and run the
loop until a condition on this variable is true.
Do while loop is similar to while loop. However, in the while loop, the condition is checked
before executing the block code. On the other hand, in a do while loop, the block of code is
executed and then the condition is checked. If the condition is satisfied, the loop execution is
again initiated else the loop is terminated. It would not be wrong to state that the do while
loop once implemented will execute at least once.
Loop statements
There are two keywords that are specifically used in connection with loops and are also termed as
control statements as they allow transfer of control from one section of the code to a different section.
These keywords are –
break
This keyword is used inside the loop at a point where you want the execution flow to terminate the
loop and directly start execution from the first instruction that appears after the loop.
continue
This keyword is used inside the loop at a point where the programmer wants the computer to
overlook the rest of the loop and move the control to the first statement of the loop.
In order to help you understand how loops are executed, let us take an example and implement it
using all the three types of loop control.
All the file operations are supported by Java under the java.io package and the implementation of
these functions is based on the concept of streams. Stream is simply a sequence of data, which is of
two types namely, InputStream and OutputStream. While the former is used to read data, the latter is
used to write data.
Byte Streams
The first type of stream supported by java is byte stream. The I/O operations that are restricted to 8-
bit size fall under this category. Before we get down to coding, you need to realize that the classes
used for performing input and output are FileInputStream and FileOutputStream respectively. Let us
now look at an example that copies the contents of one file to the other.
import java.io.*;
public class CopyFileBS {
public static void main(String args[]) throws IOException{
FileInputStream inputFile = null;
FileOutputStream outputFile = null;
try {
inputFile = new FileInputStream("in.txt");
outputFile = new FileOutputStream("out.txt");
int i;
while ((i = inputFile.read()) != -1) {
outputFile.write(i);
}
} finally {
if (inputFile != null) {
inputFile.close();
}
if (outputFile != null) {
outputFile.close();
}
}
}
}
Keep an input file named in.txt in the same folder as the class file and execute the code to see what it
does.
Character Streams
Moving from 8-bit data operations to 16-bit Unicode data operations, we need to switch from Binary
Streams to Character Streams. The classes used for performing input and output is FileReader and
FileWriter respectively. The code shown above can be modified to use character streams in the
following manner.
import java.io.*;
public class CopyFileCS {
public static void main(String args[]) throws IOException {
FileReader inputFile = null;
FileWriter outputFile = null;
try {
inputFile = new FileReader("in.txt");
outputFile = new FileWriter("out.txt");
int i;
while ((i = inputFile.read()) != -1) {
out.write(i);
}
}finally {
if (inputFile != null) {
inputFile.close();
}
if (outputFile != null) {
outputFile.close();
}
}
}
}
Keep an input file named in.txt in the same folder as the class file and execute the code to see what it
does.
Standard Streams
In order to allow the user to take input from the keyboard and print the output on the screen, Java
supports the standard streams –
System.in represents the standard input stream and allows user to give input via the
keyboard.
System.out represents the standard output stream and allows user to get output on the screen.
System.err represents the standard error stream and allows user to error messages from the
system.
The sample program given below allow the system to take input from the user and print the input
given to the screen until the user hits the ‘q’ key after which the program quits.
import java.io.*;
public class SSDemo {
public static void main(String args[]) throws IOException{
InputStreamReader inputC = null;
try {
inputC = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char charIn;
do {
charIn = (char) inputC.read();
System.out.print(charIn);
} while(charIn != 'q');
}finally {
if (inputC != null) {
inputC.close();
}
}
}
}
This program can be executed to see what the output is and how the code works.
Chapter 10: Exception Handling
Exception is any event that is unexpected, usually in manner that cannot be handled by the program
concerned. Obviously, the normal flow of execution of the program is hampered in such a situation
and the program may either terminate with an error or behave abnormally. This is the reason why
exceptions need to handled by the program only.
So, why do exceptions occur? Exceptions may occur because of a range of reasons. Some of the
scenarios that may lead to this inadvertent situation include –
Invalid data entry
The program is trying to open a file that is not present at the specified location
The JVM has fallen short of memory
Network communication is being carried out and the system loses network connection.
Evidently, exceptions may occur due to problems created by the system, user or issues at the program
level. On the basis of this observation, three classes of exceptions have been created. These three
classes of exceptions have been discussed in chapter.
Checked Exceptions
Exceptions that are checked and reported by the compiler at the time of compilation are termed as
checked exceptions. They are also called compile time exceptions and need to be handled by the
developer during the time he or she writes code.
An example of how exception handling for such a error is performed is shown in the sample code
given below.
import java.io.File;
import java.io.FileReader;
public class demoEH {
public static void main(String args[]) {
File fileDemo = new File("E://samplefile.txt");
FileReader inpFile = new FileReader(fileDemo);
}
}
If the filename and location specified while creating fileDemo handler is not present at the specified
location, then the compiler gives the error FileNotFoundException.
Unchecked Exceptions
There are some exceptions that happen at runtime. Such exceptions are called unchecked exceptions
or runtime exceptions. Logical errors, programming bugs and wrong usage of APIs are examples of
this type of error. Another important characteristic of this type of errors is that they are not detected at
the time of compilation.
To help you understand what runtime errors are, let us take an example. Consider that you have
implemented an array of 5 elements as part of your program. However, part of the code is accessing
the 6 th element. This error will be detected at runtime and the system will generate the error
ArrayIndexOutOfBoundsExceptionexception .
Errors
There are some exceptions, which are beyond the control of the system or the programmer. A common
example of such errors is stack overflow. There is hardly anything that you can do about these errors.
So, it is best to ignore them. As and when they occur, they will interrupt the execution of your
program, but nothing can be done about it.
Exception Hierarchy
Java has an inbuilt class named java.lang.Exception and all the exceptions fall under this class. All
the exception classes are subclasses of this class. Moreover, Throwable class is the superclass of the
exception class. Another subclass of the Throwable class is the Error class. All the errors like stack
overflow described above fall under this Error class.
The Exception class has two subclasses namely RuntimeException class and IOException class. A
list of the methods, for which definitions are available in Java, as part of the Throwable class, is
given below.
public String getMessage()
When called, this message returns a detailed description of the exception that has been encountered.
public Throwable getCause()
This method when called returns a message that contains the cause of the exception.
public String toString()
This method returns the detailed description of the exception concatenated with the name of the class.
public void printStackTrace()
The result of toString() along with a trace of the stack can be printed to the standard error stream,
System.err, can be done by calling this method.
public StackTraceElement [] getStackTrace()
There may be some scenarios where you may need to access different elements of the stack trace.
This method returns an array, with each element of the stack trace saved to different elements of the
array. The first element of array contains the top element of the stack trace while the bottom of the
stack trace is saved to the last element of the array.
public Throwable fillInStackTrace()
Appends the previous information in the stack trace with the current contents of the stack trace and
returns the same as an array.
Catching Exceptions
The standard method to catch an exception is using the ‘try and catch’ keywords along with their code
implementations. This try and catch block needs to be implemented in such a manner that it encloses
the code that is expected to raise an exception. It is also important to mention here that the code that is
expected to raise an exception is termed as protected code. The syntax for try and catch block
implementation is as follows –
try {
/*Protected code*/
}catch(ExceptionName exc1) {
/*Catch code*/
}
The code that is expected to raise an exception is placed inside the try block. If the exception is
raised, then the corresponding action to be performed for exception handling is implemented in the
catch block. It is imperative for every try block to either have a catch block or a finally block.
As part of the catch statement, the exception, which is expected to be raised needs to be declared. In
the event that an exception occurs, the execution is transferred to the catch block. If the raised
exception matches the exception defined in the catch block, the catch block is executed.
A sample implementation of the try and catch block is given below. The code implements an array
with 2 elements. However, the code tries to access the third element, which does not exist. As a
result, an exception is raised.
import java.io.*;
public class demoException {
public static void main(String args[]) {
try {
int arr[] = new int[2];
System.out.println("Accesing the 3 rd element of the array:" + arr[3]);
}catch(ArrayIndexOutOfBoundsException exp) {
System.out.println("Catching Exception:" + exp);
}
System.out.println("Reached outside catch block");
}
}
The output of this code is shown in the image below.
Keywords: Throw/Throws
These two keywords are similar words that are used for two entirely different purposes. The
keyword throws is used at the end of the method name to declare that the code throws a checked
exception, but the method does not handle it. In other words, this keyword is used to delay the
handling of a thrown exception. On the other hand, throw keyword is used to literally throw an
exception. This exception may be a new one or an exception that has previously occurred.
Sample code that illustrates the use of throws and throw is given below. In the method declaration, it
has been declared that the method throws an exception RException while the use of throw initiates the
throwing of this exception.
import java.io.*;
public class cName {
public void depositMethod(double amountDep) throws RException {
/*Implementation*/
throw new RemoteException();
}
/*Implementation
}
It may happen that a method may throw more than one exception. In order to declare these exceptions
in the method declaration statement, you can provide a comma-separated list of exceptions. A sample
implementation of this concept has been given below.
import java.io.*;
public class cName {
public void withdrawDemo(double amountDemo) throws RException, InsuffFundsException
{
/*Implementation*/
}
/*Implementation*/
}
Finally Block
Now that you are thorough with the try and catch block, let us look at the third block used in exception
handling, finally block. This is the last block that appears after the ‘try and catch’ blocks. Moreover,
the execution of the catch block may be omitted if the exception is not found, but the finally block is
always executed irrespective of whether the exception occurs or not.
The objective of this block is to perform any cleanup activities that may be deemed necessary by the
programmer. This is the code that you want to execute no matter what happens to the code enclosed in
the try block. The syntax of this block and how it can be implemented has been shown below.
try {
/*Protected code*/
}catch(ExpType1 exp1)
{
/*Catch block 1*/
}catch(ExpType2 exp2) {
/*Catch block 2*/
}catch(ExpType3 exp3) {
/*Catch block 3*/
}finally {
/*Finally block implementation*/
}
Sample code that implements this concept is given below to make the concept clearer.
public class demoExcep {
public static void main(String args[]) {
int arr[] = new int[2];
try {
System.out.println("Accessing the 3 rd element:" + arr[3]);
}catch(ArrayIndexOutOfBoundsException exp) {
System.out.println("Catching exception:" + exp);
}finally {
arr[0] = 5;
System.out.println("The first element is: " + arr[0]);
System.out.println("Finally block executed");
}
}
}
The output of the code is shown in the image below.
While implementing the try/catch/finally blocks, always remember a few things. Firstly, there cannot
be a catch block unless you have implemented a try block. Analogously, there cannot be a standalone
try block without a catch or finally block. Besides this, finally block is an optional construct and your
try/catch will work just fine even if you don’t have a finally block in your code.
User-defined Exceptions
Java allows you to define your own exceptions. However, before you can do that, there are a few
things that you need to remember. Firstly, any exception needs to be derived or be a child of
Throwable class. In order to implement a checked exception, you will have to extend the Exception
class. However, the implementation of runtime exception has to extend RuntimeException class.
The standard method for defining an exception is –
class demoException extends Exception { }
The following code illustrates the implementation and use of user-defined exceptions.
import java.io.*;
public class InsuffFundsException extends Exception {
private double amo;
public InsuffFundsException(double amo) {
this.amo = amo;
}
public double getAmo () {
return amo;
}
}
Conclusion
This book gave you a beginner’s tutorial on Java fundamentals. We have covered all the basic
concepts of java programming and everything you need to get started with java programming. Now
that you have had a run-through of all the basic concepts of Java and assuming that you have tried all
the codes given in this book, you are all set to jump to advanced java programming.
The key to becoming an expert at programming, be it any programming language, is practice. The
more you will practice, the better your programming skills will become! We hope you enjoyed this
book and that this book has helped you gain a basic level expertise in java. We hope to have laid the
right foundation for you to hone your skills and become an expert Java programmer.
Javascript
Learn Javascript in 2 hours And Start
Programming Today
Introduction
JavaScript is a lightweight programming language, which is primarily why it is used for web pages.
The use of this programming language allows seamless client-server interaction, adding dynamicity to
the web pages. Besides this, JavaScript implements object oriented methodology and is interpreted,
not compiled!
The first name given to JavaScript was LiveScript. Netscape released JavaScript under this name in
1995. However, in view of the immense popularity gained by Java, its name was changed to
JavaScript. Many web browsers including Internet Explorer and Netscape includes the general core
of the language.
Server-Client Interactions
The most common form of this programming language is client-side JavaScript. The browser
interprets the code only if the script is embedded in or is referenced by the HTML document. In order
words, the HTML for the webpage isn’t static and includes code that allows it to control the browser,
interact with the user and create HTML content dynamically.
Development Tools
Although, there are several editing tools available for JavaScript, the beauty of this language is that
you can start working with JavaScript with just a text editor. You don’t need a compiler or in other
tool for running JavaScript. Since, this programming language is integrated with the web browser, it
is directly interpreted and executed. If you still wish to use a development tool, you can look at
Macromedia Dreamweaver MX, Microsoft FrontPage and Macromedia Homesite 5.
Chapter 2: Syntax
The JavaScript code is enclosed within the <script></script> tag. This script is embedded inside the
HTML file by placing it inside the <body></body> of the <html></html> tags. As you can see, the
code is also enclosed inside HTML comments. The reason for doing this is that it prevents browsers
that do not understand JavaScript to use this code unlawfully.
As part of the main code, document.write function is called, which prints the string given to it as
parameter on the screen. This function can be used to write HTML as well. In order to execute this
code, open a text editor and copy this code to the file. Save the file as index.htm and open it in a web
browser that supports JavaScript. The result of this can be shown in the image below.
Case Sensitivity
JavaScript is sensitive to capitalization or case of the letters being used. For instance, I and i are two
different identifiers for JavaScript. This holds true for any keyword, function name or variable name
that you use. Anything you write in JavaScript must have a consistent case for it to be identifiable by
JavaScript.
Writing Comments
JavaScript identifies both C and C++ style of comments. The single line comments can be made by
writing // at the beginning of the line. In this scenario, anything that is written between the //
characters and end of the line are treated as comments and ignored by JavaScript. The other type of
comments supported by JavaScript is the multi-line comment. Such a comment begins with /* and
ends with */. JavaScript ignores any character and number of lines that lie between these two
character sequences.
Besides the above-mentioned, JavaScript also supports HTML style of commenting. However, it only
recognizes <!-- and treats the characters following this character phrase till the end of the line as a
single line comment. JavaScript does not recognize the HTML comment closing character sequence, -
->. Therefore, as and when you require the use of this character phrase, you must precede it with //.
In order to help you understand this in a better way, sample code has been given below.
<script language="javascript" type="text/javascript">
<!--
// Single line comment.
/* Multi-line comment
Similar to the comments in C and C++ */
//-->
</script>
Chapter 3: Enabling JavaScript in Browsers
Most of the browsers that are being used today support JavaScript. However, you may be required to
disable or enable this feature of your browser. You may perform this operation manually. This chapter
gives you a quick insight into how manual enabling and disabling of JavaScript can be performed for
browsers like Firefox, Google Chrome and Internet Explorer.
Firefox
In order to enable or disable JavaScript on Firefox, you need to follow the steps given below –
Open a new window and in the address bar of the tab, type – about: config. This will bring a dialog
box in front of you, which shall give you a warning. Choose the option that says ‘I’ll careful, I
promise!’ Once you choose this option, the browser will present you with a list of configure options.
Type - javascript.enabled - in the search bar. If you right click on this value, you will see an option
that says select toggle. Choosing this option will simply toggle the value. If JavaScript is enabled,
then choosing this option will disable it else it will be enabled.
Chrome
In order to enable or disable JavaScript on Google Chrome, you need to follow the steps given below
–
Enter the Chrome menu by clicking on a symbol on the top right hand corner of the window. From the
available options, choose Setting and click on ‘Show Advanced Setting’. The window that will
option after this will have a section named Privacy. Look for the button that says Content settings. You
will be able to locate a JavaScript section under this button. To enable JavaScript, select Allow all
sites to run JavaScript (recommended)’ else select ‘Do not allow any site to run JavaScript’.
Although, the user is free to include the JavaScript code anywhere inside the HTML document as long
as the code is enclosed inside the <script></script> tags, there are some preferred ways of its
inclusions. These practices are described below.
Including JavaScript Code in <HEAD></HEAD> Section
Typically, if you wish to trap user clicks, code related to the same is included in the head section of
the HTML document. In order to help you understand this concept, a sample code is given below.
<html>
<head>
<script type="text/javascript">
<!--
function pHWorld() {
alert("HelloWorld!")
}
//-->
</script>
</head>
<body>
<input type="button" onclick=" pHWorld ()" value="Print HelloWorld!" />
</body>
</html>
Including JavaScript Code in <BODY></BODY> Section
If there is some JavaScript functionality that you want to run after the page has loaded, then this script
should appear inside the body of the HTML document. The code given below shows how JavaScript
code can be embedded into the body of an HTML document.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("HelloWorld!")
//-->
</script>
<p>Body of HTML document</p>
</body>
</html>
Including JavaScript Code in <HEAD></HEAD> and <BODY></BODY> Sections
You can have different JavaScript codes embedded in the head and body sections of the same HTML
document. Sample code to illustrate how this can be done is given below.
<html>
<head>
<script type="text/javascript">
<!--
function printHW() {
alert("HelloWorld!")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("HelloWorld!")
//-->
</script>
<input type="button" onclick="printHW()" value="Print Hello World" />
</body>
</html>
Before we discuss variables, it is important to mention the data types that JavaScript supports. This is
a fundamental characteristic of any programming language that tells the types of data that this language
allows the developer to work with and manipulate. JavaScript supports three primitive data types.
These include –
Boolean
Boolean data type supports only two values namely, true and false.
Strings
This data type allows the use of combination of characters. For example, ‘Hello World’ is a string.
Numbers
Manipulation of numbers is a basic functionality supported by most programming languages. Unlike
other programming languages, there is no difference between floating point numbers and integers. All
numbers are treated as just ‘numbers’.
In addition to the above-mentioned, JavaScript also supports two trivial data types namely, undefined
and null. Both these data types support only one value. Apart from these, JavaScript also supports a
composite data type namely objects. However, this topic is a part of advanced JavaScript
programming and is beyond the scope of this book.
Scope of Variables
The scope of a variable is the region within which it holds value. There are two scopes allowed in
JavaScript, which are as follows –
Local Variable
Variables that are declared and defined within a function are local variables and are available only
inside the function. Moreover, function parameters are also local variables and their scope of use is
limited to the function.
Global Variable
This type of variables can be declared anywhere in the JavaScript code and their scope of use is the
whole file.
If you have a local name inside a function with the same name as that of a global variable, then the
precedence is given to the local variable inside the function. In this manner, the global variable is
hidden for that function. Sample code to illustrate this functionality is given below –
<html>
<body onload = demoScope();>
<script type = "text/javascript">
<!--
var var1 = "global";
function demoScope( ) {
var var1 = "local";
document.write(var1);
}
//-->
<
/script>
</body>
</html>
Names of Variables
JavaScript follows some naming conventions when it comes to naming variables. These rules are as
follows –
Keywords cannot be used as variable names. For example, you cannot name a variable as
var.
Variable names cannot begin with numerals. They can only begin with underscore (_) or a
character. For example, _var1 and var56 are valid variable names, but 1var is not a valid
variable name.
Please note that JavaScript is case-sensitive. Therefore, if you have declared a variable
name as emp, then you cannot access this variable using Emp or eMp names.
double
In super
Chapter 6: Operators
Operators are symbols that perform mathematical operations on one or two values. In order to
understand this, let us take a simple expression, 1+4. Here, 1 and 4 are values, which are referred to
as operands and + is the operator that performs the mathematical operation of addition on these two
operands. JavaScript supports five types of operators. These types have been described below.
Arithmetic Operators
The list of arithmetic operators supported by Java is as follows –
Addition (+)
This operator adds the values of the two operands. If there are two variables a and b with values 10
and 5, then a+b gives 15. Please note that the addition operator when used with string type operands
performs concatenation. For example, if there are two variables, a and b with values ‘sa’ and 3, then
a+b will give the result sa3.
Subtraction (-)
This operator subtracts the values of the two operands. If there are two variables a and b with values
10 and 5, then a-b gives 5.
Multiplication (*)
This operator multiplies the values of the two operands. If there are two variables a and b with
values 10 and 5, then a*b gives 50.
Division (/)
This operator divides the values of the first operand with that of the second operand. If there are two
variables a and b with values 10 and 5, then a/b gives 2.
Modulus (%)
This operator returns the remainder of the division operation between the two operands. If there are
two variables a and b with values 10 and 5, then a%b gives 0.
Increment (++)
This operator adds 1 to the value of the operand. For example, if a is a variable with value 10, then
++a will give the result 11.
Decrement (--)
This operator subtracts 1 from the value of the operand. For example, if a is a variable with value 10,
then --a will give the result 9.
The code given below illustrates the working of operators.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 5;
var c = "sa";
var val;
var linebreak = "<br />";
document.write("a + b = ");
val = a + b;
document.write(val);
document.write(linebreak);
document.write("a + c = ");
val = a + c;
document.write(val);
document.write(linebreak);
document.write("a - b = ");
val = a - b;
document.write(val);
document.write(linebreak);
document.write("a * b = ");
val = a * b;
document.write(val);
document.write(linebreak);
document.write("a / b = ");
val = a / b;
document.write(val);
document.write(linebreak);
document.write("a % b = ");
val = a % b;
document.write(val);
document.write(linebreak);
document.write("++a = ");
val = ++a;
document.write(val);
document.write(linebreak);
document.write("--a = ");
val = --a;
document.write(val);
document.write(linebreak);
//-->
</script>
Change the values and see the result!
</body>
</html>
The output of the code is illustrated in the image shown below.
Comparison Operators
The list of comparison operators supported by Java is as follows –
Equal (==)
This operator compares the value of the two operators and if the values are equal, it returns true else
it returns false. For example, if we have two variables a and b with the values 10 and 5, a==b will
give false.
Not Equal (!=)
This operator compares the value of the two operators and if the values are equal, it returns false else
it returns true. For example, if we have two variables a and b with the values 10 and 5, a==b will
give true.
Greater Than (>)
This operator compares the value of the two operators and if the value of the first operand is greater
than that of the second operand, it returns true else it returns false. For example, if we have two
variables a and b with the values 10 and 5, a>b will give true.
Less Than (<)
This operator compares the value of the two operators and if the value of the first operand is less than
that of the second operand, it returns true else it returns false. For example, if we have two variables
a and b with the values 10 and 5, a<b will give false.
Greater Than Or Equal To (>=)
This operator compares the value of the two operators and if the value of the first operand is greater
than or equal to that of the second operand, it returns true else it returns false. For example, if we
have two variables a and b with the values 10 and 5, a>=b will give true.
Less Than Or Equal To (<=)
This operator compares the value of the two operators and if the value of the first operand is less than
that of the second operand, it returns true else it returns false. For example, if we have two variables
a and b with the values 10 and 5, a<=b will give false.
The code given below illustrates the working of operators.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 5;
var val;
var linebreak = "<br />";
document.write("(a == b) => ");
val = (a == b);
document.write(val);
document.write(linebreak);
document.write("(a != b) => ");
val = (a != b);
document.write(val);
document.write(linebreak);
document.write("(a > b) => ");
val = (a > b);
document.write(val);
document.write(linebreak);
document.write("(a < b) => ");
val = (a < b);
document.write(val);
document.write(linebreak);
document.write("(a >= b) => ");
val = (a >= b);
document.write(val);
document.write(linebreak);
document.write("(a <= b) => ");
val = (a <= b);
document.write(val);
document.write(linebreak);
//-->
</script>
Change the values and see the result!
</body>
</html>
The output of the code is illustrated in the image shown below.
Logical Operators
The list of logical operators supported by Java is as follows –
Local AND (&&)
This operator performs logical AND operation on the two operands. If both the operands are non-
zero, then the result is true. For example, if we have two variables a and b with the values 10 and 5,
a&&b will give true.
Local OR (||)
This operator performs logical OR operation on the two operands. If both or one of the operands are
non-zero, then the result is true. For example, if we have two variables a and b with the values 10 and
5, a&&b will give true.
Local NOT (!)
This operator performs negation operation. If the value of the operand is non-zero, then the result is
false else the result is true. For example, if we have a variable a with the value 10, !a will give false.
The code given below illustrates the working of operators.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 5;
var val;
var linebreak = "<br />";
document.write("(a && b) => ");
val = (a && b);
document.write(val);
document.write(linebreak);
document.write("(a || b) => ");
val = (a || b);
document.write(val);
document.write(linebreak);
document.write("(!a) => ");
val = (!a);
document.write(val);
document.write(linebreak);
//-->
</script>
Change the values and see the result!
</body>
</html>
The output of the code is illustrated in the image shown below.
Bitwise Operators
The list of logical operators supported by Java is as follows –
Bitwise AND (&)
This operator performs bitwise AND operation on the two operands. If both the bits are non-zero,
then the result is true. For example, if we have two variables a and b with the values 10 (binary
equivalent = 1010) and 5 (binary equivalent = 0101), a&b will give 0.
Bitwise OR (|)
This operator performs bitwise OR operation on the two operands. If both the bits and/or one of the
bits are non-zero, then the result is true. For example, if we have two variables a and b with the
values 10 (binary equivalent = 1010) and 5 (binary equivalent = 0101), a|b will give 15.
Bitwise XOR (^)
This operator performs bitwise XOR operation on the two operands. If only one of the bits is non-
zero, then the result is true. For example, if we have two variables a and b with the values 10 (binary
equivalent = 1010) and 5 (binary equivalent = 0101), a^b will give 15.
Bitwise NOT (~)
This operator performs bitwise NOT operation on the two operands. The value of the bit is toggled.
In other words, if the bit is 1, it is changed to 0 and if it is 0, then it is changed to 1. For example, if
we have a variable a with the value 10 (binary equivalent = 1010), ~a will give 5.
Left Shift (<<)
This operator shifts the bits of the first operand to the left. The number of times this shifting is
performed is determined by the value of the second operand. For example, if we have two variables a
and b with the values 2 (binary equivalent = 010) and 1, a<<b will give 4.
Right Shift (>>)
This operator shifts the bits of the first operand to the right. The number of times this shifting is
performed is determined by the value of the second operand. For example, if we have two variables a
and b with the values 2 (binary equivalent = 010) and 1, a>>b will give 1.
Right Shift With Zero (>>>)
This operator shifts the bits of the first operand to the right. The number of times this shifting is
performed is determined by the value of the second operand. The bits that are shifted are filled with
0s. For example, if we have two variables a and b with the values 2 (binary equivalent = 010) and 1,
a>>>b will give 1.
The code given below illustrates the working of operators.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 5;
var val;
var linebreak = "<br />";
document.write("(a & b) => ");
val = (a & b);
document.write(val);
document.write(linebreak);
document.write("(a | b) => ");
val = (a | b);
document.write(val);
document.write(linebreak);
document.write("(a ^ b) => ");
val = (a ^ b);
document.write(val);
document.write(linebreak);
document.write("(~a) => ");
val = (~a);
document.write(val);
document.write(linebreak);
a = 2;
b = 1;
var linebreak = "<br />";
document.write("(a<<b) => ");
val = (a<<b);
document.write(val);
document.write(linebreak);
document.write("(a>>b) => ");
val = (a>>b);
document.write(val);
document.write(linebreak);
document.write("(a>>>b) => ");
val = (a>>>b);
document.write(val);
document.write(linebreak);
//-->
</script>
Change the values and see the result!
</body>
</html>
The output of the code is illustrated in the image shown below.
Assignment Operators
The list of assignment operators supported by Java is as follows –
Simple Assignment (=)
This operator assigns the value computed by executing the expression on the right hand side to the left
hand side variable. For example, if we have three variables a, b and c. The values of a and b are 2
and 1 respectively. The value of c after executing the statement c = a+b is 3.
Add and Assignment (+=)
This operator assigns the value computed by adding the value of the variable on the right hand side to
that of the variable on the left hand side to the left hand side variable. For example, if we have two
variables a and b. The values of a and b are 2 and 1 respectively. The value of a after executing the
statement a += b is 3.
Subtract and Assignment (-=)
This operator assigns the value computed by subtracting the value of the variable on the left hand side
to that of the variable on the right hand side to the left hand side variable. For example, if we have
two variables a and b. The values of a and b are 2 and 1 respectively. The value of a after executing
the statement a -= b is 1.
Multiply and Assignment (*=)
This operator assigns the value computed by multiplying the value of the variable on the left hand side
to that of the variable on the right hand side to the left hand side variable. For example, if we have
two variables a and b. The values of a and b are 2 and 1 respectively. The value of a after executing
the statement a *= b is 2.
Divide and Assignment (*=)
This operator assigns the value computed by dividing the value of the variable on the left hand side to
that of the variable on the right hand side to the left hand side variable. For example, if we have two
variables a and b. The values of a and b are 2 and 1 respectively. The value of a after executing the
statement a /= b is 2.
Modulus and Assignment (%=)
This operator assigns the remainder computed by dividing the value of the variable on the left hand
side to that of the variable on the right hand side to the left hand side variable. For example, if we
have two variables a and b. The values of a and b are 2 and 1 respectively. The value of a after
executing the statement a %= b is 0.
The code given below illustrates the working of operators.
<html>
<body>
<script type="text/javascript">
<!--
var a = 2;
var b = 1;
var c;
var linebreak = "<br />";
document.write("(c=a+b) => ");
c = a+b;
document.write(c);
document.write(linebreak);
document.write("(a += b) => ");
a += b;
document.write(a);
document.write(linebreak);
document.write("(a -= b) => ");
a -= b;
document.write(a);
document.write(linebreak);
document.write("(a *= b) => ");
a *= b;
document.write(a);
document.write(linebreak);
document.write("(a /= b) => ");
a /= b;
document.write(a);
document.write(linebreak);
document.write("(a %= b) => ");
a %= b;
document.write(a);
document.write(linebreak);
//-->
</script>
Change the values and see the result!
</body>
</html>
The output of the code is illustrated in the image shown below.
Miscellaneous Operators
Apart from the operators discussed above, there are two more operators supported by JavaScript.
These operators are typeof operator ad conditional operator (?:). The conditional operator will be
discussed in the chapter on Decision Making.
The typeof operator can be used to determine the data type of the value that a variable is holding. The
values returned by this operator include Boolean, string, number, function, object and undefined. For
a variable holding null value, the typeof operator returns object.
Chapter 7: Decision Making
The most common construct used in all programming languages is the decision making construct. It is
typically used to tell the computer the execution path that it must take on the basis of the value of a
variable. This condition-based logic of this construct also gives it the name conditional construct.
JavaScript supports three conditional constructs, which have been described below.
The if statement
When this construct is used, it executes the statements within the ‘if’ block provided the condition
mentioned inside the ‘if’ statement is true. On the other hand, if the expression returns false, no
statements will be executed and the execution will start from the next statement outside the ‘if’ block.
The syntax of this construct is as follows –
if (expression){
//Statements to be executed if the expression returns true
}
Sample code to illustrate the working of this conditional construct is given below.
<html>
<body>
<script type="text/javascript">
<!--
var i = 5;
if( i > 10 ){
document.write("<b>Inside If!</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Upon execution, this code gives the following result –
The if else statement
When this construct is used, it executes the statements within the ‘if’ block provided the condition
mentioned inside the ‘if’ statement is true. On the other hand, if the expression returns false, the
statements inside the else block will be executed. The syntax of this construct is as follows –
if (expression){
//Statements to be executed if the expression returns true
}
else{
//Statements to be executed if the expression returns false
}
Sample code to illustrate the working of this conditional construct is given below.
<html>
<body>
<script type="text/javascript">
<!--
var i = 5;
if( i > 10 ){
document.write("<b>Inside If!</b>");
}
else{
document.write("<b>Inside else!</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Upon execution, this code gives the following result –
Conditional Operator
Conditional operator simplifies by the if…else construct by allowing the developer to implement it in
the form of an operator. The syntax of the conditional operator is <expression>?<expression if true>:
<expression if false>. For example, consider the statement –
a>b?c=1:c=0
Here, the values of a and b are compared. If a is greater than b, then c is assigned the value 1 else c is
assigned the value 0.
Chapter 8: Loop Constructs
Looping is another fundamental programming construct that most programming languages support.
Fundamentally, looping is used to execute the same set of statements iteratively until a condition
remains true. JavaScript supports four types of looping constructs.
While Loop
The most basic loop construct is the while loop. This type of a loop executes the set of statements
inside the while loop until the expression for the while is true. As soon as the expression becomes
false, the while loop execution terminates. The syntax for implementation of while is given below –
while (expression){
//Statements of the while block
}
Sample implementation of the while loop is given below –
<html>
<body>
<script type="text/javascript">
<!--
var c = 0;
document.write("Loop begins…");
while (c < 5){
document.write("Value of c: " + c + "<br />");
c++;
}
document.write("Loop Terminates!");
//-->
</script>
<p>Change the values of the looping variable to see how things change</p>
</body>
</html>
The output of the code upon execution is shown in the image given below.
Do…While Loop
Another looping construct is the do...while loop. The condition’s validity is checked at the end of the
loop. So, this loop is that it executes at least once. This type of a loop executes the set of statements
inside the do…while loop until the expression for the while is true. As soon as the expression
becomes false, the while loop execution terminates. The syntax for implementation of while is given
below –
do{
//Statements of the while block
}while (expression)
Sample implementation of the do…while loop is given below –
<html>
<body>
<script type="text/javascript">
<!--
var c = 0;
document.write("Loop begins…");
do{
document.write("Value of c: " + c + "<br />");
c++;
} while (c < 5)
document.write("Loop Terminates!");
//-->
</script>
<p>Change the values of the looping variable to see how things change</p>
</body>
</html>
The output of the code upon execution is shown in the image given below.
For Loop
The most commonly used looping construct is the ‘for’ loop. The for loop integrates the looping
variable initialization, condition checking and looping variable update in the for statement. The syntax
for implementation of while is given below –
for(init; expression; update){
//Statements of the for block
}
Here, init is the initialization statement and expression is the condition, which is to be tested. Lastly,
the update is the expression that updates the looping variable. Sample implementation of the while
loop is given below –
<html>
<body>
<script type="text/javascript">
<!--
var c;
document.write("Loop begins…");
for(c=0; c<5; c++){
document.write("Value of c: " + c + "<br />");
}
document.write("Loop Terminates!");
//-->
</script>
<p>Change the values of the looping variable to see how things change</p>
</body>
</html>
The output of the code upon execution is shown in the image given below.
For…In Loop
This loop is typically used with objects. The loop uses a variable of the object and loops through
until the value of the property associated with the object variable is exhausted. In other words, this
loop works around object properties. The syntax for the implementation of the for…in loop is as
follows –
for (variable in object){
//Statements inside the for…in loop block
}
Sample implementation to demonstrate the working of the for…in loop is given below.
<html>
<body>
<script type="text/javascript">
<!--
var demoObject;
document.write("Properties of the Object: <br /> ");
for (demoObject in navigation) {
document.write(demoObject);
document.write("<br />");
}
document.write ("Loop Terminated!");
//-->
</script>
<p>Change the object to see how the result changes</p>
</body>
</html>
Break Statement
Whenever this keyword is encountered in a JavaScript code, the loop immediately terminates and
execution is shifted to the statement that comes right after the closing bracket of the loop. In order to
understand the working of break statement, let us take an example,
<html>
<body>
<script type="text/javascript">
<!--
var a = 5;
document.write("Loop Begins…<br /> ");
while (a < 30) {
if (a == 5){
break;
}
a = a + 1;
document.write( a + "<br />");
}
document.write("Loop terminates!<br /> ");
//-->
</script>
<p>Change the value of a to see how the loop execution is modified</p>
</body>
</html>
The output of the code is shown in the image given below.
Continue Statement
When this statement is encountered in a loop, the rest of the loop statements are ignored and the
control is shifted to the next iteration of the loop. With that said, it is important to understand that the
next iteration is execution only if the loop condition is found true. In case, the loop expression is
found false, loop execution is terminated.
The sample code given below demonstrates the use of continue statement.
<html>
<body>
<script type="text/javascript">
<!--
var a = 0;
document.write("Loop begins<br /> ");
while (a < 9){
a = a + 1;
if (a == 4){
continue; // skip rest of the loop body
}
document.write( a + "<br />");
}
document.write("Loop terminates!<br /> ");
//-->
</script>
<p>Change the value of a to see how the result changes!</p>
</body>
</html>
The output generated after execution of this code is illustrated in the image shown below.
Labels for Controlling Loop Flow
While the break and continue statements can redirect flow of control around the boundaries of the
loop construct, they cannot be used to transfer control to precise statements. This is made possible in
JavaScript with the use of labels. A label is simply an identifier followed by colon, which is placed
before the statement or code block. The following code demonstrates the use of labels.
<html>
<body>
<script type="text/javascript">
<!--
document.write("Loop begins!<br /> ");
loop1: for (var i = 0; i < 3; i++) {
document.write("Loop1: " + i + "<br />");
loop2: for (var j = 0; j < 3; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break loop1; // Do the same thing
if (i == 4) break loop2; // Quit the outer loop
document.write("Loop2: " + j + " <br />");
}
}
document.write("Loop terminates!<br /> ");
//-->
</script>
</body>
</html>
The output of the code has been illustrated in the image given below.
Chapter 9: Functions
In order to allow programmers to reuse existing code for commonly implemented functionality, the
concept of functions was introduced. There are three main advantages of breaking down any code into
functions. Firstly, it makes the code modular and manageable. This is a major point of advantage for
programs that are very large.
Secondly, code can now be reused and you don’t have to program functionalities that are already
available in the library or that you have already coded for another section of the program. Lastly, it
helps programmers to manage software development projects as independent functions can be given
to different programmers for coding.
Functions are an integral part of all programming languages and JavaScript is no exception to this
rule. You have already witnessed the use of functions like alert() in the code that we have written in
some of the previous chapters. While these are inbuilt functions, you can easily write you own
functions in JavaScript.
Defining a Function
You cannot use something that doesn’t exist. In line with this thought, you need to write the function
definition before you can use it in any of your main programs. In order to declare a function, you need
to use the function keyword. They keyword must be followed by a variable name that you intend to
use for the function.
Besides this, the function statement will also have a list of parameters inside brackets. This may be
empty if your function is not using any function parameters. Lastly, there will be a curly brace to
define the block of scope for the function. Inside this block, the actual implementation of the function
shall be written. The syntax for implementing a function in JavaScript is as follows –
<script type="text/javascript">
<!--
function demoFunc(list_of_parameters)
{
//Implementation of the function
}
//-->
</script>
Here is a sample function implementation to help you understand how it is done.
<script type="text/javascript">
<!--
function printHW() {
alert("Hello World!");
}
//-->
</script>
Calling a Function
You just have to write the name of the function along with the parameter list inside the brackets to call
a function. The sample code given below shows how a function is typically called.
<html>
<head>
<script type="text/javascript">
function printHW(){
document.write ("Hello World!");
}
</script>
</head>
<body>
<p>Click the button to invoke the function for printing Hello World!</p>
<form>
<input type="button" onclick="printHW()" value="Print Hello World">
</form>
</body>
</html>
The code invokes the function when the user clicks on the button created, as part of the HTML form.
The output generated on the execution of the code is given below –
If you click on the button, the following output is generated.
Void Keyword
The void keyword is usually used before a single operand and indicates that the expression upon
evaluation will not return any value. It is typically used with functions to indicate that the function is
not returning any value. The syntax for the usage of void keyword is given below –
<head>
<script type="text/javascript">
<!--
void func()
//-->
</script>
</head>
One of the commonest examples of the use of the oid keyword is as part of the client-side javascript
URL. It allows the developer to evaluate an expression without the overhead of the expression
returning a value and the browser displaying anything about it. The sample code shown below
evaluates the expression alert (“Warning!”), but it is not returned and displayed on the page.
<html>
<head>
<script type="text/javascript">
<!-- //-->
</script>
</head>
<body>
<p>Click! Demo for Void Keyword…</p>
<a href="javascript:void(alert('Warning!'))">Click!</a>
</body>
</html>
The output for the code is illustrated in the image shown below.
When you click on Click!, a dialog box for warning pops up.
Chapter 10: Events
Handling of the interaction between JavaScript and HTML when the user of browser manipulates a
page is done via events. Examples of events include loading of the page, clicking of the button and
closing of the window, in addition to several others. In fact, when the user presses any key while the
browser is open, it is also categorized as an event.
These events can be trapped and accordingly responded with the help of JavaScript code. For
example, the clicking of a button at close a window and hovering over some text may display a
message. This functionality of JavaScript allows the developers to code infinite responses to user
input and result in making the pages more dynamic.
Document Object Model (DOM) Level 3 includes events and a set of events is associated with every
HTML elements. These events can trigger the execution of a JavaScript code.
Attribute Description
The server and web browsers need to communicate with each other to perform operations and
resolve queries. The protocol used for this communication is the HTTP protocol, which is a stateless
protocol. However, in case of commercial websites, there is a need for the website to maintain user
session information across webpages.
A user may have entered the website, visited several pages and then left the website. The information
of when the user entered and the pages he or she visited before leaving is the session information that
the website needs to keep a track of. The most common method for tracking purchases, preferences,
commissions and site statistics is using cookies.
Storing Cookies
The string value can be assigned to document.cookie object to create a cookie. Sample
implementation is given below –
document.cookie = "key1=val1;key2=val2;expires=currdate";
It is important to note here that the ‘expires’ attribute of the document.cookie object is optional. If you
set the attribute with specific data and time, then the cookie will not be accessible beyond the
specified parameter.
The use of semicolons, whitespaces and commas are not allowed in cookie values. In case, you need
to use these characters, you must encode their values using the escape () function before storing them
in the cookie. Correspondingly, when you wish to read the cookie value, you will have to decode the
encoded values using unescape () function.
Sample code for storing values in cookies is given below.
<html>
<head>
<script type = "text/javascript">
<!--
function StoreCookie() {
if( document.form1.customer.value == "" ){
alert("Mandatory Field. Enter value!");
return;
}
cookievalue=escape(document.form1.cust.value)+";";
document.cookie="Name of Cookie = " + cookievalue;
document.write ("Storing Cookie : " + " Name of Cookie =" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="form1" action="">
Enter name: <input type="text" name="cust"/>
<input type="button" value="Store Cookie" onclick="StoreCookie();"/>
</form>
</body>
</html>
When this code is executed, you will have a cookie named ‘name’ on your computer. You can set
multiple cookies in the form of key-value pairs. Note that these pairs must be separated with commas.
Reading Cookies
Just like you saw in the previous section, document.cookie contains the list of key-value pairs, which
are separated by semicolons. We access this object to store cookies. Likewise, we access this object
to read cookies as well. If you have multiple cookies stored on your system, you will have to tokenize
the string to get individual cookies. For this, javaScript provides the split () function. Sample
implementation for this concept is given below.
<html>
<head>
<script type="text/javascript">
<!--
function demoReadCookie() {
var valcookies = document.cookie;
document.write ("Cookies : " + valcookies );
arrcookie = valcookies.split(';');
for(var i=0; i<arrcookie.length; i++){
cname = arrcookie [i].split('=')[0];
cvalue = arrcookie [i].split('=')[1];
document.write ("Key: " + cname + "; Value: " + cvalue);
}
}
//-->
</script>
</head>
<body>
<form name="form1" action="">
<p>Click the button!</p>
<input type="button" value="Read Cookie" onclick="demoReadCookie()"/>
</form>
</body>
</html>
The sample code also makes use of the Arrays object. Length is a method of the Array class that
returns the number of elements in the array concerned. Besides this, there may be some cookies set on
your system that you may not know about. The piece of code given above will display all the cookies
set on the system.
If you enter the value emp in the name field of the tab, the following output will appear.
How to Delete a Cookie
There may be situations where you may want to delete a cookie. This will invalidate any future
attempts to access the cookie. In order to delete a cookie, you can simply assign the ‘expires’ attribute
of the document.cookie class a value of the past or any date and time value that has already passed.
The sample code given below demonstrates this concept.
<html>
<head>
<script type="text/javascript">
<!--
function demoWriteCookie() {
var datenow = new Date();
datenow.setMonth(datenow.getMonth() - 1 );
cookieval = escape(document.form1.cust.value) + ";"
document.cookie="name=" + cookieval;
document.cookie = "expires=" + datenow.toUTCString() + ";"
document.write("Storing Cookie : " + "name=" + cookieval );
}
//-->
</script>
</head>
<body>
<form name="form1" action="">
Enter name: <input type="text" name="cust"/>
<input type="button" value="Store Cookie" onclick="demoWriteCookie()"/>
</form>
</body>
</html>
Chapter 12: Page Redirection
You may have witnessed situations where you typed the address of a webpage in the address and
internally you were redirected to another webpage. This concept is known as page redirection. Page
redirection may be implemented due to several reasons. A few of these reasons have been described
below.
The developer of the website moved his or her website to a new domain name. So, he or she
has implemented page redirection to direct all the traffic on the old domain name to the new
domain name. All that needs to be done at the developer’s end is to create a single
redirection page on the old website.
Different browsers support different technologies and websites are created to work on
different browsers. As a result, different versions of the same webpage have to be created.
This is also the case when a website is targeting audiences from different countries and have
a page version setup for each of these countries. In all these scenarios, page redirection may
be required to direct the user to the version of the webpage that is deemed best for it.
The website owner may have changed the name of the website or may have bought a new
domain for the website. However, the old website name is already indexed with search
engines. If the old domain name is brought down, the website owner will lose business as the
users will see no page corresponding to the web search result. To avoid the problems
associated with such a situation, page redirection is implemented.
Dialog boxes are an important tool for user interaction and are typically used in situation where you
want to raise a warning or get a specific input from the user. JavaScript supports three types of dialog
boxes, which have been discussed below.
You must have seen the print button on webpages that allow you to take a printout of the webpage.
This is typically used for forms where the user would want to keep a copy of the form that he or she
has filled. This functionality can be implemented using the print function of the JavaScript’s window
object.
The function window.print() available in JavaScript prints the webpage as and when it is invoked. It
is usually called using the onclick event. Sample implementation of the printing functionality can be
seen in the code given below.
<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print Page" onclick="window.print()" />
</form>
</body>
<html>
Although, this functionality is supported in JavaScript, it is usually not recommended, as the print is
most often not printer friendly. A page with just text, images and advertisements is considered a
printer-friendly page. The page can be made printer-friendly by adopting the following practices.
Create another copy of the page that contains only text and images.
Use comments lik e ← Printing Starts Here-> and <- Printing Ends Here -> to make clear
demarcation of what you require in the page.
Finally, you can also use the inbuilt browser functionality for page printing, if need be.
Conclusion
Now that we have introduced you to all the basic concepts of JavaScript programming, you are all set
to begin. We recommend you to execute the examples given in this book to see how JavaScript
programming works. Also, work around with the code by changing parameters and values to see how
it impacts the result.
Besides this, try out some examples of your own. Practice is what is going to teach you programming
in real. No number of books can impart you with the skill to program unless you program yourself.
Formulate problem statements and write code for it. Make mistakes, learn from them and then, make
some new mistakes. This is the true world of programming.
We hope this book helped you gain background and foreground in your strive to learn JavaScript
programming. Any feedback or recommendations on how to make this book better are welcome.
SQL
Introduction
Structured Query Language or SQL is a programming language that is designed for managing and
retrieving data present in relational databases. This book is a beginner’s tutorial to SQL and how it
works. Moreover, this book shall also help you program or write queries in SQL for database
management.
This book is a guide for beginners and does not require any prior knowledge about the language. We
shall introduce all the concepts that you require for understanding SQL in this book. However, little
understanding of programming concepts and fundamentals will be helpful in creating the right
foundation for able learning.
Evidently, you cannot learn a programming language for databases unless you know what a database,
particularly RDBMS. We shall introduce you to the basics of these concepts in the book. However,
you may read about them before you start learning SQL.
Ideally, you must execute SQL queries on Oracle 11g RDBMS. However, you may not have the setup
or the resources to set the system up for execution. In such a case, you can look at the various online
platforms available for the same. One such platform is Coding Ground, which is free and available
for everyone to use.
As you embark on this journey to learn SQL, you must understand that the secret to becoming an
expert on any programming language is practice. The more you practice, the better you will become!
Practice hard; remember the fundamentals and focus on innovation!
As mentioned previously, SQL is a programming language that is used for managing and operating
databases. Some of the common operations that can be performed using SQL include creating and
deleting rows, in addition to retrieving and modifying data that is available in the rows of the
RDBMS. Although, there are several versions of SQL available, it is an ANSI standard language.
What is SQL?
Structured Query Language or SQL is a computer programming language that is typically used for
storage, retrieval and manipulation of data that is stored in the relational database. This is the
standard computer programming language used for RDBMSs (Relational Database Management
Systems) like Oracle, MySQL and MS Access, in addition to many others. With that said, the version
used by each of these systems may vary. For instance, Oracle uses PL/SQL and MS SQL Server
makes use of T-SQL.
IBM’s Ted Cod, who is popularly known as the father of relational databases, gave the concept of
relational model for databases in 1970 and that is when it all began. It was four years later in 1974
that SQL appeared. This was just an idea, which got conceptualized in the form of System/R in 1978
and was released by IBM. The ANSI standard and first prototype of relational databases was
released in 1986, which is popularly known as Oracle. IBM is credited for this release too.
Why SQL?
SQL has many advantages, which makes it a standard and popular programming language for
databases. These advantages include –
SQL programming language can be used for accessing data in RDBMSs.
It can also be used for describing data.
Definition of data and its manipulation are also activities that SQL support.
SQL can be used with other programming languages by embedding SQL modules into other
languages’ code, pre-compilers and libraries.
It is possible to create and drop databases using this programming language.
It can be used for setting permissions on views, tables and procedures.
Lastly, it can be used for creating views, procedures and functions.
The Process
Whenever you give a command to the system, the SQL process starts. The system determines the best
way to perform the task, which is interpreted by the SQL engine. The different components involved
in the process are as follows –
Optimization Engines
SQL Query Engine
Classic Query Engine
Query Dispatcher
The SQL Query engine is earmarked for handling SQL queries and does not manage logical files. The
classic query engine handles these files and non-SQL queries. The SQL Architecture is illustrated in
the image shown below.
Commands
Some of the basic SQL Commands that you will use and encounter during interactions with relational
databases have been listed below. They will be explained in detail, later in the book. Typically,
commands in SQL are categorized into three categorized namely DDL (Data Definition Language),
DML (Data Manipulation Language) and DCL (Data Control Language). The commands that are
classified under DDL category are as follows –
CREATE
This command is used for creating an object, table or view.
ALTER
This command is typically used for modifying an existing database object. In most cases, this object
is a table.
DROP
The objects, tables and views created using CREATE can be deleted or removed using the DROP
command.
The next set of commands is commands that fall under the category of DML or Data Manipulation
Language. These commands are as follows –
SELECT
This command is used for retrieving a set of records from one or more than one tables.
DELETE
This command is used for deleting records.
UPDATE
This command is used for modifying or updating records.
INSERT
This command is used for inserting records.
The last category of commands falls under DCL or data control language. These commands are as
follows –
GRANT
Users can be granted privileges using the GRANT command.
REVOKE
The privileges given to users can be taken back using the REVOKE command.
Chapter 2: Introduction to RDBMS
RDBMS is a popular acronym for Relational Database Management Systems. SQL, including other
database systems like MySQL, DB2 and Oracle, are based on the fundamentals of RDBMS. As we
know, Codd gave the first iconic model in the field of databases in the form of relational model.
RDBMS is a database management system, which is based on this model.
This chapter shall introduce you to the basic concepts of RDBMS and build a foundation to facilitate
learning of SQL. We shall introduce you to all the fundamentals that you need to understand before
you can try your hands at SQL and program in it.
Table
Tables are objects that are used by RDBMSs to hold data. Typically, a table is a collection of rows
and columns that contain data entries. This is the simplest form of data storage. An example of how
tables look like is shown below. This table has employees’ data for a company. The fields of data
included consist of ID number, name, gender and salary.
ID Number Name Gender Salary
20156 James Male 1200
20157 Andy Female 1250
20158 Rebecca Female 575
20159 Andrew Male 1100
Fields
Every column of the table represents a field, which is a piece of information that is held for the
record, which corresponds to every row of the table. In other words, every row is a record and every
column is information stored for the record. A number of columns or fields form a record. In the
example given above, ID number, name, gender and salary are fields.
Record
Every row or field values form one record. The employees’ data table given above has four records.
Evidently, the number of records is equal to the number of rows. Therefore, every row corresponds to
one record in the table. Example of a record is shown below –
20156 James Male 1200
To summarize the concept, every horizontal entry in a table is called a record while every vertical
entry in the table contains data for the field specified corresponding to all the records in the table.
The table entries given below represent the vertical entries corresponding to the field ‘Name’.
Name
James
Andy
Rebecca
Andrew
Null Value
Any value for a field, if left blank, indicates a NULL value. It indicates that the field’s value for the
record concerned does not exist or has no value. It is important to understand that a NULL value is not
the same as zero value or a value with all white spaces. It is a value that has been left blank during
the process of creation of data.
Constraints in SQL
Sometimes, rules are enforced on the columns of the table that contain data specific for the field for
all the records in the table. These rules are referred to as constraints, which are generally used to
ensure that a field only gets a particular type of value. For instance, if there is a field called age in the
table, then this field can only take numeric values. This is a constraint that can be set on the field
‘age’. Setting up such constraints improves the reliability and accuracy of data stored in the table.
Until now, we have only spoken about constraints that impose limits on fields. We can also set up
constraints for the whole table. As is obvious, the constraints set up for the table apply to all the data
stored in the table. Some of the constraints commonly available and used in SQL include –
NOT NULL
Whenever set, this constraint ensures that the field value is never set to NULL.
DEFAULT
This constraint is typically used to fill in a default value for any field value that is left blank.
UNIQUE
If this constraint is set on a column, then all the values set for this field will have to be unique.
PRIMARY Key
When this constraint is set for a column, it indicates that the field is the primary key or the field value
is a unique identifier for every record existent in the table.
FOREIGN Key
When this constraint is set for a column, it indicates that the field is the foreign key or the field value
is a unique identifier for every record existent in another table.
CHECK
As the name suggests, this constraint checks if the values for a field satisfy pre-defined conditions.
INDEX
This constraint indicates that the column can be used as an index, which shall be used for faster data
retrieval from the table.
Data Integrity
Data integrity is the measure of the accuracy and consistency of data stored in the database. With each
database, the categories of data integrity existent are as follows –
Entity Integrity
This category of integrity refers to the accuracy and consistent of each entity in the database, which is
each record. Therefore, every record must be unique and no duplicates of any of the records must be
there.
Domain Integrity
This category of integrity ensures that every field gets valid entries by imposing restrictions on the
type, format and range of values that a field can hold.
Referential Integrity
In databases, many times, other tables use the rows of one table. The deletion of these records can
affect the tables that were using these records. In order to avoid such a problem, this category of data
integrity exists. According to this category of data integrity, records or rows that are being used by
other table in the database cannot be deleted.
User-defined Integrity
Any rules that the user wishes to impose on columns and that are not covered in the other data
integrity categories form a part of user-defined integrity category.
Normalization
In order to facilitate database operations, it is prerequisite to have the data arranged in the most
efficient manner. The process of organizing data efficiently in the database is called database
normalization, which serves two purposes –
It helps in managing the problem of data redundancy and ensures that the same data in not
stored in more than one table.
It also helps in maintaining consistency in data dependencies.
As a result, data is stored logically and takes lesser space than otherwise, improving the efficiency of
data storage. Besides this, the logical storage of data ensures that data makes more sense. In simple
words, normalization is a guideline that helps in creating a effective and efficient database structure.
Normal forms are format for database structuring and as part of the normalization guidelines, several
normal forms are defined. The database structure needs to be organized in such a manner that it first
complies with the first normal form rules, then the second and finally, the third normal form rules.
Although, a database structure that is normalized upto the third normal form is considered good, you
can take it further to fourth and fifth normal form as well. This discussion aims to give you an idea
about normalization and why it is done. Normalization using the different normal forms is beyond the
scope of this book.
Chapter 3: Knowing Databases
Now that you are thorough with RDBMS concepts, let us look at the relational database management
systems available in the market. This chapter shall give you an introduction to the different RDBMSs
and the features each of them include.
MySQL
The open source SQL database is MySQL. It supports different platforms like Unix, Linux, Mac OSX
and Microsoft Windows. Although, the core version of My SQL is free, you may have to pay for some
of the premium features. Moreover, MySQL comes coupled with a SQL database server, which is
fast, robust and multi-threaded in nature.
MySQL’s development started in the year 1994 and scientists David Axmark and Michael Widenius
are credited for the first internal release of the DBMS in 1995. The windows version of the DBMS
came much later in 1998. Initialy, the MySQL project was owned by MySQL AB. The ownership of
the project changed to Sun Microsystems in the year 2008, after which the version 5.1 of MySQL was
released. Key features of this database management system include –
Flexibility
High Availability
Scalability
High Performance
Web Strength
Robust Transactional Support
Data Warehouse Strength
Comprehensive Application Development
Strong Data Protection
Open Source Freedom
Management Ease
Lowest Total Cost of Ownership
24 x 7 Support
MS SQL Server
Microsoft came up with their own relational database management system in the form of MS SQL
Server, which works on ANSI SQL and T-SQL, as its primary query languages. Sybase released the
first version of this DBMS in the year 1987. Sybase collaborated with Aston-Tate and Microsoft for
porting SQL Server to OS/2 and released SQL Server 1.0 in 1989, after which Aston-Tate dropped
out of SQL development and Microsoft released SQL Server 2000. Key features of MS SQL Server
include –
High Availability
Database snapshots
High Performance
Database mirroring
Service Broker
CLR integration
Ranking functions
DDL triggers
XML integration
Isolation levels based on row version
Database Mail
TRY...CATCH
Oracle
Oracle is one of the most popular and largest multi-user DBMSs available in the market today. As the
name suggests, Oracle is owned and created by ‘Oracle Corporation’. The key feature of Oracle is
that it efficiently manage its resources, which in entirety is that database that is accessed by many
clients over the network.
Considering the fundamental architecture of Oracle, it is deemed best for client-server computing.
Moreover, it supports many platforms like Unix, Windows, Linux and Mac OSX. The journey of
oracle began way back in 1977 when Ed Oats, Bob Miner and Larry Ellison founded ‘Software
Development Laboratory’. Oracle became the first commercial SQL database management system
when its Version 2.0 was released in the year 1979.
It was in the same year that the name of the company was changed to Relational Software Inc. (RSI).
Owing to the fact that most of the development work undertaken by this company was related to
Oracle, its name again changed in 1982 and it got its current identity of Oracle Corporation.
It was in the subsequent years that Oracle got its multi-faceted features. For instance, the cross-
platform version of Oracle or Oracle Version 3.0 was released in 1983 while features like
concurrency control were added in versions 4.0 and 5.0. Key features of Oracle include –
Read Consistency
Concurrency
Quiesce Database
Locking Mechanisms
Self-managing database
Portability
ASM
SQL*Plus
Resource Manager
Scheduler
Materialized views
Data Warehousing
Table compression
Bitmap indexes
Analytic SQL
Parallel Execution
Partitioning
Data mining
MS Access
MS Access is a basic database management system from Microsoft and is used at the entry-level,
which makes it also one of the most popular Microsoft products ever. Other reasons for its popularity
include its inexpensiveness and ability to create powerful solutions for small projects. Besides this,
Microsoft’s flagship feature of highly intuitive and easy-to-use graphical interfaces also adds to the
reputation of the product.
It is important to mention here that MS Access makes use of Jet-SQL, which is a variant of SQL. This
dialect of SQL is specifically used by the Jet database engine, which is used by MS Access for
database operations. The first version of MS Access was released in 1992 and it has seen
innumerable improvements and additions over the years. Presently, MS Access is available as part of
the MS Office product by Microsoft. Key features of this database management system include –
MS Access allows users to create forms, reports, table and queries. Moreover, the user can
connect all these tools with the help of macros.
Data can be imported from and exported to different formats that include Oracle, ODBC,
Outlook and Excel, in addition to several others.
MS Access support a special format called the Jet database Format or MDB. This format
allows the storage of the application and its data in the same file. This file can be used to
transfer the complete application even if the user is in a disconnected environment.
There is support for parameterized queries, which can be referenced by .NET or VB6
programs via ADO or DAO.
MS Access can also be interfaced with MS SQL Server’s desktop version, which can be
used as an alternative to the existing database engine of this DBMS.
It is important to understand that MS Access is not a client-server DBMS and thus, it does
not implement stored procedures, transaction logging or database triggers. It is in fact a file
server-based database.
Chapter 4: Syntax
A guidelines and rules that have to be followed in order to make the programming language
understandable for its compiler or interpreter are referred to as Syntax. This chapter shall introduce
you to the SQL syntax to enable you to move ahead with the book with ease.
To start with, as a rule, every SQL statement must start with a keyword. Keywords are words that are
reserved for use by the SQL programming language. Some examples of this include SELECT,
CREATE, INSERT, DELETE and ALTER. Besides this, it if important for you to remember that every
SQL statement must terminate with a semicolon (;).
Another important point that you must comprehend before we get down to writing SQL statements is
that SQL is case insensitive. So, whether you write SELECT or select, SQL will know that you mean
SELECT. However, when you are working with MySQL, ensure that the table names are exactly as
they are mentioned in terms of case because MySQL is case insensitive.
This chapter gives the syntax of all the basic SQL commands. Using these commands and how they
can be implemented on real-world scenarios shall be covered in the later chapters.
In all the syntax rules given below, col stands for column, t_name stands for table name, col_name
stands for column name, v stands for value, i_name stands for index name, db_name stands for
database name and cond stands for condition.
SELECT Statement
SELECT col1, col2....colN FROM t_name;
SQL WHERE Clause
SELECT col1, col2....colN FROM t_name WHERE cond;
DISTINCT Clause
SELECT DISTINCT col1, col2....colN FROM t_name;
AND/OR Clause
SELECT col1, col2....colN FROM t_name WHERE cond1 {AND|OR} cond2;
BETWEEN Clause
SELECT col1, col2....colN FROM t_name WHERE col_name BETWEEN v1 AND v2;
IN Clause
SELECT col1, col2....colN FROM t_name WHERE col_name IN (v1, v2,...vN);
ORDER BY Clause
SELECT col1, col2....colN FROM t_name WHERE cond ORDER BY col_name {ASC|DESC};
LIKE Clause
SELECT col1, col2....colN FROM t_name WHERE col_name LIKE { PATTERN };
COUNT Clause
SELECT COUNT(col_name) FROM t_name WHERE cond;
GROUP BY Clause
SELECT SUM(col_name) FROM t_name WHERE cond GROUP BY col_name;
HAVING Clause
SELECT SUM(col_name) FROM t_name WHERE cond GROUP BY col_name HAVING (arithematic
condition);
CREATE TABLE Statement
CREATE TABLE t_name( col1 data_type, col2 data_type, col3 data_type, ..... colN data_type,
PRIMARY KEY( col names ) );
CREATE INDEX Statement
CREATE UNIQUE INDEX i_name ON t_name ( col1, col2,...colN);
DROP TABLE Statement
DROP TABLE t_name;
SQL DROP INDEX Statement
ALTER TABLE t_name DROP INDEX i_name;
SQL TRUNCATE TABLE Statement
TRUNCATE TABLE t_name;
SQL DESC Statement
DESC t_name;
SQL ALTER TABLE Statement (Rename)
ALTER TABLE t_name RENAME TO new_t_name;
SQL ALTER TABLE Statement
ALTER TABLE t_name{ADD|DROP|MODIFY} col_name {data_type};
SQL INSERT INTO Statement
INSERT INTO t_name( col1, col2....colN) VALUES ( v1, v2....vN);
SQL DELETE Statement
DELETE FROM t_name WHERE {cond};
SQL UPDATE Statement
UPDATE t_name SET col1 = v1, col2 = v2....colN=vN [ WHERE cond ];
SQL CREATE DATABASE Statement
CREATE DATABASE db_name;
SQL USE Statement
USE db_name;
SQL DROP DATABASE Statement
DROP DATABASE db_name;
Any object specified in SQL needs to have a data type, which is a declaration of the type of data that
the object is allowed to hold. The objects in SQL for which data type needs to be specified include
expressions, variables and columns. While creating tables, you can specify the data type of columns
that are included in the same on the basis of your requirements.
There are six categories of data types available in SQL, which have been discussed below –
Exact Numeric
These data types are used to declare objects that can hold numeric values that are exact in nature. The
different data types that are part of this category include –
bigint
smallint
int
tinyint
bit
numeric
decimal
smallmoney
money
Approximate Numeric
These data types are used to declare objects that can hold numeric values that are approximate in
nature. The different data types that are part of this category include –
real
float
Character Strings
These data types are used to declare objects that can hold character strings. The different data types
that are part of this category include –
varchar
char
text
varchar(max)
Binary
These data types are used to declare objects that can hold binary values The different data types that
are part of this category include –
image
binary
varbinary
varbinary(max)
timestamp
This data type is used to declare a variable that will hold the timestamp corresponding to a row. So,
as and when the row will get updated, the timestamp value will be automatically revised.
sql_variant
this data type can be used to store values corresponding to most SQL-supported data types like
timestamp, text and ntext.
cursor
This data type is used to declare a reference to the cursor object.
xml
This data type is used to declare a variable that can store XML data. This type of data can be stored
in a variable or column of the table.
uniqueidentifier
This data type is used to declare a globally unique identifier (also known as GUID).
table
This data type is used to declare an object that shall hold the result set, which can later be used for
further processing.
Chapter 6: Operators
Operators are keywords or reserved characters that are used to specify the condition in the WHERE
clause of SQL statements. This condition may require arithmetic operators like addition (+) or
relational operators for comparison like inequality (!=). Besides this, operators may also be used as
conjunctions to specify multiple conditions in a SQL statement. SQL operators are divided into three
classes, each of which has been individually discussed in this chapter.
Arithmetic Operators
Operators that are used for performing arithmetic operations are referred to as arithmetic operators.
The list of arithmetic operators supported by SQL is as follows –
Addition (+)
This operator adds the values of the two operands. If there are two variables a and b with values 10
and 5, then a+b gives 15.
Subtraction (-)
This operator subtracts the values of the two operands. If there are two variables a and b with values
10 and 5, then a-b gives 5.
Multiplication (*)
This operator multiplies the values of the two operands. If there are two variables a and b with
values 10 and 5, then a*b gives 50.
Division (/)
This operator divides the values of the first operand with that of the second operand. If there are two
variables a and b with values 10 and 5, then a/b gives 2.
Modulus (%)
This operator returns the remainder of the division operation between the two operands. If there are
two variables a and b with values 10 and 5, then a%b gives 0.
Comparison Operators
Operators that are used for performing comparative operations are referred to as comparison
operators. The list of comparison operators supported by SQL is as follows –
Equal (==)
This operator compares the value of the two operators and if the values are equal, it returns true else
it returns false. For example, if we have two variables a and b with the values 10 and 5, a==b will
give false.
Not Equal (!= and <>)
This operator compares the value of the two operators and if the values are equal, it returns false else
it returns true. For example, if we have two variables a and b with the values 10 and 5, a!=b and
a<>b will give true.
Greater Than (>)
This operator compares the value of the two operators and if the value of the first operand is greater
than that of the second operand, it returns true else it returns false. For example, if we have two
variables a and b with the values 10 and 5, a>b will give true.
Less Than (<)
This operator compares the value of the two operators and if the value of the first operand is less than
that of the second operand, it returns true else it returns false. For example, if we have two variables
a and b with the values 10 and 5, a<b will give false.
Greater Than Or Equal To (>=)
This operator compares the value of the two operators and if the value of the first operand is greater
than or equal to that of the second operand, it returns true else it returns false. For example, if we
have two variables a and b with the values 10 and 5, a>=b will give true.
Less Than Or Equal To (<=)
This operator compares the value of the two operators and if the value of the first operand is less than
that of the second operand, it returns true else it returns false. For example, if we have two variables
a and b with the values 10 and 5, a<=b will give false.
Not Less Than (!<)
This operator compares the value of the two operators and if the first value is not less than or greater
than the second value, it returns true else it returns false. For example, if we have two variables a and
b with the values 10 and 5, a!<b will give true.
Not Greater Than (!>)
This operator compares the value of the two operators and if the first value is not greater than or
lesser than the second value, it returns true else it returns false. For example, if we have two
variables a and b with the values 10 and 5, a!<b will give false.
Logical Operators
Operators that are used for performing logical operations are referred to as logical operators. The list
of logical operators supported by SQL is as follows –
ALL
This operator can be used to make a comparison between a given value and all the values that exist in
another set of values.
ANY
This operator is used to compare a specified value with any value that is deemed applicable for
comparison in a set of values.
BETWEEN
This operator is used to specify a range of values and is typically used to make searches for values
that lie within this range.
AND
This operator is used to define more than one conditions in the WHERE clause. If all the conditions
are true, then the SQL statement is accordingly executed.
OR
This operator is used to define more than one conditions in the WHERE clause. If one of the
conditions is true, then the SQL statement is accordingly executed.
EXISTS
If there is a table and you wish to know if a particular record exists in the table, then this operator can
be used for this purpose.
LIKE
This operator is typically used with Wildcard operators to search for values that share similarities
with the specified value.
IN
If there is a value and there is a need to compare this value with a list of literal values, then the IN
operator can be used for this purpose.
NOT
This is the negation operator and is typically used along with other operators. For instance, if we use
the operator combination NOT BETWEEN, then the search will look for values that do not lie in the
given range.
UNIQUE
This operator returns unique rows in the specified table and is typically used for removing duplicates.
IS NULL
This operator is used to compare a specific value with NULL to test its existence.
Chapter 7: Expressions
When operators, functions and values are used together in such a manner that the same can be
evaluated to compute a value, this combination is referred to as an expression. You can visualize SQL
expression as a mathematical formula that is written using the SQL syntax. In order to help you
understand how a typical SQL expression looks like, let us take an example.
SELECT col1, col2, colN FROM t_name WHERE [exp];
In the given example, the expression is performing a SELECT operation and requests selection of
columns 1 to N from the table ‘t_name’. The results corresponding to rows for which the given
expression evaluates to true must be outputted. SQL supports three types of expressions, each of
which has been discussed below.
Boolean Expressions
In case of boolean expressions, fetching of data is done after a single value is matched. The syntax for
such expressions is as follows –
SELECT col1, col2, colN FROM t_name WHERE exp_matching_single_value;
This statement selects columns 1 to N from the table ‘t_name’ and outputs the rows that satisfy the
condition specified by exp_matching_single_value. In order to gain better understanding of boolean
expressions, let us take an example. Consider a table named CUSTOMERS. The SQL statement given
below shall print all the records available in the CUSTOMERS table.
SELECT * FROM CUSTOMERS;
The output will typically look like –
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
98706 Shayla 22 12000.00
98718 Mathews 37 41000.00
The following SQL statement is the simplest example of a boolean expression.
SELECT * FROM CUSTOMERS WHERE Salary=37000;
The execution of this query will return the following.
ID Name Age Salary
98675 Amit 32 37000.00
Numeric Expression
Expressions that are of the numeric type are typically used to perform mathematical operations in a
SQL statement. Syntax for numeric expressions is as follows –
SELECT formula_arith as Op_Name [FROM t_name WHERE cond];
Here formula_arith is any mathematical formula that can be specified to perform an arithmetic
operation in the SQL query. Besides this, t_name is the name of the table and cond is the condition of
the WHERE clause. A simple example to demonstrate the working of numeric expressions is given
below –
SELECT (100+76) AS ADD;
Execution of this query shall give the result 176. Many other SQL functions like sum(), avg() and
count, in addition to many others, may be used as formula_arith to perform data calculations against
the values selected from the columns of the table concerned. For example, the SQL statement given
below shall count the number of entries in the CUSTOMERS table.
SELECT count(*) FROM CUSTOMERS;
Execution of this query will return the value 4.
Date Expressions
Such expressions are typically used to get information about the current date or time on the system.
Functions like GETDATE() or CURRENT_TIMESTAMP may be used in the SQL query to get the
desired results. Sample statements for their usage have been given below –
SELECT CURRENT_TIMESTAMP;
SELECT GETDATE();
Chapter 8: Working With Databases
The typical hierarchy of a relational database system starts with databases, which are further divided
into tables. Table is a collection of records or rows, which are formed by values assigned to columns
or fields. Evidently, the biggest element in this hierarchy is the database. This chapter shall help you
create and delete databases. Besides this, it shall also teach you how to inform the system that you
wish to use a specific database.
Create Database
In order to create databases in SQL, the CREATE DATABASE statement is used. The syntax for the
same is given below.
CREATE DATABASE db_name;
Here db_name is the name of database. A sample statement for this SQL statement is as follows –
CREATE DATABASE company;
However, before you decide to execute this SQL statement, be sure to check that you have admin
privileges. Upon creation, you can view the database entry in the list of databases in the system,
which can be viewed using the following SQL statement –
SHOW DATABASES;
Drop Database
You can remove a created database from the system using the DROP DATABASE statement. The
syntax for the same given below –
DROP DATABASE db_name;
Here, db_name is the name of the database you wish to delete from the system. Sample SQL statement
to demonstrate the working of this command can be seen below –
DROP DATABASE company;
A word of caution for you here is that be sure that you want to delete a database before you decide to
do it because deletion of the database will result in the deletion of all the data related to and
presiding inside the database. Moreover, you need admin privileges to perform this operation. Upon
exexution of this statement, you can check if you database has been deleted or not using the following
SQL statement.
SHOW DATABASES;
This SQL statement shall return the list of databases that are existing on the system. So, if the database
that you have just deleted is not listed here, then the operation has been successfully completed.
Select Database
The SQL Schema can contain n number of databases. Therefore, when you wish to see data that is
specific to a database, you will need to tell the system that you wish to work with the database
concerned for all your future queries. In order to inform the system about the database you wish to
access, the USE command is used. The syntax for the same is as follows –
USE db_name;
Here, db_name is the name of database that you wish to access. Be sure to specify a database name
that already exists in the system. Also, be sure to use unique names for databases on a SQL schema.
An example to demonstrate the working of this SQL statement is given below for your reference and
understanding.
Firstly, list the databases available on the system to ensure that you use the right name for the database
that you are wishing to access. In order to do this, the following SQL statement must be fired.
SHOW DATABASES
Assuming that a database named company exists on the system, then you can give the following SQL
statement to tell the system that it should use company named database for execution of all future
queries.
USE company;
Chapter 9: Working With Tables
The next elemental entity in SQL is a table. A table can simply be described as a collection of
records. It is typically divided into rows and columns. While columns represent fields, the collection
of values for these fields form a row or a record. This chapter introduces the operations that can be
performed on tables.
Create Table
The creation of a table involves giving a name to the table, in addition to defining columns and their
data types. In order to create a table, the CREATE TABLE SQL statement is used. The syntax for the
same is given below –
CREATE TABLE t_name(col1 data_type, col2 data_type, col3 data_type, .....colN data_type,
PRIMARY KEY(columns));
Here, col stands for column and data_type is the data type of the object concerned. One or more
columns can be specified as primary keys for the table. CREATE TABLE is the keyword that is used
to tell the system that you wish to create a table. The t_name stands for table name, which will
uniquely identify the table.
The list of columns that a table will include shall be specified within brackets that follow the table
name. The data type of each column is specified alonside the column name within the brackets. In
order to help you get a hang of how CREATE TABLE can be used for creating a table, the following
example has been provided.
CREATE TABLE CUST(ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT
NULL, SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
The SQL statement given above creates a table named CUST, which contains the data of customers.
The fields declared within this table is CUST_ID, CUST_NAME, CUST_AGE and CUST_SALARY.
The data type and constraint specific to the field is written beside it. For instance, CUST_ID is an
integer that cannot have the value NULL. Lastly, CUST_ID is declared as the primary key of the table,
which means that the field uniquely identifies each record of the table.
In order to see if the SQL statement has done the required processing for you, you can execute the
SQL command –
DESC CUST;
Drop Table
The other important operation that is performed on table is dropping or deleting a table. In order to
perform this operation, the DROP TABLE statement is used. Once executed, this statement removes
the indexes, data, constraints, permissions and triggers associated with the table. Therefore, this SQL
statement should be used very carefully as all the data related to the table will be lost. The syntax for
executing this SQL statement is given below.
DROP TABLE t_name;
Here, t_name is the name of the table. You must ensure that the name of the table exists in the database
before executing this statement. In the last example, we created a table named CUST. Let us see if the
table still exists in the database using the following SQL statement –
DESC CUST;
This shall give the details of the table, if it exists in the working database. In order to delete this
table, the following SQL statement must be executed.
DROP TABLE CUST;
Now, if you execute the SQL statement mentioned below, an error message that the table does not
exist will appear.
DESC CUST;
Alternatively, the following SQL may also be used for inserting records –
INSERT INTO CUST VALUES (98701, ‘Rohan’, 45, 50000.00);
INSERT INTO CUST VALUES (98675, ‘Amit’, 32, 37000.00);
INSERT INTO CUST VALUES (98706, ‘Shayla’, 22, 12000.00);
INSERT INTO CUST VALUES (98718, ‘Mathews’, 37, 41000.00);
One table can be used to populate anotheer table by using the SELECT statement. However, the table
used for populating the table concerned must have the required fields. The syntax for this operation is
given below –
INSERT INTO t1_name [(col1, col2, ... colN)] SELECT col1, col2, ...colN FROM t2_name
[WHERE cond];
On the other hand, if you wish to retrieve all the fields of table, then the following query can be given.
SELECT * FROM CUST;
The output for this query is as follows –
Where Clause
While the previous example shows how specific fields for records can be printed, this clause is used
to filter records from the table. A set of records from the total number of records can be chosen by
giving a condition as part of the WHERE clause. The WHERE clause can also be used on data
retrieved by joining two tables.
The records that satisfy the condition as part of the WHERE clause are returned upon execution of the
SQL statement. This clause is typically used for filtering records and choosing necessary records
from the set of records. Moreover, this clause can be used along with DELETE and UPDATE
statements. These SQL statements will be discussed later. The syntax for implementing this clause is
as follows –
SELECT col1, col2, colN FROM t_name WHERE [cond]
Here, col is the column and t_name is the name of the table. Besides this, cond is the condition, which
needs to be applied on the WHERE clause. Conditions applied for the WHERE clause can be
clubbed together using logical operators like OR/AND/NOT. The use of this clause is demonstrated
in the example given below. Consider the table named CUST given above. Let us select records of
customers whose salary is greater than 37000. For this, the query to be given as follows –
SELECT * FROM CUST WHERE SALARY > 37000;
The output of the query upon execution shall give the following output.
Let us select records of customers whose name is Amit. For this, the query to be given as follows –
SELECT * FROM CUST WHERE NAME = ‘Amit’;
The output of the query upon execution shall give the following output.
When working with strings, the character sequence must be given within inverted commas. On the
other hand, numerals are to be given without inverted commas.
Updating Records
The records already existent in the table can be altered using the UPDATE statement. If you need to
alter only a few records out of the total records, you can specify the condition using WHERE clause.
If you don’t specify with a condition along with the WHERE clause, all the rows will be modified.
The syntax for the implementation of the same is given below.
UPDATE t_name SET col1 = v1, col2 = v2...., colN = vN WHERE [cond];
Any number of conditions can be combined together using logical operators for filtering records. If
we take the example of the CUST table again, we can update the record corresponding to ID = 98675
by changing the field Salary = 55000, using the SQL statement shown below.
UPDATE CUST SET SALARY = 55000 WHERE ID = 98675;
The CUST table after the execution of this query will appear like this.
On the other hand, if you don’t give the WHERE clause, then all the records of the table shall be
updated. For instance, if we execute the query shown below –
UPDATE CUST SET SALARY = 1000.00;
The CUST table after the execution of this query will appear like this.
Deleting Records
In order to delete records that already exist in the table, the DELETE statement is used. Specific rows
can be deleted by specifying the WHERE clause, which filters the rows on the basis of the specified
condition. However, if you don’t use the WHERE clause, all the records in the specified table shall
be deleted. The syntax for implementation of the same is given below –
DELETE FROM t_name WHERE [cond];
Here, t_name is the name of the table and cond is the condition on the basis of which rows need to be
filtered. You can specify any number of conditions you want by using AND and OR conjunctive
operators. Assuming that the table from which a record needs to be deleted is named CUST and has
the following data –
ID Name Age Salary
98701 Rohan 45 1000.00
98675 Amit 32 1000.00
98706 Shayla 22 1000.00
98718 Mathews 37 1000.00
If you wish to delete all the records of the table CUST, the following query needs to be used –
DELETE FROM CUST;
However, it is important for you to understand that this shall only delete the records of the table and
the table will still continue to exist. So, you can add more records to the table by using the INSERT
INTO query.
Chapter 10: Conjunctive Operators
Conjunctive operator is a name given to operators that are used to combine two or more conditions in
a query. SQL supports two conjunctive operators named AND and OR. These operators enable the
developer to make multiple comparisons as part of the same query.
Now, if we wish to retrieve records of people who are under the age of 30 and have a salary greater
than 40000, the following query needs to be fired.
SELECT * FROM CUST WHERE SALARY > 40000 AND age < 30;
Upon execution, this query will generate the following result –
The OR Operator
The OR operator is used as part of the WHERE clause and is typically used when the developer
wishes to filter out records that satisfies both or one of the conditions specified with the OR operator.
The syntax for the implementation of OR conjunctive operator is as follows –
SELECT col1, col2, colN FROM t_name WHERE [cond1] OR [cond2]...OR [condN];
Here, col is the name of the column to be selected, t_name is the name of the table and cond is the
condition that needs to be tested for filteration of records. Any number of conditions can be jointly
tested using the OR operator. It is important to note that the records that are chosen need to fulfil both
or one of the conditions mentioned as part of the WHERE clause that is using the OR operator. In
order to understand how this concept can be implemented, let us take the example of a table named
CUST, which has the following records –
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
98706 Shayla 22 42000.00
98718 Mathews 37 12000.00
Now, if we wish to retrieve records of people who are under the age of 30 or have a salary greater
than 40000, the following query needs to be fired.
SELECT * FROM CUST WHERE SALARY > 40000 OR age < 30;
Upon execution, this query will generate the following result –
Chapter 11: LIKE Clause
The LIKE clause is used alongside wildcard operators for comparing values that are similar and may
or may not be exactly the same. The wildcard operators that are supported in SQL and can be used
with LIKE clause are the percent sign (%) and underscore (_).
While the former operator represents multiple characters, one or zero, the latter operator is used to
indicate a single character or number. It is allowed to use these operators in combination. The syntax
used for implementing the LIKE operator along with these wildcard operators is shown below –
SELECT FROM t_name WHERE col LIKE 'XXXX%'
or
SELECT FROM t_name WHERE col LIKE 'XXXX_'
or
SELECT FROM t_name WHERE col LIKE '%XXXX%'
or
SELECT FROM t_name WHERE col LIKE '_XXXX_'
or
SELECT FROM t_name WHERE col LIKE '_XXXX'
Here t_name is the name of table and col represents the column for which a comparison needs to be
made. Multiple conditions can be grouped together using the AND and OR operators. Sample
implementation to demonstrate the working of the clause is given below. Here EMP_SAL is a column
that contains numeric values.
WHERE EMP_SAL LIKE ‘400%’
This statement shall return any records for which the salary value starts with 400. For example,
employees with salary 400, 4000, 4001 and 4000, along with similar values of the same type, will be
outputted.
WHERE EMP_SAL LIKE ‘%400%’
This statement shall return any records for which the salary value has the number combination 400, at
any location. For example, employees with salary 400, 2400, 24001 and 4000, along with similar
values of the same type, will be outputted.
WHERE EMP_SAL LIKE ‘_400%’
This statement shall return any records for which the salary value has 400 at the second position. For
example, employees with salary 1400, 24000, 74001 and 7400567, along with similar values of the
same type, will be outputted.
WHERE EMP_SAL LIKE ‘2_%_%’
This statement shall return any records for which the salary value starts with 2 and has at least three
digits. For example, employees with salary 200, 24000, 24050 and 2400, along with similar values
of the same type, will be outputted.
WHERE EMP_SAL LIKE ‘%4’
This statement shall return any records for which the salary value ends with 4. For example,
employees with salary 404, 4004, 40014 and 40004, along with similar values of the same type, will
be outputted.
WHERE EMP_SAL LIKE ‘_4%3’
This statement shall return any records for which the salary value has 2 at the second position and 3 at
the last position. For example, employees with salary 423, 4203, 42013 and 42009843, along with
similar values of the same type, will be outputted.
WHERE EMP_SAL LIKE ‘2____7’
This statement shall return any records for which the salary value starts with 2, ends with 3 and has
exactly 6 digits. For example, employees with salary 200003, 203003, 200093 and 290003, along
with similar values of the same type, will be outputted.
A working example of this concept has been provided below. Consider a table named CUST with the
following data –
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
98706 Shayla 22 42005.00
98718 Mathews 37 12000.00
In order to display the records corresponding to any customers for whom the value of salary ends
with 00, the following query needs to be fired –
SELECT * FROM CUST WHERE SALARY LIKE '%05.00';
The output of the query upon execution shall be as follows –
Chapter 12: TOP Clause
The TOP clause is typically used for outputting the first N records or a specific percentage of records
from a table. It is important to mention at the starting of the chapter that this clause is not supported by
many databases. However, variations of this clause may be supported.
For instance, there is a LIMIT clause in MySQL, which is used to fetch a limited number of records
from a table. On the other hand, Oracle supports ROWNUM command for the same functionality. The
syntax for using TOP clause is shown below for your reference.
SELECT TOP num|percent col_name(s) FROM t_name WHERE [cond];
Here, num/percent is the number or percent of records that you wish to retrieve from the top of the
table, starting with the first record and col_name is the name of column that needs to be retrieved.
Lastly, cond is the condition specified as part of the WHERE clause to filter the records on the basis
of a condition.
A few working examples of the TOP clause have been given below. Consider the table named CUST
with the following data as the table for which all the queries are written.
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
98706 Shayla 22 42005.00
98718 Mathews 37 12000.00
If you wish to retrieve the first 2 records from the table CUST, then the query for the same is as
follows –
SELECT TOP 2 * FROM CUST;
Upon execution, the following result shall be generated.
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
In case you are using MySQL, the query needs to slightly changed and the new query will look like
this –
SELECT * FROM CUST LIMIT 2;
Lastly, if Oracle is being used as the base RDBMS for running these queries, the query will be –
SELECT * FROM CUST WHERE ROWNUM <= 2;
The execution of the last two commands will generate the same result as that generated for the TOP
clause.
Since, we are using MySQL, the TOP clause showed an error, but the LIMIT clause worked as
expected. Also, please note that some DBMSs sort the result in ascending order. This is a default
setting and may vary the order of records in the result set.
Chapter 13: ORDER BY Clause
There may be situations where you may be required to sort data on the basis of their values into
descending or ascending order. Moreover, this sorting can be performed for a single column as well
as for multiple columns. In fact, the sorting order for display of results is set to ascending for many
databases. The syntax for using this clause is as follows –
SELECT col-list FROM t_name [WHERE cond] [ORDER BY col1, col2, .. colN] [ASC | DESC];
Here, col-list is the list of columns that need to be used for sorting, t_name is the name of the table,
col is the name of the column and cond is the condition specified in the WHERE clause for filtering
records. The list of columns that need to be used for sorting must be given as the col-list. A sample
implementation to demonstrate how the ORDER BY clause works has been given below. Consider a
table named CUST with the following data to run the queries given below.
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
98706 Shayla 22 42005.00
98718 Mathews 37 12000.00
The following query can be used to sort the records in the table on the basis of the value of salary in
ascending order.
SELECT * FROM CUST ORDER BY SALARY ASC;
The result of the query after execution shall look like this –
ID Name Age Salary
98718 Mathews 37 12000.00
98675 Amit 32 37000.00
98706 Shayla 22 42005.00
98701 Rohan 45 50000.00
In order to sort the results by arranging the names of the customers in alphabetical order, the
following query must be given.
SELECT * FROM CUST ORDER BY NAME ASC;
You may also order the records of the table by arranging the entries for age in descending order. The
query for the same is as follows –
SELECT * FROM CUST ORDER BY AGE DESC;
The result set for the query upon its execution is as follows –
Chapter 14: GROUP BY Clause
In line with the ORDER BY, which is used to sort results, SQL also supports GROUP BY clause that
allows you to group similar records. Typically, the GROUP BY clause must be mentioned after the
WHERE clause in the SELECT statement.
You can also use GROUP BY and ORDER BY clauses together in the same query. However, be sure
to place the GROUP BY clause before the ORDER BY clause in the same. The syntax for using the
GROUP BY clause is as follows –
SELECT col1, col2 FROM t_name WHERE [cond] GROUP BY col1, col2 ORDER BY col1, col2
Here, col is the name of the column, t_name is the name of the table and cond is the condition that
needs to be used for filtering records. Please note that more than one condition can be given as part of
the WHERE clause. A sample implementation has been given below to help you understand the
concept in a better way. Consider a table named CUST with the following data to run the queries
given below.
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
98706 Shayla 22 42005.00
98718 Mathews 37 12000.00
The query used to determine the total salary of each record in the CUST table will look like this –
SELECT NAME, sum(SALARY) FROM CUST GROUP BY NAME;
This query, upon execution shall give the following result.
Consider a table named CUST with the following data to run the queries given below.
Now, in case we have many people with the same name, but they have different identities. Let us
change the sample data table to –
Consider a table named CUST with the following data to run the queries given below.
ID Name Age Salary
98756 Rohan 45 50000.00
98779 Rohan 45 5000.00
98675 Amit 32 37000.00
98706 Shayla 22 42005.00
98701 Rohan 45 5000.00
98705 Shayla 22 2000.00
98718 Mathews 37 12000.00
The following query will add the salaries of people with the same name.
SELECT NAME, sum(SALARY) FROM CUST GROUP BY NAME;
The result of the execution of this query shall be as given hereunder.
Chapter 15: DISTINCT Keyword
One of the biggest issues that are faced in databases is the presence of duplicate records in the
system. In order to get rid of duplicity, SQL supports a dedicated keyword called DISTINCT, which
can be used with the SELECT statement to get unique results for the query.
This functionality is particularly useful in operations that require you to a list of unique records only.
For instance, there can be many people with the same name. So, if you need a list of the names, then it
is irrelevant to have many records with the same entry. Such kind of duplicity can be dealt with using
the DISTINCT keyword. The syntax used for this keyword is as follows –
The standard SQL query for displaying the values corresponding to the field ‘NAME’ in the CUST
table is –
You can also club this functionality of SQL with the ORDER BY clause to get unique records in the
order for preference. For instance, we can order the names in alphabetical order using the following
query –
There may be situation where you may want to join the data of two or more table and considate the
same into a single table. In order to combine tables or combine records of two fields on the basis of
the common values of their fields, SQL supports JOIN clause. Moreover, SQL supports different
types of joins, each of which has been discussed in this chapter.
Inner Join
This is the most commonly used form of join and is also referred to as equijoin. The column values of
the two tables are combined on the basis of the join predicate. The records of the first table are
compared with the same of the second table. For every set of rows that satisfy the join predicate, they
are combined into a single row. The syntax for implementing inner join is as follows –
SELECT t1.col1, t2.col2... FROM t1 INNER JOIN t2 ON t1.common_field = t2.common_field;
Here t1 and t2 are the two tables. Col are the columns from these tables. A sample implementation for
this concept is described below. For this, let us consider two tables named CUST and CORDER. The
first table has customer data while the second table has data for the orders. The data in the table
CUST is as follows –
ID Name Age
98701 Rohan 45
98675 Amit 32
98706 Shayla 22
In order to inner join the two tables, the following query needs to be executed.
SELECT ID, NAME, ORDER_AMT FROM CUST INNER JOIN CORDER ON CUST.ID =
CORDER.CID;
The output of the query can be seen in the image shown below.
SQL Left Join
In the left join, all the rows of the first table are included in the table even if no match on the same for
the second table are found. From the second table, the rows that match from second table with that of
the first table on the basis of the join predicate are included in the result. The syntax for performing
left join is as follows –
SELECT t1.col1, t2.col2... FROM t1 LEFT JOIN t2 ON t1.common_field = t2.common_field;
Here, t1 and t2 are the two tables and col is the column in the table. In order to perform left join on
the two table CUST and ORDER given above, the following query needs to be fired.
SELECT ID, NAME, ORDER_AMT FROM CUST LEFT JOIN CORDER ON CUST.ID =
CORDER.CID;
The result of the execution is as follows –
Self Join
This join operations joins the table with itself as if it is two table being joined with each other. The
syntax for performing this operation is given below –
SELECT a.col_name, b.col_name... FROM t1 a, t1 b WHERE a.com_field = b.com_field;
Here, t1 is the table, com_field is the common field to be used for performing the join operation and
col is the column in the table. In order to perform self join on the table CUST given above, the
following query needs to be fired.
SELECT a.ID, b.NAME, a.SALARY FROM CUST a, CUST b WHERE a.SALARY < b.SALARY;
You can run the query to see how the results appear.
Cartesian Join
This type of join operation is also called cross join. It performs a cross product of the two tables.
This join is similar to inner join with no join-condition or a join-condition that always returns true.
The syntax for performing a cartesian join is –
SELECT t1.col1, t2.col2... FROM t1, t2 [, t3 ]
Here, t1 and t2 are the two tables and col is the column in the table. In order to perform cartesian join
on the two tables CUST and ORDER given above, the following query needs to be fired.
SELECT ID, NAME, ORDER_AMT FROM CUST, CORDER;
Execute the query on the system to visualize the results.
Conclusion
Now that you have come to the end of this book, we would like to remind you that like every other
programming language, you will get better with SQL as you practice and experience more of what it
has in store for you. Moreover, there may be variations of SQL used on different RDBMSs and some
keywords may not be supported by one RDBMS because it may be using a different version.
However, there should be an alternative keyword that implements same or similar functionality. So,
be patient and look for the same. For instance, the TOP clause is available in ANSI SQL, but Oracle
has ROWNUM for the same functionality. We have tried to cover all such cases, but if you come
across a case that is not covered in this book, try to look for the alternative yourself using the SQL
manual.
SQL is the fundamental programming language for databases and you must be a pro at it if you work in
the field of databases or are planning to become one. This book contains all the basic information you
require to get started with SQL and shall build the right foundation for advanced courses in SQL. We
hope this book helped you in your strive to learn SQL programming language.
Python
Introduction
Python is a high-level programming language that is interpreted, not compiled! Besides this, it is an
object-oriented programming language that supports interaction between the developer and interpreter
used for interpreting Python code. This programming language is known to have been created between
1985-1990. Guido van Rossum is credited for this development.
Just like Perl programming language, the source code for Python is available under GNU General
Public License (GPL). This book is a beginner’s guide to learning Python and shall help you create
the right foundation for learning advanced Python programming.
Moreover, this book has been designed keeping the requirements of beginners with no Python
background in mind. Therefore, you can start right away and learn Python from scratch, with the help
of this book. With that said, it is crucial to mention here that some basic knowledge of programming
and programming concepts shall help you immensely in facilitating rapid learning.
We hope you will enjoy this book. Happy coding!
Python is an interpreted, high level, object oriented language that is commonly used for scripting. The
driving force behind the development of Python was to create a programming language that can be
easily understood. Therefore, readability was one of the primary requirements of the Python project.
It is because of this reason that Python makes extensive use of English keywords without placing
much emphasis on syntactical constructions and punctuation. Before we move on to actual
programming, let us look at a little theory about the Python programming language.
History
Python is known to have been developed at National Research Institute for Mathematics and
Computer Science in the Netherlands around late eighties and early nineties. Guido van Rossum is
credited for its development, which is considered to have been inspired from many programming
languages like C, C++, ABC, Modula-3, SmallTalk and Algol-68.
It is also known to have derived elements from the Unix Shell and some other scripting languages.
Although, the core development team still manages the development of the language and it remains
copyrighted, the source code is now available as part of GNU General Public License (GPL).
Key Features
The key features of the Python programming language include –
Python code is directly interpreted by the interpreter at run-time. Therefore, there is no need
for the programmer to compile the code. This is also the manner in which this programming
language is similar to PHP and Perl.
Python allows the developer to interact with the interpreter at any time of execution. This
makes development much simpler and provides unmatched flexibility from the developer’s
perspective.
Python completely supports and implements the object-oriented methodology by
encapsulating code inside objects.
Python is considered one of the easiest languages to learn for beginners. However, the
simplicity of the language does not affect the powerful applications of the same. Python can
be used to create simple text processing applications as well as games and browsers.
Other Features
In addition to the above-mentioned, Python also has some other good features that are worth
mentioning. These include –
In addition to object-oriented programming, Python also supports structured and procedural
programming.
Python can be used as a standard scripting language as well as a programming language for
large applications by compiling programs to byte-code.
Garbage is automatically collected by the Python ecosystem.
Python can easily be integrated with other programming languages like C, C++, CORBA,
Java and COM.
Type checking is done dynamically and Python supports many high level data types.
Chapter 2: Environmental Setup
Local Setup
If you are not sure whether your system has python already installed or not, you can simply open the
terminal or command prompt and type python. If python is already present on the system, this
command will also retturn the version of python that is there. Python is supported on the following
operating systems –
Win 9x/NT/2000
Unix (Linux, Solaris, AIX, FreeBSD, SunOS, HP/UX and IRIX, in addition to some others)
OS/2
Macintosh (PPC, Intel and 68K)
PalmOS
DOS (multiple versions)
Windows CE
Nokia mobile phones
BeOS
Acorn/RISC OS
VMS/OpenVMS
Amiga
VxWorks
QNX
Psion
In addition to the above-mentioned, porting of Python to .NET virtual machines and Java has also
been done.
Getting Python
Although, python is copyrighted, its source code is available under the General GNU license.
Therefore, the latest binaries and source code can be directly downloaded from the Python website.
Besides this, you will also find the documentation related to Python and programming on the same
source. The documentation is available in HTML, PostScript as well as PDF formats.
Installing Python
Installing Python is as simple as just downloading the binaries for the platform and installing Python
for the same. However, if you are using a platform for which the binaries of Python are not available.
You can download the source code and compile the same using a C compiler on the concerned
platform manually.
This manual installation also gives you much more flexibility in terms of the features that you can
incorporate in your custom installation. This section covers Python installation for main operating
systems like UNIX, Linux, Windows and Macintosh.
Unix/Linux
In order to install Python on Unix/Linux, you need to follow the steps given below –
Go to the official page of Python using the web browser.
Download the binaries available for Unix/Linux platform.
Extract the files to a folder.
If you wish to customize the installation by adding or removing some options, access the
Setup file and do the same.
Run the ./configure script.
Give the commands make and make install.
These commands shall install Python to /usr/local/bin. The libraries of python can be found at
/usr/local/lib/pythonXX where XX is the version of Python that you have downloaded.
Windows
In order to install Python on a Windows system, you need to follow the steps given below –
Go to the official page of Python using the web browser.
Download the Windows installer python-XYZ.msi. In order to run this file, please ensure that
your Windows system has Microsoft Installer 2.0 installed. Also, note that XYZ is the
version of Python you are installing.
Download and save the installer on the local machine and run it.
Upon running, the file will take you to the Python install wizard and from here onwards, you
just need to follow the instructions until the wizard says that the installation is done.
Macintosh
Most of the recent Mac machines have Python pre-installed in them. With that said, they may not have
the most recent version and it is always good to check and get the latest version of the language
before getting started with Python programming. You can get the current version of Python for Mac
along with instructions to install it by accessing the Downloads section of the Python website.
Unix/Linux
In order to add the Python directory for a specific session in the Unix/Linux operating system, you
need to follow one of the three methods given below –
Setting Path Using CSH Shell
In order to set Path using this method, you just need to type the command given below and type enter –
PATH "$PATH:/usr/local/bin/python"
Setting Path Using Bash Shell
In order to set Path using this method, you just need to type the command given below and type enter –
export ATH="$PATH:/usr/local/bin/python"
Setting Path Using SH or KSH Shell
In order to set Path using this method, you just need to type the command given below and type enter –
PATH="$PATH:/usr/local/bin/python"
Windows
In order to link the Python path to a directory for a session, you just need to type the command given
below at the command prompt and press enter.
path %path%;C:\Python
Environment Variables
Python recognizes a few environment variables that have been described below –
PYTHONPATH
This environment variable is similar to the PATH variable and sets the directory where the system is
instructed to look for executable files and modules. PYTHONPATH is usually preset by the Python
installer.
PYTHONSTARTUP
This environment variables contains the path to the file that contains the Python source code, also
called the initialization file. Every single time that the interpreter is started, this initialization file is
called. This file is referred to as .pythonrc.py in the Unix operating system. It usually contains
commands for modifying PYTHONPATH or loading utilities.
PYTHONCASEOK
This environment variable can be set to any value for activating it. It basically checks import
statements to find any mismatch in the case that may be present.
PYTHONHOME
This environment variable also contains a module search path and is also seen as an alternative to
PYTHONPATH.
Running Python
Python can be started in any of the three different ways, which have been illustrated below.
Interactive Interpreter
Most systems including UNIX and DOS provide a command-line interpreter. In order to run Python,
you need to enter the command python and get started with Python programming right away. Some of
the options that are available with the command for advanced operations are as follows –
–d
This extension generates debug output.
–O
This extension generates optimized code.
–S
This extension instructs the system to not run import sites to look for Python paths
upon startup.
–v
This extension asks the system to provide detailed traces on import statements.
–X
This extension disables built-in exceptions.
–c cmd
This extension instructs the system to run Python script, which has been provided as
smd string.
file
This extension instructs the system to run Python script, which has been provided in
a file.
From Command Line
You can run the Python script that invokes the interpreter by running the following command.
python script.py
If you are unable to run this command, please check if you have file permissions to access this file.
Integrated Development Environment (IDE)
You can also run Python programs via a GUI (Graphical User Interface) provided you have the IDE
for the operating system that runs Python. For example, you will need IDLE for UNIX, PythonWin for
Windows and Mac version of IDLE for Macintosh. With that said, there are many other IDEs also
available for running Python on different platforms. You may explore them if you wish.
Before you start with programming, be sure to set the environment for Python programming in your
system. If you face any trouble, you may contact your system administrator. As an option, you can also
try the online compilation options available.
Chapter 3: Basic Syntax
As you learn the nitty-gritties of the Python programming language, you will realize that it shares
resemblance with many other programming languages like C, C++ and Java. However, this does not
take away the fact that there are substantial differences as well. Let us dwell into the syntax of Python
to know more.
You can also write the set of Python statements inside a Python script file. Opening the text editor and
writing the statements inside a text file can do this. The file should be saved with the extension .py.
For example, test.py is a valid python script file. You can simply write the statement given below
inside the test.py file.
print "Hello World!"
In order to run the script file, you just need to mention the name of the file in the following manner –
$python test.py
Identifiers in Python
User-defined structures like variables, functions, modules and objects require a name, which is also
referred to as ‘identifier’. An identifier can be created from any combination of numbers, alphabets
(lowercase or uppercase) and underscore (_). However, an identifier cannot start with a number.
Moreover, special characters like $, @ and % cannot be used in the identifier name.
It is important to mention here that Python is a case sensitive language. Therefore, var and Var are two
different variables. Besides this, there are some other naming conventions in Python that you must be
aware about. These include –
All identifiers start with a lower case character except for class names, which must always
begin with a capital letter.
It is assumed that an identifier that begins with underscore (_) is a private identifier.
It is assumed that an identifier that begins with two underscores (_) is a strongly private
identifier.
It is assumed that an identifier that also ends with two underscores (_) is a language defined
special name.
Reserved Words
Some words are reserved for the use of the programming language to facilitate its basic functionality.
These words cannot be used as identifiers for variables or any other objects that may be created in
the program. Please note that all the keywords in Python are completely lower-case. The list of
keywords can be found in the table given below.
assert or finally
def return if
elif while in
is else with
except Yield lambda
Comments
Python makes use of the hash sign (#) to indicate the beginning of a comment. All the characters that
follow this sign are not considered by the system. However, it is important to note that the hash sign
must not appear inside the quotes of a string. In such a scanrio, it shall not be considered the
beginning sign for a comment. Sample implementation of comments in Python are as follows –
name = "Jacob" # This is a comment
Multiple lines of comments may also appear in the same line, as shown below.
# This is a comment. # This is a comment. # This is a comment. # This is a comment.
Blank Lines
Any line that contains only a comment or whitespaces are considered blank lines by the Python
interpreter. Such lines are completely ignored. Such lines are usually used for terminating a multi-line
statement. If you working in an interactive interpreter session and you have been giving a multi-line
statement, then you will have to give a blank line to terminate the preceding statement.
Suites
Suites or multiple statement groups is a term used to indicate a group of statements that are known to
belong to the same block. Most complex statements like class and function definitions or looping and
decision making statements require the implementation of code blocks or a header line followed by a
suite.
A header line typically starts with the keyword and ends with a colon (:). The statements that follow
the colon make up a suite. Sample implementation of this concept has been given below for your
reference.
if expression : suite elif expression : suite else : suite
Command Line Arguments
The rise of interactive applications and dynamic programming has increasingly drifted the code
writing methodology towards programs that require information from the user as to how they should
run. The parameters that you provide to the program for this purpose while initiating its execution are
called command line arguments.
Python allows you to provide command line arguments using the extension, -h. Alternatively, you can
also ask for user input in your program if you wish to keep the control of program execution in your
hands. This is just an introduction to the concept of command line arguments and its implementation
shall be covered as part of advanced Python programming.
Chapter 4: Variables
A program can simply be described as logical manipulation of data values. In order to manipulate
these data values, you must store them in specific memory locations that can be referenced as and
when required. Variables allow you to reference specific memory locations that contain data values
required for logical manipulation.
It would not be wrong to state that the creation of a variable reserves a memory location in the
physical memory of the system and gives it the name of the variable. The amount of memory reserved
for a variable depends on the variable type. In fact, the data type of the variable also restricts the type
of data values that can be stored in the memory location corresponding to the variable.
For instance, if you declare an integer variable, x, then 4 bytes of memory is reserved in the memory.
This memory can be referenced using the identifier x and the range of values that this variable can
hold depends on the range of range of values allowed on your system for integer variables.
Multiple Assignment
Same data value can be assigned many variables at the same time. For example, the statement given
below is a valid Python statement.
x=y=z=1
This statement assigns three variables to the same memory location that contains the data value 1.
Alternatively, the statement given below is also valid.
x,y,z = 23,22,"jacob"
This statement declares three variables. The first two variables contain integer values whereas the
third variable is instructed to contain a string data value.
Numbers
The data type in Python, which is used for storing numeric values is Numbers. Whenever you assign
a numeric value to a variable, you automatically create an object of the Numbers class. For example,
the statement given below creates a variable X, which is an object of Numbers class as the data
value 1 was assigned to the variable.
X=1
References to Numbers objects can be deleted using the del statement. For instance, if you wish to
delete the variable X’s reference to a Number’s object, you simply need tp write the Python
statement,
del X
You can likewise use the del statement to delete multiple object references simulataneously using
only one Python statement. There is support for four numerical data types in Python, which are as
follows –
int
These data type takes care of signed integers. Examples of this data type include 123, -987, 0x69,
-0x260 and 080.
float
These data type takes care of floating point real values. Examples of this data type include 0.0,
187.67, -87.67, 90., -32.54e100 and 70.2-E12.
long
These data type takes care of long integers, which may also be in hexadecimal or octal base, in
addition to decimal base. Examples of this data type include 51924361L, 0122L, 535633629843L,
-0x19323L, 0xDEFABCECBDAECBFBAEl and 4721885298529L.
complex
These data type takes care of complex numbers. Examples of this data type include 45.j, 3.14j, .876j,
9.322e-36j and -.6545+0J.
There are a few things worth mentioning here. Firstly, you may use L or l suffix to indicate long data
type. However, the use of L is recommended because l can be confused with 1 in the standard
displays. Besides this, complex numbers can syntactically be represented as a+bj, where a and b are
real numbers and j is an imaginary unit.
Strings
Whenever a combination of characters are used and placed inside quotations, the combination of
characters is referred to as a string. You may use a pair of single or double quotation marks to
indicate that the combination of characters is a string literal. In order to slice strings, you can use the
slice operators ([] or [:]). The beginning of the string is indicated by the index 0.
Another important operator that will commonly use with strings is the concatenation operator (+). The
plus sign when used with two string operands gives a new string objects that combines the first and
second operands. Sample code for implementing concatenation of strings is given below for your
reference.
#!/usr/bin/python
str1 = 'Thank You'
print str1 # Prints complete string
print str1[0] # Prints first character of the string
print str1[2:5] # Prints characters starting from 3rd to 5th
print str1[2:] # Prints string starting from 3rd character
print str1 * 2 # Prints string two times
print str1 + " Printed" # Prints concatenated string
The output generated upon the execution of this code is shown in the image attached below.
Lists
List is a compund data type available in Python. Besides this, it is also the most versatile data type
available. A list is a collection of items that are placed within brackets and separated by commas.
Lists are similar to arrays with the difference that lists allow you to put items of different type in a
single list.
The members of the list can be accessed using the slice operators ([] and [:]). The index 0 indicates
the beginning of the list. Lastly, * is the repetition operator and + is the concatenation operator.
Sample code to demonstrate the working of lists is given below.
#!/usr/bin/python
list1 = [ 'jacob', 665 , 9.98, 'maria', 88.8 ]
list2 = [456, 'alisa']
print list1 # Prints complete list
print list1[0] # Prints first element of the list
print list1[1:3] # Prints elements starting from 2nd till 3rd
print list1[2:] # Prints elements starting from 3rd element
print list2 * 2 # Prints list two times
print list1 + list2 # Prints concatenated lists
The output generated upon the execution of this code is shown in the image attached below.
Tuples
This data type is similar to lists in the sense that it is a collection of data values that are separated by
commas. The only difference between lists and tuples is that the items within a tuple are enclosed
inside parentheses. Another important difference beween tuples and lists is that the elements of the
latter can be updated and changed while that of the former cannot be modified. Therefore, tuples are
commonly also called read-only lists. Sample code to demonstrate the working of tuples is given
below.
#!/usr/bin/python
tuple1 = ( 'jacob', 3446 , 798.6, 'maria', 88.8 )
tuple2 = (786, 'alisa')
print tuple1 # Prints complete tuple
print tuple1[0] # Prints first element of the tuple
print tuple1[1:3] # Prints elements starting from 2nd till 3rd
print tuple1[2:] # Prints elements starting from 3rd element
print tuple2 * 2 # Prints tuple two times
print tuple1 + tuple2 # Prints concatenated tuples
The output generated upon the execution of this code is shown in the image attached below.
Please note that you cannot update the value of any element of a tuple. For instance, the statement
given below is invalid.
tuple1[2] = 1000
On the other hand, in lists, it is allowed and the statement given below is a valid statement.
list1[2] = 1000
Dictionary
If you are familiar with the concept of hash tables, you will find a lot of similarity between the Python
dictionary and hash tables. The working of a dictionary is based on associative arrays that consist of
key-value pairs. Any data type key can be used including numbers and strings. On the other hand, the
values must be a Python object. Dictionaries are enclosed with curly braces and are accessed using
square brackets. Sample code to demonstrate the working of dictionaries is given below.
#!/usr/bin/python
dict1 = {}
dict1['one'] = "One"
dict1[2] = "Two"
dict2 = {'name': 'jacob','code':6785, 'dept': 'marketing'}
print dict1['one'] # Prints value for 'one' key
print dict1[2] # Prints value for 2 key
print dict2 # Prints complete dictionary
print dict2.keys() # Prints all keys
print dict2.values() # Prints all values
The output generated upon the execution of this code is shown in the image attached below.
An important thing to mention here is that there is no concept of order in dictionaries. There are
simply unordered. Therefore, it cannot be said that a dictionary is out of order.
In order to manipulate data, a construct called operator is provided. The simplest example of
operator is the ‘+’ in the expression, 2+3. Here, 2 and 3 are data values and + is the operator that tells
the system as to what kind of manipulation needs to be performed on the concerned data values,
which are also referred to as operands.
Python supports many types of operators namely arithmetic, logical, relational, assignment,
membership, bitwise and identity operators. The different operators available under each of these
categories have been described below.
Arithmetic Operators
The operators, which perform arithmetic operations on numeric data values are called arithmetic
operators. The operators available in Python are as follows –
Addition (+)
This operator adds two numeric data values. For example, if there are two variables a and b, where a
= 10 and b = 5, then a + b = 15.
Subtraction (-)
This operator subtracts a numeric value from another numeric value. For example, if there are two
variables a and b, where a = 10 and b = 5, then a - b = 5.
Multiplication (*)
This operator multiplies a numeric value to another numeric value. For example, if there are two
variables a and b, where a = 10 and b = 5, then a * b = 75.
Division (/)
This operator divides a numeric value from another numeric value. For example, if there are two
variables a and b, where a = 10 and b = 5, then a / b = 2.
Modulus (%)
This operator returns the remainder computed after dividing a numeric value from another numeric
value. For example, if there are two variables a and b, where a = 10 and b = 5, then a % b = 0
because 10 is completely divisible by 5 and no remainder is present.
Exponent (**)
This operator calculates the exponential power on operators. For example, if there are two variables
a and b, where a = 10 and b = 2, then a ** b = 100 as the operation calculates the value of 10 2 .
Floor Division (//)
This operator rounds off the quotient by removing the digits that appear after the decimal point. In
case one of the operands is negative, the resultant is rounded off on the timeline from 0 to negative
infinity. For example, if there are two variables a and b, where a = 9 and b = 2, then a // b = 4.
Relational Operators
The job of these operators is to compute the expression by comparing their values. The value of the
expression is computed to be either true or false. The relational operators available in Python are as
follows –
Equal To (==)
This operator checks if the operands on both sides of the operator are equal. The result returned is
true if the operands are equal. Otherwise, the result returned is false. For example, if there are two
variables a and b, where a = 10 and b = 5, then (a == b) is FALSE.
Not Equal To (!=)
This operator checks if the operands on both sides of the operator are not equal. The result returned is
true if the operands are not equal. Otherwise, the result returned is false. For example, if there are
two variables a and b, where a = 10 and b = 5, then (a != b) is TRUE.
Not Equal To (<>)
This operator is similar to the Not Equal To (!=) operator and functions in the same manner.
Greater Than (>)
This operator checks if the operands on the left side is greater than the operand on the right hand side
of the expression. The result returned is true if the operands are so arranged. Otherwise, the result
returned is false. For example, if there are two variables a and b, where a = 10 and b = 5, then (a > b)
is TRUE.
Less Than (<)
This operator checks if the operands on the left side is less than the operand on the right hand side of
the expression. The result returned is true if the operands are so arranged. Otherwise, the result
returned is false. For example, if there are two variables a and b, where a = 10 and b = 5, then (a < b)
is FALSE.
Greater Than Or Equal To (>=)
This operator checks if the operands on the left side is greater than or equal to the operand on the
right hand side of the expression. The result returned is true if the operands are so arranged.
Otherwise, the result returned is false. For example, if there are two variables a and b, where a = 10
and b = 5, then (a >= b) is TRUE.
Less Than Or Equal To (<=)
This operator checks if the operands on the left side is less than or equal to the operand on the right
hand side of the expression. The result returned is true if the operands are so arranged. Otherwise, the
result returned is false. For example, if there are two variables a and b, where a = 10 and b = 5, then
(a <= b) is FALSE.
Assignment Operators
The job of this set of operators is to assign values to variables using a combination of different
operators. Assignment operators available in Python include –
Equal To (=)
This operator is used to directly assign values to a variable. For example, if there is a variable a, then
a = 8, assigns the value 8 to the variable a.
Add and Assignment (+=)
This operator is used to directly assigns the value computed by adding the data value on the right hand
side to the value of the variable on the left hand side, to the variable mentioned on the left hand side
of the expression. For example, if there is a variable a and a = 5, then a += 8 will result in a = 8+5 =
13.
Subtract and Assignment (-=)
This operator is used to directly assigns the value computed by subtracting the data value on the right
hand side from the value of the variable on the left hand side, to the variable mentioned on the left
hand side of the expression. For example, if there is a variable a and a = 5, then a -= 8 will result in a
= 5-8 = -3.
Multiply and Assignment (*=)
This operator is used to directly assigns the value computed by multiplying the data value on the right
hand side to the value of the variable on the left hand side, to the variable mentioned on the left hand
side of the expression. For example, if there is a variable a and a = 5, then a *= 8 will result in a =
8*5 = 40.
Divide and Assignment (/=)
This operator is used to directly assigns the value computed by dividing the data value on the left
hand side by the value of the variable on the right hand side, to the variable mentioned on the left hand
side of the expression. For example, if there is a variable a and a = 10, then a /= 5 will result in a =
10/5 = 2.
Modulus and Assignment (%=)
This operator is used to directly assigns the remainder computed by dividing the data value on the left
hand side by the value of the variable on the right hand side, to the variable mentioned on the left hand
side of the expression. For example, if there is a variable a and a = 10, then a /= 5 will result in a =
10%5 = 0.
Exponent and Assignment (**=)
This operator is used to directly assigns the value computed by finding the exponent of the data value
on the right hand side and the value of the variable on the left hand side, to the variable mentioned on
the left hand side of the expression. For example, if there is a variable a and a = 10, then a **= 2 will
result in a = 10 2 = 100.
Floor and Assignment (//=)
This operator is used to directly assigns the value computed by finding the floor of the operand on the
right hand side and the value of the variable on the left hand side, to the variable mentioned on the left
hand side of the expression. For example, if there is a variable a and a = 9, then a //= 2 will result in
a = 9//4 = 2.
Logical Operators
This set of operators is used for performing logical operations on variables. The logical operators
supported by Python include –
Logical AND
This operator works on two operands. If both the operands are non-zero, the expression returns
TRUE else it returns FALSE.
Logical OR
This operator works on two operands. If one or both the operands are non-zero, the expression
returns TRUE else it returns FALSE.
Logical NOT
This operator works on one operand. If the operand is zero, this expression returns TRUE else it
returns FALSE.
Bitwise Operators
The bitwise operators perform logical operations on numbers in such a manner that bit-by-bit result is
calculated. The bitwise operators supported in Python include –
Bitwise AND (&)
This operator works on two operands and the output for each set of input bits is 1 if both the inputs
are one else the output is zero.
Bitwise OR (|)
This operator works on two operands and the output for each set of input bits is 1 if one or both of the
inputs is one else the output is zero.
Bitwise XOR (^)
This operator works on two operands and the output for each set of input bits is 1 only if one of the
inputs is one else the output is zero.
Bitwise COMPLEMENT (~)
This operator works on a single operand and negates the values from 0 to 1 and from 1 to 0.
LEFT SHIFT (<<)
This operator works on two operands. The bits of the left operand are shifted left. The number of
places is equal to the number specified as value for the second operand.
RIGHT SHIFT (>>)
This operator works on two operands. The bits of the left operand are shifted right by the number
specified as value for the second operand.
In order to understand how bitwise operations take place, let us take an example. Assume two
variables, a and b, having the values 60 and 13 respectively. The binary equivalent of a and b are as
follows –
a = 00111100
b = 00001101
Using the AND truth table according to which the output is 1 only if both the inputs are 1.
Correspondingly, the output of a&b = 00001100. Similarly other bitwise operations can also be
performed.
Membership Operators
Membership in sequences like lists and tuples can be tested using membership operators. Python
supports the following membership operators –
In Operator
This operators evaluates if a variable is a member of the sequence concerned and returns true if so.
Not In Operator
This operators evaluates if a variable is not a member of the sequence concerned and returns true if
so.
Identity Operators
This set of operators compares the memory locations of variables to test if they are referring to the
same data value/memory location. The identity operators supported in Python include –
Is Operator
This operators evaluates if a variable is referring to the same location as that of the other variable
and returns true if so.
Is Not Operator
This operators evaluates if a variable is not referring to the same location as that of the
other variable and returns true if so.
Checking conditions is one of the fundamental programming scenarios. A typical decision making
construct checks for the truthfulness of a condition. If the condition is found true, a block of statements
corresponding to the condition is executed. The flow diagram for a standard conditional construct is
illustrated below.
As a rule, any non-zero or non-NULL value is assumed to be true while evaluating the if condition.
Correspondingly, any zero or NULL value is assumed to be false. The decision statements available
in Python include –
If statement
The standard decision making statement available in all programming languages is ‘if’ statement. This
programming construct checks the condition specified within round brackets that follow the ‘if’
keyword. If the condition is found true, the block of statements that follow the if statement are
executed. On the contrary, if the condition is found false, the control is shifted to the statement that
appears after the if block.
If-else statement
The if-else statement is an enhanced version of the basic ‘if’ statement. It also includes a ‘else’ block
that includes statements that shall be executed if the condition mentioned in the ‘if’ statement is found
false.
Nested if statements
Python also allows the use of nested if statements or if-else statements. Moreover, there is
no defined limit on the depth of nesting that can be performed.
One of the fundamental constructs in any programming language is the loop, which caters for
programming scenarios that require repetitive or iterative execution of a block. Python also provides
control structures for looping. The typical pathway of execution for loops is shown in the diagram
given below –
In order to handle the looping requirements of a developer, Python provides the following constructs
–
While Loop
The while loop checks a condition and if found true, the block of code following the loop statement is
executed. On the contrary, if the condition is found false, the loop block is exited.
For Loop
In addition to condition checking, the ‘for’ loop also allows the developer to declare, initialize and
update the looping variable.
Nested Loops
Python allows nesting of loops and there is no limit on the depth of nesting permitted.
Control Statements
Owing to the powerful structures that loops are, it is easy to create scenarios that take the program
into an infinite loop. In order to counter such situations, Python also supports some control statements
that can be used to redirect execution from the usual pathway to the desired execution path. The list of
control statements provided by Python is given below for your reference.
Break
The break statement breaks the loop and transfer control to the statement that follows the loop block.
Continue
The continue statement halts the execution of the current loop and transfers control to the loop
statement (while or for statement of the loop).
Pass
The pass statement is typically used for statements that are syntactically required by the program, but
the program needs to be instructed to not execute them.
Chapter 8: Functions
Most applications that are developed today require hundreds of lines of code to function the way they
do. However, it is not possible to write such long code in a single file, in one function. Moreover,
there may be many tasks that may have to be repeatedly performed in the code. In order to better
organize the code into modules and create code blocks that perform a specific functionality, which
can be reused every time the functionality is required, the concept of functions came into existence.
The two main advantages of functions are (1) they allow a high degree of code reusability and (2)
provide better modularity for your application. You have already come across functions like print ()
in the sample codes. Print is an inbuilt function available in Python for displaying any set of
characters on the screen. Python also allows you to create functions of your own, which are referred
to as user-defined functions.
Defining a Function
User-defined functions can be stated using the following rules –
The definition of a function begins with the declaration statement. This statement starts with
the keyword def, which is followed by the name of the function and a pair of parentheses.
These parentheses are used to declare any parameters that this function requires as input from
the calling function.
The statement of a function is usually the docstring or the documentation string. However,
please note that this statement is optional.
After this, the function’s code block begins. This block starts with a colon and all the
statements that are part of the block are indented in the same manner.
Every function has a mandatory return statement. This statement returns an expression to the
calling function. There may be functions that do not return anything at all. For such functions,
the statement given below is used.
return None
The syntax for defining a function is given below for your reference.
def name_of_function( list_of_parameters ):
" docstring"
function_suite
return [expression]
A function can have any number of input parameters. It is important to understand that the parameters
must be given from the calling function in the same order as they are mentioned in the function
definition. Sample code to demonstrate the implementation of a function is given below.
def printstring( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Function definition only provides the details of the function in terms of its name, input parameters and
what it should do in the form of the function suite. Once you have defined a function, you can call it
from another function or you may call it directly from the prompt by giving its name and the
parameters it requires to execute. The sample code given below calls the printstring() function that
we defined in the last section.
#!/usr/bin/python
# Function definition is here
def printstring( str ):
"This string is input parameter to the printstring function."
print str
return;
# Function is being called
printstring("First Function Call!")
printstring("Second Function Call!")
Upon execution, the code yields the following result –
Passing Data to Functions by Value and Reference
When you pass a data value to a function using the input parameter of the function, you are sending the
variable name that refers to the memory location corresponding to the data value. Therefore, this
method of passing a data value to a function is called ‘Calling by Reference’. In this case, if there is
any change in the data value of the variable, the same is reflected in the variable’s value, in the
function. Sample code to demonstrate this functionality of Python is given below.
#!/usr/bin/python
# Function definition is here
def changemyvalue( list1 ):
"The passed list's value is changed here"
list1.append([22,33,44,55]);
print "Values of List in Function: ", list1
return
# Now you can call changeme function
list1 = [11,66,77];
changemyvalue( list1 );
print "Values of List Outside the Function: ", list1
Upon execution, the code yields the following result –
Here is another sample code to show you how call by reference can be used to overwrite values of
variables from the calling function.
#!/usr/bin/python
# Function definition
def changemyvalue( list1 ):
"Values of the list are changed inside the function."
list1 = [11,22,33,44]; # A new reference is assigned to list1
print "Values of list inside function: ", list1
return
# Call the function
list1 = [99,88,77];
changemyvalue( list1 );
print "Values of list outside function: ", list1
Upon execution, the code yields the following result –
Function Arguments
There are four types of arguments that can be used to call a function. These include default arguments,
required arguments, keyword arguments and variable-length arguments, and have been described
below.
Required arguments are arguments that are mentioned in the function definition and the interpreter
will raise a syntax error if the calling function doesn’t give these arguments while calling the function
concerned. In the printmyvalue() example, the parameter str was a ‘required argument’. These
arguments must be provided in the same order in which they are provided in function definition.
The second type of arguments is keyword arguments, which are related to function calls. The
arguments are identified here by the name of the parameter. This allows you to give arguments that are
not in order of their occurrence in the function definition because the Python interpreter identifies the
parameter by the name of the parameter provided in the definition of the function. Sample code given
below demonstrates the working of keyword arguments.
#!/usr/bin/python
# Function definition is here
def printvalues( name, age ):
"The parameters passed to the function are printed here"
print "Name: ", name
print "Age ", age
return;
# Now you can call function
printvalues( age=43, name="michael" )
Upon execution, the code yields the following result –
Sometimes, you may want arguments to assume default values if the calling of the function fails to
provide an argument value for the same. This concept can be implemented using default arguments.
Sample code given below demonstrates how default arguments can be implemented.
#!/usr/bin/python
# Function definition is here
def printvalues( name, age=50 ):
"The parameters passed to the function are printed here"
print "Name: ", name
print "Age ", age
return;
# Now you can call function
printvalues( age=43, name="michael" )
printvalues( name="michael" )
Upon execution, the code yields the following result –
There may be programming scenarios that require you to provide more number of arguments that are
required or mentioned in the function definition. Variable-length arguments allow you to provide
arguments that were not mentioned in the definition of the function. The syntax for implementing
variable-length arguments is given below.
def name_of_function([formal_args,] *var_args_tuple ): "docstring" suite return
[expression]
Here, the * and var_args_tuple indicate all the non-keyword arguments that are provided to the
function. The asterisk indicates that the tuple may be empty in cases where no non-keyword arguments
may be given. Sample implementation of this concept is given below for your reference.
#!/usr/bin/python
# Function definition
def printvalue( arg1, *vartuple ):
"This function demonstrates the working of variable length arguments."
print "Output : "
print arg1
for var in vartuple:
print var
return;
# Call printvalue function
printvalue( 1 )
printvalue( 77, 66, 55 )
Upon execution, the code yields the following result –
Anonymous Functions
In order to create small functions, Python allows a provision for anonymous functions. These
functions are not declared like normal functions using the def keyword. Instead, they are created using
the lamda keyword. Some of the key features of these functions are given below –
Lamda functions can return a single value in the form of an expression. However, they can
take any number of arguments.
Lamda functions cannot contain multiple expressions or commands.
Since, lamda functions require an expression, they cannot be used for making a direct call to
print.
Lamda functions work within the local namespace. Therefore, they can only access variable
that are in the global namespace or within their parameter-list.
It would not be wrong to state that lamda functions are one-line version of a function.
However, they cannot be compared to inline functions in C and C++, which provide
significant performance enhancement because of their presence.
In order to implement lamda functions, the following syntax may be used.
lambda [arg1 [,arg2,.....argn]]:expression
Sample implementation of this concept has been provided below for your reference.
#!/usr/bin/python
# Function definition
sum = lambda arg_1, arg_2: arg_1 + arg_2;
# Call sum as a function
print "Result 1 : ", sum( 11, 22 )
print "Result 2 : ", sum( 24, 24 )
Upon execution, the code yields the following result –
Return Statement
This statement is officially the exit statement of a function. It tells the interpreter that the function has
terminated and it is time to redirect control back to the place where the function was called.
However, the return statement can also be used to return a value or expression to the caller. For
functions that do not return anything, only the keyword return is used. The sample code given below
demonstrates how a return statement can give a value back to the caller.
#!/usr/bin/python
# Function definition
def sum( arg_1, arg_2 ):
# Add parameters and return their value."
result = arg_1 + arg_2
print "Inside function : ", result
return result;
# Call sum function
result = sum( 11, 22 );
print "Outside function : ", result
Upon execution, the code yields the following result –
Scope of Variables
The concept of blocks and namespaces gives rise to variable forms of accessibility as far as elements
of the program are concerned. Therefore, variables declared and defined at one location may not be
available to a function at another location. The region where a variable is deemed accessible is
called the ‘scope of a variable’.
Typically, a variable can have local or global scope. If a variable is defined inside a block or
function, then the variable is ‘local’ to that block of code and can be accessed only within its
confines. On the other hand, variables that are defined outside all the blocks and functions are
globally accessible to all and are known to have a ‘global’ scope. Sample code given below
demonstrates the working of local and global variables.
#!/usr/bin/python
result = 0; # global variable
# Function definition
def sum( arg_1, arg_2 ):
# Add parameters and return result."
result = arg_1 + arg_2; # local variable
print "Inside function (local result) : ", result
return result;
# Call sum function
sum( 11, 22 );
print "Outside function (global result) : ", result
Upon execution, the code yields the following result –
Chapter 9: Modules
In addition to functions, Python also allows logical organization of code in the form of modules.
Related code can be grouped together into a module. This makes it easier to understand and use.
More specifically, a module is a Python object, which has arbitrarily named attributes that can be
bound and referenced. It can also be defined a file that contains Python code including class, functions
and variables.
In order to help you visualize how a module looks like, we request you to see the code given below.
For a module support, which resides inside a file support.py, the code inside the file is as follows –
def print_func( par ): print "Hello : ", par return
Locating Modules
Whenever you give an import statement, the interpreter searches for the module in the following paths
and sequences –
Current directory
Each directory inside the path stated in PYTHONPATH
If both of the above paths fail, the default path is checked. In Unix, the default path is
/usr/local/lib/python.
The search path for the module is located in the sys.path variable of the system module. All the three
paths mentioned above are available in this variable. The PYTHONPATH is basically an
environment variable that includes a set of directories and can be set by the user using the following
command –
For Unix Users:
set PYTHONPATH = /usr/local/lib/python
For Windows Users:
set PYTHONPATH = c:\python20\lib;
Packages
A single Python application environment can have many modules and sub-packages. The hierarchical
structure that defines the file directories of this arrangement is called a package. Packages can also be
imported in the same manner as modules.
Conclusion
Now that we have reached the end of this book, we are sure that you are thorough with the basics of
Python programming. Besides this, we hope you have executed all the sample codes provided in this
book on a local setup or online arrangement. If you haven’t done so already, please go ahead and do
so.
A programming language, irrespective of which programming language you are working on, can only
be learnt well if you practice it. Just like you cannot learn to drive a car by reading a book on the
same and until you actually sit on the driving seat and get a real world hang of how it operates, you
cannot program in a programming language until you have written programs and executed them in a
real-world environment.
We hope this book has helped you gain ample ground on the basics to take you leaps forward in the
advanced programming lessons of Python. You can take this learning forward to become an expert
programmer in Python. We wish you good luck in all your future endeavors.
PHP
Introduction
PHP or PHP Hypertext Preprocessor is a programming language, which was designed with the
objective to allow creation of dynamic content. Moreover, PHP also enables this dynamic content to
interact with databases. As a result, the most intuitive application of PHP is for development of web-
based software applications. This book is an introductory tutorial to help you learn PHP from scratch
and build the right foundation for advanced lessons in this programming language.
Although, this tutorial does not require the reader to have any prior knowledge of PHP or any other
programming language, basic knowledge about programming concepts is recommended. Besides this,
considering the fact that PHP allows interaction with databases, you can expect to encounter
databases once in a while. Therefore, some background knowledge and understanding of databases
and SQL will also be of immense help.
This book includes several sample codes, which have been provided to give you the real-world
programming experience. Go ahead and execute these codes for a better learning experience. Besides
this, you may also try variations of code because the best way to learn a programming language is by
writing programs in it. We wish you a fruitful experience. Happy Coding!
Copyright 2017 - All rights reserved.
This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold with the idea that the publisher is not required to render
accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
means or in printed format. Recording of this publication is strictly prohibited and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
loss due to the information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely, and is universal as so. The
presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are the owned by the owners themselves, not affiliated with this
document.
Chapter 1: Overview
The first version of PHP was a small open source project that was initiated by Rasmus Lerdorf. This
version of PHP was released in the year 1994 and it was after this release that PHP really picked up
as a language of choice for programmers all over the world. It is this growing popularity of the
language that has converted this small project into a project of world-wide recognition.
Before moving any further, let us look at a few facts about PHP. Firstly, PHP is a recursive acronym
that stands for PHP: Hypertext Preprocessor. Basically, it is a scripting language for server-side
programming. The scripts are embedded into HTML code and can be used to manage databases,
dynamic content and session tracking. One of the most popular applications of PHP is in the
development of e-commerce websites.
The fact that PHP allows management of databases is one of the key features of this programming
language. To support this, PHP allows seamless integration with many databases like Microsoft SQL
Server, Informix, Sybase, Oracle, MySQL and PostgresSQL. Performance-wise, PHP is literallu
zippy in zits execution. This is all the more true for scripts that are compiled in the form of Apache
module on Unix side. Upon starting, the MySQL Server can execute the most complex queries in
record-setting time.
Multi-tier development, which is the need of modern programming, has bene made possible by PHP.
PHP4 supports distributed object architectures (CORBA and COM) and Java. Besides this, it also
supports a variety of protocols like LDAP, IMAP and POP3. Lastly, PHP is one of the most forgiving
languages you will ever use and shares excessive similarities with the C programming language as far
as syntax is concerned.
As you can see in the sample code, the web browser does not output the PHP code as it is. Instead, it
processes the code and what we get on the browser of the client screen is pure HTML output. PHP
code can be integrated with HTML using one of the three ways illustrated below –
<?php PHP code goes here ?>
<? PHP code goes here ?>
<script language = "php"> PHP code goes here </script>
Using one of the formats shown above, you can put PHP code in HTML. This tells the parser that the
text present in this format is PHP script, which needs to be executed. The commonest tag used for
PHP integration with HTML is <?php … ?>.
Environmental Setup
Evidently, PHP runs with HTML in the web browser and to test PHP code, you will need to set up a
local system. In order to run PHP scripts as part of your HTML in the web pages, you require three
components to be installed on your local system. These components include –
Web Server
You can use any web server and rest assured that PHP will work with it. Therefore, if you are
working on a Windows system, you can safely work with the Microsoft’s Internet Information Server
(IIS). With that said, the Apache remains the most popular server for PHP because of its open source
nature.
Database
Likewise, PHP can be used with any database solution, which includes popular databases like Sybase
and Oracle. However, the solution that is most commonly used is MySQL.
PHP Parser
The system cannot read and understand the PHP instructions provided by you until you have a PHP
parser installed on your machine, which reads PHP statements and generate HTML output that is then
sent to the Web Browser.
Now that we have already written our first PHP program, let us take this knowledge forward to write
more programs in this programming language. However, in order to graduate to more complex
programs, you need to learn the syntax that this programming language uses.
Escaping to PHP
Firstly, we need to understand that PHP code is written as part of HTML or is embedded into HTML.
Therefore, there has to be a way by which the PHP parsing engine differentiates between HTML and
PHP. The mechanism used for this purpose is referred to as ‘escaping to PHP’. This can be done in
four ways, which are as follows –
Canonical PHP Tags
The most universally accepted and effective tag style for PHP is <?php … ?>. The use of this tag style
ensures that your tags will be correctly interpreted by most systems.
Short-Open (SGML-style) Tags
The SGML tags look similar to the format given below –
<? … ?>
it is evident from the name that this format is the shortest way to tell the PHP parser that you are
embedding PHP code. However, in order to ensure that PHP recognizes your tags, you need to do the
following –
While building PHP, use the configuration option, --enable-short-tags.
Open the php.ini file and check if the short_open_tag setting is set to ‘on’. Since, the same
syntax is used for XML tags, you must switch this option to ‘off’ for enabling XML parsing.
ASP-style Tags
These tags use the same tags as that used by Active Server Pages for delineating code blocks. You
will have to check the php.ini file to see if these tags are enabled for your PHP configuration. In order
to use these tags, you must follow the given syntax –
<% … %>
HTML Script Tags
The HTML script tags can be used in the following manner –
<script language = "PHP">...</script>
Comments in PHP
Comments are text or lines that are ignored by the parser. These lines of text are typically used to
improve the readability and understandability of code. However, they do not contribute, in any way,
towards changing the output. PHP supports single-line as well as multi-line comments.
Single – line comments can be made by preceding the line with # or //. The presence of these
characters tell the parser that the text following this character combination and until a newline
character is encountered, is a comment. Example of single line comments can be found below.
<? # This is a comment, and # This is the second line of the comment // This is a comment
too. Each style comments only print "An example with single line comments"; ?>
Multi – line comments are comments that span across multiple lines. In other words, the termination
of a multi-line comment is not assumed on the presence of a newline character. These comments begin
with the character combination ‘/*’ and end with ‘*/’. Any text written between these two character
combinations is referred to as a ‘multi-line comment’. Example of a multi-line comment is given
below –
<? /* This is a comment with multiline Author : Mohammad Mohtashim Purpose: Multiline
Comments Demo Subject: PHP */ print "An example with multi line comments"; ?>
It is important to mention here that PHP is insentive to whitespaces. In other words, no matter how
many whitespace characters you use, in an isolated manner or together, the system will just ignore it.
Typically, whitespace characters include tabs, spaces, newlines and carriage returns of any kind.
Besides this, PHP is case-sensitive. In other words, variables xz and Xz are two different identifiers
for the PHP system. Lastly, all PHP expressions must be terminated with a semicolon (;). The
presence of semicolon is an indication to the system that the expression has terminated and now, it can
expect to receive a new PHP expression.
Digging deeper into the concept of expressions, they are nothing but a combination of tokens that
cannot be further broken into sub-entities. These tokens are strings, numbers, constants and variables.
In addition to these, keywords are also tokens. A collection of statements that does a specific function
is called a block and is demarkated with the help of braces. The sample code shown below
demonstrates all the concepts mentioned in the text.
if (2==2) print("Equality prevails<br>"); if (2 == 2) { print("Re-analysis"); print("
completed.<br>"); }
In order to store information, we need to create variables that can hold this information and used for
referencing the same. Some of the most important things to understand about using variables in this
programming language are as follows –
As a rule, all variable names must be preceded by a dollar sign ($) for it to be considered
valid by the system.
The most recent assignment statement related to the variable determines its current value.
In order to assign values to variables, the equal to operator (=) must be used. This operator
must have the variable on the left hand side and the value or the expression that computes the
value on the right hand side of the operator.
It is a good programming practice to declare variables before using them. However, if you do
not do so, PHP will still allow you to go ahead and use the variable.
PHP does not assign any intrinsic type to a variable. Therefore, you can use a variable to
store any kind of information, be it a number or a string. No such type needs to be assigned to
a variable in advance.
If you use a variable without assigning a value to it, the variable will hold a default value.
Whenever necessary, type of a variable is automatically converted from one to the other.
Variables in PHP are similar to those in Perl.
PHP supports eight data types when it comes to information storing in variables. These data types are
as follows –
Booleans
This data type can only hold two types of values, which include TRUE and FALSE. There are
situations that demand expressions to be evaluated as boolean giving the result of TRUE or FALSE.
While performing such evaluations, the following rules must be kept in mind –
If the expression evaluates to a number, which is zero, then the value of the expression is
FALSE. Any other number is considered non-zero and is evaluated as TRUE.
If the expression evaluates to a string, then the boolean value of the expression is TRUE if it
evaluates to a valid string. On the other hand, if the string is empty, then the expression is
evaluated to FALSE.
Any expression that evaluates to the value NULL has an equivalent boolean value of FALSE.
If an expression evaluates to an array, then the boolean value of the expression is TRUE if the
array has elements. On the other hand, if the value of the expression is an array with no
elements, its boolean value is FALSE. Considering the case of objects, if any of the member
variables of the objects have a value assigned to it, then the object evaluates to the boolean
value TRUE, else it is evaluated as FALSE.
Any resource that is valid for the PHP system is evaluated as TRUE.
The use of doubles as booleans must be avoided.
Integers
All the whole numbers are included in Integers. For example, any number like 6758 or 54 is an
integer. The syntax or PHP expression for assigning a value to an integer, is given below –
$int_variable = 45;
It is important to mention that the largest integer that can be held by a system is 2,147,483,647.
Doubles
All floating point numbers that are actually just whole numbers followed by a decimal point and
fractional part fall under this data type.
Strings
Any combination of characters is referred to as a string. All string operations are supported in PHP.
NULL
This data type can store only one value and is usually used for initializing variable. The one value
that it stores is NULL. Although, conventionally, capital letters are used for writing NULL, it can also
be written as ‘null’ and the system will recognize it as the same. Therefore, the following statement is
valid –
$var_1 = null;
There are two important things to note about NULL. Firstly, NULL always evaluates to FALSE when
a boolean equivalent is to be determined. Secondly, if NULL is tested against IsSet() function, it
always evaluates to FALSE.
Arrays
A collection of data of the same type can also be called an array. In fact, arrays can also be visualized
as a number of variables of the same type, which are referred by the same name and are distinguished
by the index at which they are present.
Objects
Programmers can define classes or templates, which when instantiated create objects. A class is
typically composed of data values and functions. An object of that class can access all the functions
of the class and possesses a set of data members of itself, in accordance with the data members
defined for the class.
Resources
There may be some programming scenarios that require you to refer to resources that are not
available within PHP. An example of such a programming scenario is database connection. In order
to hold such references, special variables are required, which are called resources.
The difference between single quoted strings and doubly quoted strings is that the former are treated
literally while the latter can replace the value of variables. Besides this, certain specially interpreting
character sequences are also represented as doubly quoted strings.
As far as the limitation on the string length is concerned, PHP does not impose any such limits.
Therefore, as long as the memory allows, you can create effectively long strings. Doubly quoted
strings are processed by the system in one of the following ways –
Whenever a variable name is encountered, which is identified by the appearance of $ as the
first character in the name, the string representation of the variable is automatically put into
its place.
Special characters begin with a backslash (\) and they are accordingly interpreted as a
special character with a specific purpose.
The common replacements for escape sequences are as follows –
Escape Sequence Meaning
\\ Single backslash (\)
\” Double quote (“)
\$ Dollar sign ($)
\t Tab
\r Carriage return character
\n Newline character
Scope of Variables
The scope of a variable determines its accessibility in the program in terms of the elements that are
allowed to access the variable and those that cannot. There are four types of scope in PHP which
include local, global, static variables and function parameters.
Variables that are only available within the block of code to which they belong are referred to as
local variables. On the other hand, variables that are globally available and accessible for all are
called global variables. Function parameters are parameters supplied to a function and act as local
variables for the function.
Static variables are a special type of variables that maintain their value and exist between function
calls. Therefore, if you are using a static variables and use it in a function that is called thrice, the
value of static variable will be assumed as the value assigned to it by the last function call.
An identifier or name used to refer to a simple value is called ‘constant’. It is important to note that
the value of a constant cannot be change during the course of the program. Therefore, a constant holds
the value that it does, throughout!
As a convention, a constant is declared in capitals. However, they are case-sensitive, by default. The
naming conventions used for naming a constant is same as that for a variable. The name can be any
combination of characters including underscore (_) except for special characters. Moreover, the name
of the constant cannot start with a numeric character.
As mentioned previously, the value of a constant remains ‘constant’. Therefore, once you have
defined a constant, you cannot change its value or un-define it for that sake. In order to define a
constant, the function define() needs to be used.
Retrieval of the constant’s value just requires mentioning its name. The difference between using a
variable and constant is that the name of a variable is preceded by $ while the constant’s name is
written just as it is. Alternativey, the use of the function constant() can also be used to retrieve the
value of a constant.
Constant Function
This function is used to retrieve the value of a constant. The calling of this function returns the
constant’s value. This function is generally used for constants whose name is not mentioned and it is
stored in a variable is is the return value for a function.
Sample implementation of this concept is given below –
<?php
define("MINIMUM_SIZE", 25);
echo MINIMUM_SIZE;
echo constant("MINIMUM_SIZE ");
?>
It is important to mention here that constants can only hold scalar data like integer, float, boolean and
string.
Magic Constants
There are some predefined constants supported by PHP. Any script that runs on PHP can access these
constants. Some constants in PHP change on the basis of where they are being used. For instance, the
constant __LINE__ is dependent on the line that it is being used on. These are case-insensitive. Some
of the PHP constants, which are defined as ‘magical’ are as follows –
Magic Constant Meaning
__LINE__ This constant indicates the present
line number.
__FILE__ This constant contains the path
and filename of the file
concerned. It is important to
mention here that the path
contained by this constant is the
absolute path.
__FUNCTION__ This constant includes the name of
the function as it was when the
function was declared. The name
is case-sensitive.
__CLASS__ This constant returns the name of
the class concerned in a case-
sensitive manner and exactly in
the manner that it was declared.
__METHOD__ This constant returns the name of
the method concerned in a case-
sensitive manner and exactly in
the manner that it was declared.
Chapter 5: Operators
Whenever an operation needs to be performed, it needs to have operand (s) and an operator that
operates on the operand (s). The commonest example of this concept is addition. When you add two
numbers, say 2 and 3, the numbers are operands and + is the addition operator that words on the
numbers.
Addition is just one of the operations that we perform. There are dedicated operators for all other
operations that you will need to perform for your basic programming tasks. Operators are divided
into five categories, which include conditional operators, logical operators, arithmetic operators,
assignment operators and comparison operators. Each of these categories has been described below.
Arithmetic Operators
All mathematical operations are performed using operators that fall under the category of arithmetic
operators. List of supported operators have been given below.
Addition (+)
This operator performs addition between two numbers. If a and b are two variable holding 5 and 6
respectively. Then, c = a+b, will yield c = 11.
Multiplication (*)
This operator performs multiplication between two numbers. If a and b are two variable holding 5
and 6 respectively. Then, c = a*b, will yield c = 30.
Subtraction (-)
This operator performs subtraction between two numbers. If a and b are two variable holding 5 and 6
respectively. Then, c = a-b, will yield c = -1.
Division (/)
This operator performs addition between two numbers. If a and b are two variable holding 10 and 5
respectively. Then, c = a/b, will yield c = 2.
Modulus (%)
This operator returns the remainder left after dividing the two numbers. If a and b are two variable
holding 10 and 5 respectively. Then, c = a%b, will yield c = 0.
Increment (++)
This operator adds 1 to the value of the variable. If a is a variable holding the value 1, then a++ will
yield the value 2.
Decrement (--)
This operator reduces 1 from the value of the variable. If a is a variable holding the value 1, then a--
will yield the value 0.
Comparison Operators
All operations involving comparison are performed using comparison operators. A list of the
operators supported by this programming language is given below –
NOT EQUAL TO (!=)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns FALSE else it return TRUE.
EQUAL TO (==)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns TRUE else it return FALSE.
GREATER THAN (>)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than the second operand, it returns TRUE else it return FALSE.
LESS THAN (<)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than the second operand, it returns TRUE else it return FALSE.
GREATER THAN OR EQUAL TO (>=)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than or equal to the second operand, it returns TRUE else it return FALSE.
LESS THAN OR EQUAL TO (<=)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than or equal to the second operand, it returns TRUE else it return FALSE.
Logical Operators
All the logical operations in PHP are performed using logical operators. The list of operators
supported by this programming language is given below.
And
This operator works on two operands. If both the operands are non-zero, the expression returns
TRUE else it returns FALSE. Sample usage of this operator is as follows –
(A and B)
Or
This operator works on two operands. If one or both the operands are non-zero, the expression
returns TRUE else it returns FALSE. Sample usage of this operator is as follows –
(A or B)
Logical AND (&&)
This operator works on two operands. If both the operands are non-zero, the expression returns
TRUE else it returns FALSE. Sample usage of this operator is as follows –
(A && B)
Logical OR (||)
This operator works on two operands. If one or both the operands are non-zero, the expression
returns TRUE else it returns FALSE. Sample usage of this operator is as follows –
(A || B)
Logical NOT (!)
This operator works on one operand. If the operand is zero, this expression returns TRUE else it
returns FALSE. Sample usage of this operator is as follows –
(!A)
Assignment Operators
The list of assignment operators supported by PHP include –
Simple Assignment Operator (=)
This operator assigns the value computed by the right hand side to the variable on the left hand side. If
a, b and c are three variable and the expression is c = a+b, then the value of addition of a and b is
assigned to c.
Add AND Assignment Operator (+=)
This operator assigns the value computed by the addition of right hand side and left hand side to the
variable on the left hand side. If a and c are two variable and the expression is c += a, then the value
of addition of a and c is assigned to c.
Subtract AND Assignment Operator (-=)
This operator assigns the value computed by the subtraction of right hand side from left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c -= a, then the
value of c-a is assigned to c.
Multiply AND Assignment Operator (*=)
This operator assigns the value computed by the multiplication of right hand side and left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c *= a, then the
value of c*a is assigned to c.
Divide AND Assignment Operator (/=)
This operator assigns the value computed by the division of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c /= a, then the value
of c/a is assigned to c.
Modulus AND Assignment Operator (%=)
This operator assigns the value computed by the modulus of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c %= a, then the value
of c%a is assigned to c.
Operator Precedence
If an expression uses multiple operators, then operator precedence rules are used to determine the
order to execution of operations. The precedence of operators in terms of whether they will be
evaluated from right to left or left to right is defined for groups of operators in the following manner –
Right to Left
Unary
Conditional
Assignment
Left to Right
Postfix
Multiplicative
Additive
Shift
Relational
Equality
Logical AND
Logical OR
For example, if we have to evaluate the expression a = 3 + 5 * 5, then multiplication is performed
before addition. Therefore, a = 28 instead of 40.
Chapter 6: Decision Making
Several programming scanrios require a decision to be taken on the basis of the truthfulness of a
condition. The programming constructs provided for this purpose are referred to as decision making
statements. PHP supports three decision making constructs namely if, else if and switch. The flow
diagram for these constructs has been illustrated below –
The if…else Statement
This statement is typically used to programming scenario that requires the execution of a block if the
condition being tested is found true. However, if the condition is found false, another code block is
executed. The syntax of this construct is as follows –
if (condition)
Code block to be executed if the condition is found true;
else
Code block to be executed if the condition is found false;
Sample code that implements this concept has been given below for your reference.
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "Thank God It’s Friday!";
else
echo "It is just another day!";
?>
</body>
</html>
Upon execution, this code yields the following result.
A block of code can be executed multiple times using the concept of loops. Four types of loops are
supported by PHP, which include for, while, foreach and do…while. This chapter will discuss each
of these and also introduce you to loops statements like break and continue.
One of the most useful data structures supported by PHP is arrays. An array is a collection of data
elements that are of the same type. For instance, if you wish to store 20 integers, then it can be stored
in an array of 20 elements. You can also look at arrays as a collection of variables of the same type;
each of which is capable of storing data.
PHP supports three types of arrays, which include numeric arrays, multi-dimensional arrays and
associative arrays. The individual elements of the array can be accessed using the index or position
of the element in the array. The three types of arrays differ in the manner their elements are accessed.
Numeric arrays have numeric index that are incremented in a linear fashion. For instance, the first
element of the array has the default index of 0. For all elements succeeding this data value, the index
is incremented by 1.
On the other hand, associative arrays have strings as index. The array is composed in a key-value
fashion and the keys are stored as index while the values are accessed using the keys. Therefore, the
storage of elements and their accessibility is dependent upon the association between the key and
value.
Lastly, an array can be composed of elements each of which is an array in itself. Such an array is 2-
dimensional. Correspondingly, the dimensionality of an array can be increased depending on the
programming requirement. Arrays that have multiple dimensions are called multi-dimensional arrays.
Moreover, the elements of such arrays are accessed using multiple indices.
Numeric Array
Numeric arrays can store any type of data like strings, numbers and objects. However, the only thing
worth remembering is that the array’s indices are numeric. Moreover, the default index of the first
element of the array is zero. The function used to create arrays is array(). Sample code to demonstrate
the functionality of numeric arrays is given below for your reference.
<html>
<body>
<?php
/* Creating arrays using method 1 */
$numberlist = array( 9, 8, 7);
foreach( $numberlist as $value ) {
echo "Value is $value <br />";
}
/* Creating arrays using method 2 */
$numberlist[0] = "nine";
$numberlist[1] = "eight";
$numberlist[2] = "seven";
foreach( $numberlist as $value ) {
echo "Value is $value <br />";
}
?>
</body>
</html>
Upon execution, the following result is generated –
Associative Arrays
Associative arrays are similar to numeric arrays in the way they function. However, their indexing
mechanism is different. They work on the key-value format. Values have keys, which are
The associative arrays are very similar to numeric arrays in term of functionality but they are different
in terms of their index. Associative array will have their index as string so that you can establish a
strong association between key and values.
For instance, if you need a data structure to store the salaries of employees, then the same can best be
done using an associative array. In this case, employee names can be used as keys and salaries as
values. Please note that you must never put associative arrays inside double quotes as they don’t
return any value in that case. Sample code to demonstrate the functioning of associative arrays is
given below –
<html>
<body>
<?php
/*Creating associative array using method 1*/
$salary = array('james' => 20000, 'jacob' => 15000, 'maria' => 7500);
echo "Salary of first employee is ". $salary['james'] . "<br />";
echo "Salary of second employee is ". $salary['jacob']. "<br />";
echo "Salary of third employee is ". $salary['maria']. "<br />";
/*Creating associative array using method 2*/
$salary['james'] = "high";
$salary['jacob'] = "medium";
$salary['maria'] = "low";
echo "Salary of first employee is ". $salary['james'] . "<br />";
echo "Salary of second employee is ". $salary['jacob']. "<br />";
echo "Salary of third employee is ". $salary['maria']. "<br />";
?>
</body>
</html>
Upon execution, the code yields the following result –
Multi-dimensional Arrays
In a multi-dimensional array, every element of the array is also an array. Therefore, a multi-
dimensional array is composed arrays, which in turn can also be made up of arrays. In order to access
elements of a multi-dimensional array, multiple indices must be used. Sample code to demonstrate the
functioning of multi-dimensional arrays is given below –
<html>
<body>
<?php
$marks = array( "mohammad" => array ( "physics" => 35, "maths" =>
30, "chemistry" => 39 ), "qadir" => array (
"physics" => 30, "maths" => 32, "chemistry" => 29 ),
"zara" => array ( "physics" => 31, "maths" => 22, "chemistry" =>
39 ) );
/* Accessing values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
Upon execution, the code yields the following result –
Chapter 9: Strings
The simplest definition of strings is that it is a combination of characters. For instance, ‘Hello
World!’ and “This is a test string” are strings. You will commonly notice the use of single inverted
and double inverted commas. When a string is placed inside single quotes, it is taken literally and
cannot be changed during the course of the program.
On the other hand, the use of double quotes indicates that the string can replace a variable’s value.
Moreover, PHP imposes no limit on the length of a string. However, the memory available on the
system may pose as a limitation. Therefore, as long as the memory can afford it, you can create
arbitrarily long strings.
Strings that appear within double quotes are preprocessed by PHP in one of the following ways: the
strings that are preceded by a backslaash (\) are treated as special characters and interpreted
accordingly whereas strings that are preceded by dollar sign ($) are treated as variable names. Some
of the commonly used escape sequences include \n (newline), \r (carriage return), \$ (dollar sign) and
\t (tab).
This chapter demonstrates how some common string operations can be performed in PHP.
Concatenating Strings
In order to concatenate strings, PHP’s dot (.) operator can be used. Sample code to illustrate how this
function can be performed is given below –
<?php
$string_1="Hello World!";
$string_2="9876";
echo $string_1 . " " . $string_2;
?>
Upon execution, this code shall give the following result –
You can notice the use of dot (.) operator twice in the code given above. The first dot operator
concatenates string_1 with the blank space string (“ “) and the second concatenates the resultant string
from this operation with string_2.
this function is typically used in programming scenarios that implement loops and need to know when
and where a string is ending to control execution.
A function is an independent block of code that takes input in the form of parameters and returns a
result to the caller. In other words, a function can also be described as a block of code that performs a
specific function. Functions in PHP are no different than functions in any other programming language.
We have already looked at some functions in the chapter on strings like strlen() and strpos(). While
these functions are inbuilt functions available as part of the PHP package, this programming language
also gives you the option to create your own functions and use them at your own free will.
There are two main facets of functions, in any programming language. Firstly, functions need to be
created before they are used. Therefore, creation of a function is the first facet. Secondly, functions
need to be used by calling them from another function or block of code. Each of these facets will be
dealt with in detail in the sections that follow.
Content from one PHP file can be included into another PHP file before it gets executed at the server.
In order to perform this operation, PHP provides two functions namely include() and require(). This
is a way in which PHP allows reusability of code. Moreover, elements like headers, footers and
functions can be directly imported from one file to another file and thus, they can be used on multiple
pages.
Apart from supporting code reusability, this functionality of PHP also allows easy code management
in the sense that the whole look of the website can be easily changed without putting in much effort. In
order to implement a change, all you need to do is change the file that is included for it.
File I/O
This section of this chapter deals with opening, closing, reading and writing of files. There are
dedicated functions for performing these operations in PHP. In order to open a file, fopen() can be
used. Calling this function typically requires two parameters namely filename and the mode in which
the programmer wishes to open the file. The different modes available in PHP are as follows –
Mode Function
r This mode opens the file for only
reading. The file pointer points to
the first character of the file.
r++ This mode opens the file for
reading as well as writing. The
file pointer points to the first
character of the file.
w This mode opens the file for only
writing. The file pointer points to
the beginning of the file.
Moreover, the file length is
truncated to zero. In case the file
does not exist, then the system
tries to create a file.
w++ This mode opens the file for only
writing and reading. The file
pointer points to the beginning of
the file. Moreover, the file length
is truncated to zero. In case the
file does not exist, then the system
tries to create a file.
A This mode opens the file for only
writing. The file pointer points to
the end of the file. In case the file
does not exist, then the system
tries to create a file.
a++ This mode opens the file for only
writing and reading. The file
pointer points to the end of the
file. In case the file does not exist,
then the system tries to create a
file.
If the requested file is successfully opened, the file pointer for the filr is returned. On the other hand,
if the file opening operation fails, FALSE is returned to the calling function. As a rule, be sure to
close any file that you open. The function used for this purpose is fclose(), which has been discussed
below.
Once a file is open, one of the operations that you will perform is file reading. This is typically done
using fread(), which requires two arguments namely, file pointer and file length in bytes. If the size of
the file is unknown, you can use filesize() function to determine the same and only requires the
filename as argument. In order to read a file, the steps that you will need to follow include –
Opening the file using fopen()
Determining the size of the file using filesize()
Reading the contents of the file using fread()
Closing the file using fclose()
Sample code for demonstrating the different steps involved in the process has been provided below
for your reference.
<html>
<head>
<title>Demo for reading a file</title>
</head>
<body>
<?php
$file_name = "tmp.txt";
$file1 = fopen( $file_name, "r" );
if( $file1 == false ) {
echo ( "Cannot open file" );
exit();
}
$file_size = filesize( $file_name );
$file_text = fread( $file1, $file_size );
fclose( $file1 );
echo ( "Size of File : $file_size bytes" );
echo ( "<pre>$file_text</pre>" );
?>
</body>
</html>
You can run this code to see the output it generates. If the file is not present, the program shall give an
error message else it shall provide you the desired output.
The other function that you can expect to perform with files is writing. It is possible to rewrite a file
or append the same on need basis. The function used for this purpose is fwrite(), which requires two
arguments namely filepointer to the file and the string that needs to be written to the file.
Besides this, this function also expects a third argument, which is the length of data that is to be
written. Typically, if you provide this argument, writing to the file will stop as soon as the number of
bytes specified in datasize is reached.
Chapter 12: Web Concepts
With the rising popularity of Internet, there has been an increasing need for dynamic content and
webpages that can react to user input, randomly generated numbers and dynamically adapt to different
web browsers. Redirection of client browser is also an important concept in this regard that has been
dealt with in this chapter.
HTML Forms
The first and foremost thing to understand while working with PHP and HTML Forms is that eevry
single element of the HTML Form shall be available to you within your PHP script. You can see it for
yourself by creating a file named test.php and writing the following code in it.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("Name is invalid!");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
the form created using this script will have a submit button. Upon clicking the button, the default PHP
variable named $_PHP_SELF will be called. The code also makes use of methods POST and GET.
We shall talk about these in detail in the next chapter.
Browser Redirection
Raw HTTP headers are provided by the header() function to the browser. This function can also be
used to redirect the browser to another location. In order to avoid loading of the different elements of
the page before redirection occurs, the redirection code must be placed at the top of the page.
The Location: header, which is the argument to the header() is sed to specify the target. The use of
exit() after this function is recommended to avoid any further parsing of code. Sample code for
redirection is provided below for your reference.
<?php
if( $_POST["location"] ) {
$location = $_POST["location"];
header( "Location:$location" );
exit();
} ?>
<html>
<body>
<p>Choose the site you wish to visit :</p>
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method ="POST">
<select name = "location">.
<option value = "http://www.google.com"> Google.com </option>
<option value = "http://www.yahoo.com"> Yahoo.com </option>
</select>
<input type = "submit" />
</form>
</body>
</html>
Chapter 13: GET and POST Methods
The client browser uses two methods to send information from the client to the web server. These
methods are GET and POST. However, before sending the information, the browser first encodes the
information using the coding scheme called URL encoding.
In this coding scheme, key-value pairs, which are here name-value pairs, are combined together in
such a way that different name-value pairs are separated by & (ampersand). Any whitespaces are
replaced by the plus sign (+) and non-alphanumeric characters are replaced with their hexadecimal
values. Once the encoding process is over, the data is sent to the web server.
Conclusion
Now that we have reached the end of this book on PHP programming, we hope that this book has
helped you gain expertise in the fundamentals of this programming language. You can take this journey
of learning forward by moving to the advanced concepts of PHP.
Learning is a lifelong process and as you will practice programming in PHP, you will get you know
more about the programming language and what it offers to the developers. Moreover, the
functionality of what has been taught in this book will only find ground once you implement the given
concepts.
Moving forward, we recommend you to run the sample codes given in this book and edit or improve
them according to you understanding. This will give you a good hang of the PHP ecosystem. Besides
this, the world of PHP is too wide and huge to be covered in a simple book. You will learn as you
practice. We hope you enjoyed reading this book and any feedback is most welcome.
C++
Introduction
Bjarne Stroustrup developed C++ at Bell Labs in the year 1979. C++ is a middle level programming
language that supports varied platforms like Mac OSX, Unix and Windows, in addition to a few
others. This book is an introductory tutorial on C++ and is designed for beginners with little to no
background of the programming language.
This book follows a practical and simple approach to C++. We have included executable examples
along with screenshots of the execution to help you run the examples for yourself and execute them.
This will give you a hands-on experience of C++ programming language as well as its environment,
which shall prepare you well for any advanced learning in the same.
Although, this book does not require you to have any prior knowledge of C++, knowledge of basic
programming languages and computer programs is highly recommended. You can simply follow the
book as a step-by-step guide, moving from one example to the next, as you read the theory related to
it. Nothing teaches any programming language fundamentals better than writing and executing
programs in the same. We hope you will like the book. With you bug-less programming!
C++ is a programming language that can be used for object-oriented, procedural as well as generic
programming. It’s ability to support all these programming forms can be attributed to the fact that C++
has features corresponding to both low level and high level programming languages. This
programming language is a enhanced version of C, which was developed by Bjarne Stroustrup in the
year 1979 at Bell Labs. However, it was initially named C with classes, which was changed in 1983
to C++.
It is a middle–level language that is free-form, statically-typed and case-sensitive. The type checking
for this programming language is performed at the time of compilation and not at the time of
execution. Moreover, it is compiled and not interpreted. As mentioned previously, C++ is an
enhanced version of C and any C program is a C++ program also. The program can be compiled and
executed in the C++ environment just like it is done in a C programming environment. Lastly, all the
object-oriented features like inheritance, polymorphism, data hiding and encapsulation are supported.
The C++ paclage includes three main components, which include the core language elements like data
types, literals and variables, the standard library and standard template library or STL. The C++
standard library includes functions that are used for manipulating objects like files and strings.
Besides this, C++ also includes a library of rich methods for manipulating data structures, in addition
to other such elements of the programming language.
Why C++?
C++ is a programming language that can be used to program in many different methodologies. With
that said, the change in programming style does not affect the efficicency or time-effectiveness of the
program. Moreover, it is used for designing new systems as well as maintain old systems. it is for all
these reasons that C++ is a popular programming language.
Another important aspect of its popularity is the multi-faceted use of this programming language. C++
can be used for writing programs that manipulate the hardware like device drivers as well as creating
user interfaces for user-system interaction. Besides this, C++ is one programming language that is
taught as part of any computer science course because of the sheer utility and widespread use of this
programming language.
Environment Setup
In order to run C++ programs, you will need to set up the C++ programming environment on your
system. However, you may also choose the online option to avoid the hassle of installing software
and compilers. Due to the heavy dependence of the online solution on the availability of a good
Internet connection, it is always good to have a setup that can work for you even if Internet is not
working.
In order to create a local environment setup for C++, you need two software solutions. Firstly, you
require a text editor, which can be used for writing C++ programs. If you are using Windows,
Notepad will do the job for you. However, if you are working on Linux or Mac, you will have to
explore options like VI editor and TextEdit. All the C++ files need to be stored using the .cpp
extension.
Next, these programs will then be compiled and executed using the C++ compiler. The most popular
compiler used for this purpose is the GNU C/C++ compiler. It is simple to install these compilers on
your system. All you need to do is follow their tutorial or instructions for installation and you should
be good to go.
Chapter 2: Syntax
Assuming that you have your system ready with the text editor and compiler, if you are using the local
setup, we move on to the basic of C++ programming language. The first thing that you need to learn
about any programming language is the syntax. This chapter shall help you learn the syntax and get
started with C++ programming.
A C++ Program
You cannot hope to learn any programming language unless you look at the code and are comfortable
with the look and feel of it. You have to code it to know it! The simplest program in C++ that we will
introduce here is the program that prints Hello World! The sample code has been given below –
#include <iostream>
using namespace std;
/*This is my first C++ program*/
int main() {
cout << "Hello World!"; //This line prints the text
return 0;
}
The output of the code shall look like this –
Going into the details of what this code does and how it works, the first like of the program includes a
library file named iostream. This file is required to perform any input/output operation in the
program. Generally, you must declare all the header files that your program requires at the beginning
of the program. The next line tells the system to use the namespace std.
Mentioning this is important in view of the fact that most of the functions and methods that are used
from the libraries are available under this namespace. You may have a namespace of your own, with
the functionalities you require, implemented as part of it. Execution always begins from the main()
method. Therefore, all your programs must have a main method that returns an int value. Notice the
return statement at the end of the program. Your program must return an integer or you will receive a
warning for it.
The main statement that prints the required text on the screen is the cout statement. It has a string
combination that is placed within double inverted commas. Anything that is placed within these
double inverted commas as part of the cout statement are printed on the screen. Notice the placement
of two comments in the program. One of the comments is placed inside /* and */ character
combination while the other comment follows the // character combination.
The former is a multi-line comment. The comment starts after the /* character combination and ends
wherever */ is encountered. On the other hand, the latter is a single-line comment. The comment, in
this case, starts after the // character combination and terminates as and when the newline character is
encountered. Another important thing to notice in the program is the use of semi-colon at the end of
every statement. A C++ statement must terminate with a semi-colon.
Your C++ program can have any number of whitespaces and blank lines. The compiler simply ignores
them. Besides this, you can see that the C++ statements inside the main() function are enclosed inside
curly brackets. This is referred to as a block. As a rule, all logically-related statements are kept
inside one block. In order to compile and execute this C++ program, open the text editor and write
this program in it. You need to save the file with the extension .cpp. For instance, you can name this
file as sample.cpp. Compile and execute this file to see the desired results.
Identifiers
An important element of a C++ program that has not been used in the sample program is identifier.
Identifier is a name given to a function, variable or class and can be described as a combination of
characters, numbers and underscore. As a rule, an identifier can begin with an underscore or
character. Never use an identifier that starts with a numeral. You may use capital and small-case
alphabets. C++ is case-sensitive. Therefore, iden and Iden are two different identifiers for the system.
Besides this, the use of any other special characters or punctuations within an identifier is prohibited.
Keywords
While naming identifiers, it is important to note that the name must not be same as a keyword.
Keywords are reserved words that C++ uses for its function implementation. A list of keywords is
give below for your reference.
In order to help you understand this concept, let us take the example of a class called table, which has
the variables named length, breadth, height, wood, color and type. Besides this, it has a method that
can be used to initialize a table. Evidently, this is a template or a form that needs to be filled for any
new table. So, when you create a table, you instantiate an object of the class table and initialize the
variables described above using the method that the class includes for it.
Chapter 3: Data Types
As you will graduate to writing more complicated programs, you will realize that you need variables
for storing information. For instance, if you wish to add two numbers, then you need two variables
that can store these two values and then, another variable for storing the resultant.
Each variable has a type and the type determines the number of memory locations in the physical
space that need to be reserved for that variable. For instance, variables can store characters, integers,
floats, boolean and strings. The identifier used for referring to this variable is called the variable
name. C++ supports built-in as well as user-defined data types. Each of these classes have been
discussed in this chapter.
Like we mentioned previously, a variable is an entity that stores variables and has a data type. As a
rule, all variables used in a program must be declared. When we declare a variable, we basically tell
the compiler that the variable must have the specified amount of memory allotted to it as it is expected
to store values of the specified type. The syntax for defining a variable is as follows –
data_type var_name;
Here, data_type is the data type and var_name is the name of the variable. It is crucial to note here
that data_type must be a valid data type or else you can expect an error message for the same. Sample
declaration is given below –
int x;
You can also declare multiple variables in the same line, as it is shown below –
int x, y, z;
Here, x, y and z are three variable, which are declared as integers. Now that you know how to
declare variables, let us see how we can assign values to these variables. For example, if we wish to
assign the value 0 to x, 1 to y and 2 to z, then I can place these statements in my code,
x=0;
y=1;
z=2;
Declaration and initialization can be clubbed together in the following manner –
int x=0, y=1, z=2;
if you don’t initialize the variables, default or garbage values are stored into them. If the variables are
declared as ‘static’, then they are initialized with the value NULL or zero. On the other hand, all other
variables contain garbage values. Be sure to realize this fact as it may lead to many logical errors in
the code.
The variable declaration statement is checked for at the time of compilation. However, actual
variable definition is required only at the time of linking. This is particularly the case for global
variables that are declared in one file and used in many other files. Such variables are declared using
the extern keyword.
#include <iostream>
using namespace std;
// Declaration of the variables x, y, z and a
extern int x, y;
extern int z;
extern float a;
int main () {
// Definition
int x, y;
int z;
float a;
// Initialization
x = 5;
y = 10;
z = x + y;
cout << z << endl ;
a = 55.0/2.0;
cout << a << endl ;
return 0;
}
When this code is compiled and executed, the following result is obtained.
Scope of Variables
Every variable has a scope or a region in which it remains valid. Broadly, there are two types of
scopes namely, local and global variables. Besides this, there is also a third type of scope, which is
formal parameters. Local variables are declared inside a block and they are accessible only within
that block. The following code uses three local variables namely x, y and z and performs
multiplication of x and y; the result of which is stored in z.
#include <iostream>
using namespace std;
int main () {
// Declaration of local variables
int x, y;
int z;
// Initialization of local variables
x = 5;
y = 7;
z = x * y;
cout << z;
return 0;
}
The output of the code can be seen in the image given below.
On the other hand, global variables are not block-dependent and are accessible to all the blocks and
functions. Lastly, formal parameters are parameters that are imported into a function. They are treated
as local variables to the function and are accessible inside the function only.
#include <iostream>
using namespace std;
// Declaration of global variable
int g_var;
int main () {
// Declaration of local variables
int l_var1, l_var2;
// Initialization of local variables
l_var1 = 5;
l_var2 = 7;
/* The resultant of addition of two local variables saved into a global variable */
g_var = l_var1 + l_var2;
cout << g_var;
return 0;
}
The output of the code is as follows –
This may bring into question a scenario when a local variable has the same name as a global variable
and is accessed inside its scope. In this case, the local variable gets preference. Sample code to
illustrate how this works has been provided below.
#include <iostream>
using namespace std;
// Declaration of global variable
int g_var = 20;
int main () {
//Declaration of local variable of the same name
int g_var = 10;
cout << g_var;
return 0;
}
The result of the execution of this code is given below.
It is crucial to mention here that local variables contain garbage values if they are only declared and
not initialized. On the other hand, global variables are initialized by the value zero (if number) or
NULL (if character). With that said, it is considered a good programming practice to initialize
variables whenever you declare them.
Type Qualifiers
Another concept in C++ that holds importance here is that of type qualifiers. There are three type
qualifiers in C++ namely, const, restrict and volatile. The use of const will be discussed later in this
book. The restrict qualifier restricts access to the value by only allowing the pointer declared as
restricted to be used for the access. Volatile keyword is usually used to indicate that the variable
concerned can be altered in different ways by the program.
Storage Classes
A storage class is a method by which the lifetime and scope of the variable can be modified. The
storage class of a variable is specified as the first word in the declaration of the variable. The storage
classes available in C++ are auto, mutable, extern, register and static. Each of these classes has been
discussed in detail below.
Auto Class
This is the default storage class for all local variables. Moreover, this storage class can only be used
inside functions for variables local to the function. Sample declaration for the same is as follows –
auto int a = 0;
Register Class
Variables declared as belonging to the register class are stored in the register instead of RAM. This
poses several limitations on the variables. Firstly, the variable cannot be longer than a word. Besides
this, applying the unary & operator on the variable is not allowed as it does not have a memory
location. Sample declaration for such a variable is given below –
register int x;
Declaring a variable as register does not guarantee its storage in the register. It just means that you
want the variable to be stored in the register and the same will be done if a register is available. This
storage class is typically used for variables that are required to be accessed quickly and many times
in the program, as is the case of counters.
Static Class
The scope of a static variable is not block-dependent and the variable remains alive throughout the
lifetime of the program. Therefore, if you make a local variable static, only one copy of the variable
is saved for any number of function calls made to the function inside which this variable exists.
Another usage of this modifier lies in the case of global variables. A global variable declared as
static is available only inside the file that it exists. Besides this, if a class member is declared as
static, only one copy of this member is stored across any number of objects that may have been
created for the same.
Extern Class
The extern storage class creates a reference to the global variable for which it is used and the
variable can now be accessed from any number of files. However, once defined, this variable cannot
be defined again. This storage file is typically used for global variables that need to be used beyond
the scope of one file.
Mutable Class
This class is specifically used with class objects and allows the modification of the mutable member
by any const member function of the class.
Chapter 5: Constants or Literals
Constants or literals are identifiers that are assigned fixed values. The program is not allowed to alter
these values under any circumstance. In the event that a program attempts to alter the value of a
constant or literal, an error message is flashed. With that said, they are exactly like regular variables
and have a data type. They are also declared and initialized like regular variables.
Integer Literals
A literal that is decimal, octal or hexadecimal is referred to as an integer literal. The preceding
numbers or digits indicate the base of the literal. For instance, 0 precedes octal numbers while
hexadecimal literals have 0X before them. If a literal doesn’t have any prefix, then it is decimal.
Literals may also have suffixes like L or U, which indicate if a literal is long or unsigned,
respectively.
Boolean Literals
A Boolean literal is only allowed to have two values. Therefore, there are only two types of Boolean
literals namely, true and false. However, do not assume true to be equal to 1 and false toe be same as
0.
Character Literals
It is a practice to enclose character literals within single inverted commas. A character literal can
store characters, special characters and universal characters. A list of special character sequences
has been given below for your reference.
\\ \ character
\? ? character
\b Backspace
\a Alert or bell
\n Newline
\f Form feed
\t Horizontal tab
\r Carriage return
\v Vertical tab
The functionality of escape sequences can be understood by running the following code.
#include <iostream>
using namespace std;
int main() {
cout << "Hello\t\t\tWorld\n\n\n!";
return 0;
}
When you execute the code, you will see that Hello and World are separated by three tabs and the
exclamation sign appears after three newlines.
String Literals
When you have to declare string literals or character sequences, you must do so within double
inverted commas. The string can be a sequence of characters and special characters. Moreover, it can
also be multiple lines that are separated using the newline special character or a character with many
white spaces.
The second method makes use of preprocessor directives. The syntax to define a
preprocessor directive is as follows –
#define name val
Here, name is the identifier and val is the value that you expect it to contain. Sample
implementation of this concept is given below –
#include <iostream>
using namespace std ;
#define SIDE 15
#define NEWLINE '\n'
int main () {
int sq_area ;
sq_area = SIDE * SIDE ;
cout << sq_area ;
cout << NEWLINE ;
return 0 ;
}
The output for this program is shown in the image given below.
Please note that it is considered a good programming practice to write the name of literals or
constants in capital letters.
Chapter 6: Operators
In order to perform logical and mathematical manipulation on variables and values, an entity called
operators is used. C++ supports many types of operators including arithmetic, logical and bitwise
operators. Each class of operators is discussed in detail below.
Arithmetic Operators
All mathematical operations are performed using operators that fall under the category of arithmetic
operators. List of supported operators have been given below.
Addition (+)
This operator performs addition between two numbers. If a and b are two variable holding 5 and 6
respectively. Then, c = a+b, will yield c = 11.
Multiplication (*)
This operator performs multiplication between two numbers. If a and b are two variable holding 5
and 6 respectively. Then, c = a*b, will yield c = 30.
Subtraction (-)
This operator performs subtraction between two numbers. If a and b are two variable holding 5 and 6
respectively. Then, c = a-b, will yield c = -1.
Division (/)
This operator performs addition between two numbers. If a and b are two variable holding 10 and 5
respectively. Then, c = a/b, will yield c = 2.
Modulus (%)
This operator returns the remainder left after dividing the two numbers. If a and b are two variable
holding 10 and 5 respectively. Then, c = a%b, will yield c = 0.
Increment (++)
This operator adds 1 to the value of the variable. If a is a variable holding the value 1, then a++ will
yield the value 2.
Decrement (--)
This operator reduces 1 from the value of the variable. If a is a variable holding the value 1, then a--
will yield the value 0.
Relational Operators
All operations involving comparison are performed using relational operators. A list of the operators
supported by this programming language is given below –
NOT EQUAL TO (!=)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns FALSE else it return TRUE.
EQUAL TO (==)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns TRUE else it return FALSE.
GREATER THAN (>)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than the second operand, it returns TRUE else it return FALSE.
LESS THAN (<)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than the second operand, it returns TRUE else it return FALSE.
GREATER THAN OR EQUAL TO (>=)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than or equal to the second operand, it returns TRUE else it return FALSE.
LESS THAN OR EQUAL TO (<=)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than or equal to the second operand, it returns TRUE else it return FALSE.
Bitwise Operators
The only difference between normal operators and bitwise operators is that these operators perform
operations bit-by-bit. Moreover, these operators can be applied on byte, int, short, long and char. The
list of bitwise operators supported in Java include –
Bitwise AND (&)
This operator works on two operands and the output for each set of input bits is 1 if both the inputs
are one else the output is zero.
Bitwise OR (|)
This operator works on two operands and the output for each set of input bits is 1 if one or both of the
inputs is one else the output is zero.
Bitwise XOR (^)
This operator works on two operands and the output for each set of input bits is 1 only if one of the
inputs is one else the output is zero.
Bitwise COMPLEMENT (~)
This operator works on a single operand and negates the values from 0 to 1 and from 1 to 0.
LEFT SHIFT (<<)
This operator works on two operands. The bits of the left operand are shifted left. The number of
places is equal to the number specified as value for the second operand.
RIGHT SHIFT (>>)
This operator works on two operands. The bits of the left operand are shifted right by the number
specified as value for the second operand.
In order to understand how bitwise operations take place, let us take an example. Assume two
variables, a and b, having the values 60 and 13 respectively. The binary equivalent of a and b are as
follows –
a = 00111100
b = 00001101
Using the AND truth table according to which the output is 1 only if both the inputs are 1.
Correspondingly, the output of a&b = 00001100. Similarly other bitwise operations can also be
performed.
Logical Operators
All the logical operations in Java are performed using logical operators. The list of operators
supported by this programming language is given below.
Logical AND
This operator works on two operands. If both the operands are non-zero, the expression returns
TRUE else it returns FALSE.
Logical OR
This operator works on two operands. If one or both the operands are non-zero, the expression
returns TRUE else it returns FALSE.
Logical NOT
This operator works on one operand. If the operand is zero, this expression returns TRUE else it
returns FALSE.
Assignment Operators
The list of assignment operators supported by Java include –
Simple Assignment Operator (=)
This operator assigns the value computed by the right hand side to the variable on the left hand side. If
a, b and c are three variable and the expression is c = a+b, then the value of addition of a and b is
assigned to c.
Add AND Assignment Operator (+=)
This operator assigns the value computed by the addition of right hand side and left hand side to the
variable on the left hand side. If a and c are two variable and the expression is c += a, then the value
of addition of a and c is assigned to c.
Subtract AND Assignment Operator (-=)
This operator assigns the value computed by the subtraction of right hand side from left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c -= a, then the
value of c-a is assigned to c.
Multiply AND Assignment Operator (*=)
This operator assigns the value computed by the multiplication of right hand side and left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c *= a, then the
value of c*a is assigned to c.
Divide AND Assignment Operator (/=)
This operator assigns the value computed by the division of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c /= a, then the value
of c/a is assigned to c.
Modulus AND Assignment Operator (%=)
This operator assigns the value computed by the modulus of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c %= a, then the value
of c%a is assigned to c.
Left Shift AND Assignment Operator (<<=)
If a and c are two variable and the expression is c <<= a, then the value of c<<a is assigned to c.
Right Shift AND Assignment Operator (>>=)
If a and c are two variable and the expression is c >>= a, then the value of c>>a is assigned to c.
Bitwise AND Assignment Operator (&=)
If a and c are two variable and the expression is c &= a, then the value of c&a is assigned to c.
Bitwise XOR AND Assignment Operator (^=)
If a and c are two variable and the expression is c ^= a, then the value of c^a is assigned to c.
Bitwise Inclusive OR and Assignment Operator (|=)
If a and c are two variable and the expression is c |= a, then the value of c|a is assigned to c.
Miscellaneous Operators
In addition to the above-mentioned, there are a few more operators that do not fall under any
specified category. These operators are –
sizeof
The sizeof operator is used to determine the size of the variable that is passed as argument to it. The
syntax for using the sizeof() operator is –
X = sizeof(a); //Now variable X will contain the size of the variable a
Conditional Operator (?:)
The conditional operator is the replacement of a simple if-else statement. The syntax of the
conditional operator is –
condition?a:y;
When ths C++ statement is given, it checks the condition for truthfulness. If the condition is true,
expression corresponding to a is executed else the expression corresponding to b is executed.
Comma Operator (,)
A sequence of operations are performed when the comma operator is used. the value returned by the
expression separated by commas is the value of the last expression in the list.
Dot (.) and Arrow (->)
These operators are used to access class members associated with objects, structures and unions.
Cast
Cast operator coverts the data type of the variable or value that is sent to it as a parameter. For
instance, the value returned by the expression int(3.5) is 3. The expression typecasts the floating point
number 3.5 into an integer.
Pointer Operator (& and *)
The * operator is used to indicate a pointer to a variable. For instance, *p is a pointer variable. On
the other hand, & operator is used to determine the address of a variable. For instance, &a will return
the memory address corresponding to a.
Operator Precedence
If an expression uses multiple operators, then operator precedence rules are used to determine the
order to execution of operations. The precedence of operators in terms of whether they will be
evaluated from right to left or left to right is defined for groups of operators in the following manner –
Right to Left
Unary
Conditional
Assignment
Left to Right
Postfix
Multiplicative
Additive
Shift
Relational
Equality
Bitwise AND
Bitwise XOR
Bitwise OR
Logical AND
Logical OR
For example, if we have to evaluate the expression a = 3 + 5 * 5, then multiplication is performed
before addition. Therefore, a = 28 instead of 40.
Chapter 7: Loop Constructs
The fundamental structure that is available in almost all programming languages is loops. It forms the
core of programming and have been discussed in detail in this chapter. In your programming
endeavours, you will experience several situations where you will be required to execute a set of
statements, a specified number of times. While most old programming languages have a goto label
that allows you to redirect control for repetetive execution, it is not considered a good programming
practce to use the same.
In order to prevent the usage of goto statement for such purposes, loops were introduced. C++
supports four types of loops, which are as follows –
For Loop
The for loop allows the programmer to specify a variable and condition. The variable can be
initialized and updated as part of the for statement. Moreover, the for statement also check the
condition and the for block is executed only if the condition is true. The syntax for implementing the
for loop is as follows –
for(data_type var_name = init_val; condition; var_name update expression){ … }
Here, data_type is the data type of the variable called var_name, which is updated using the
expression given in the last section of the for statement. The condition to be checked for executing the
for block is mentioned in the middle section of the for statement. Sample implementation of the for
loop is as follows –
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "Outside Loop \n";
for (i = 1; i <= 5; ++i) {
cout<< "Inside Loop for i = ” << i << ‘\n’;
}
return 0;
}
The result of the execution of this program is as follows –
While Loop
While is a comparatively simpler construct that only checks the truthfulness of a condition for
executing the while block. If the specified condition is found true, the block executes else it breaks.
The syntax for implementing the while loop is as follows –
while(condition){ … }
Here, the condition to be checked for executing the while block is mentioned in the while statement.
Sample implementation of the for loop is as follows –
#include <iostream>
using namespace std;
int main()
{
int i = 1;
cout << "Outside Loop \n";
while (i <= 5) {
cout<< "Inside Loop for i = " << i << '\n';
i++;
}
return 0;
}
The result of the execution of this program is as follows –
Do…While Loop
Do…while loop is a variant of the while loop, which executes at least once irrespective of whether
the specified condition is true or false. The condition is checked at the end of the first execution of the
block when the while statement is encountered. The syntax for implementing the do…while loop is as
follows –
do { … } while(condition);
Here, the condition to be checked for executing the while block is mentioned in the while statement.
Sample implementation of the for loop is as follows –
#include <iostream>
using namespace std;
int main()
{
int i = 1;
cout << "Outside Loop \n";
do {
cout<< "Inside Loop for i = " << i << '\n';
i++;
}while (i <= 5);
return 0;
}
The result of the execution of this program is as follows –
Nested Loop
One of more loops of any type, be it for, while or do…while can be used inside each other to form a
nested loop. There is no limitation on the number of loops that are allowed.
Another important construct as far as core programming elements are concerned, is decision making
construct. In a decision making construct, the programmer can specify the condition that needs to be
tested and the set of statements that must be executed if the condition is true. Moreover, the
programmer can subsequently also specify the set of statements that must be executed if the condition
is false.
C++ supports five types of decision making constructs, each of which has been described below.
If statement
The if statement is the simplest decision making construct that tests the condition, which appears in
the if statement. If the condition is found true, the block of statements that follow the if statement is
executed. Sample implement for the if statement is given below.
#include <iostream>
using namespace std;
int main()
{
int i = 1;
if (i == 1) {
cout << "Inside If Block \n";
}
return 0;
}
The output for this code is shown in the image given below.
If else statement
The if else is an enhancement of the simple if decision making construct that tests the condition, which
appears in the if statement. If the condition is found true, the block of statements that follow the if
statement is executed. On the other hand, if the condition is found false, the block of statements that
follow the else statement are executed. Sample implement for the if else statement is given below.
#include <iostream>
using namespace std;
int main()
{
int i = 1;
if (i == 0) {
cout << "Inside If Block \n";
}
else {
cout << "Inside Else Block \n";
}
return 0;
}
The output for this code is shown in the image given below.
Nested if statements
You can have multiple if statements, obe inside another to test multiple conditions. There is no limit
of the amount of nesting that can be performed for if. However, the higher the number of ifs inside one
another gets, the time complexity of the program increases. Sample code for implementing the nested
if is as follows –
#include <iostream>
using namespace std;
int main()
{
int i = 1;
int j = 1;
if (i == 1) {
cout << "Inside If Block 1\n";
if (j == 1) {
cout << "Inside If Block 2\n";
}
}
return 0;
}
The output generation upon the execution of this code can be seen in the image given below.
Switch statement
In order to mitigate the complexity challenges associated with nested if statements, C++ also provides
switch statement, which can test a variable for multiple values and execute corresponding statements
for the same. This construct internall creates a table, which is used for the execution. As a result,
execution is faster and more efficient that the nested if. The syntax for implementing switch statement
is as follows.
Switch (variable) {
Value1:
Statements
Value2:
Statements
Value3:
Statements
default:
Statements
}
A sample implementation of the switch statement is given below.
#include <iostream>
using namespace std;
int main()
{
int i = 3;
switch (i){
case 1:
cout << "Value entered is 1";
break;
case 2:
cout << "Value entered is 2";
break;
case 3:
cout << "Value entered is 3";
break;
default:
cout << "Value entered cannot be identified by the switch block";
break;
}
return 0;
}
The output generated on the execution of the code is as follows –
Some programs may include complex tasks and as a result, they may become really long. Moreover,
these tasks may have to be performed repetetively. For instance, tasks like addition, factorial
determination and many other similar mathematical functions are used commonly in computation. It is
better to write a code and call it than to write the same code again and again. It is mere wastage of
programming effort and increases the number of lines of code.
Besides this, it is a good programming practice to divide a big task into small manageable tasks.
Modularization of code makes it readable, easy to understand and maintainable in the long run. It is
for these reasons that the concept of functions has been introduced in programming languages. Just
like the main function that we have implemented in almost every example that we have written, other
functions with task-specific implementation can also be written.
A function can be best decribed as a block of code that performs a specific task and need to be
declared and defined as part of the C++ code. The function declaration includes the return type,
function name and parameters. On the other hand, the actual body of code that contains the
implementation of the task to be performed is referred to as function definition.
Implementing Functions
Functions may be referred by many names. They are also known by names like procedure, sub-routine
and method. Many functions have been implemented and are available as part of the C++ standard
library. You will encounter and use many of these functions in the chapters that follow. The syntax for
implementing a function is as follows –
ret_type f_name( list of parameters ) {
//Body
}
Here, ret_type is the return type of the function, f_name is the name of the function and list of
parameters entails the parameters that the function is expected to take. The list of parameters that are
passed to a function must be same in number, order and type as that mentioned in the function
implementation.
Moreover, there may be functions that do not have any parameters and no parameters need to be
passed to them for invokation. The function statement is commonly also called the function header
while the implementation of the function is called function body. In order to help you understand this
better, let us look at the sample implementation of a function that determines the maximum value out of
the two values provided to it and returns the maximum value as result.
int maximum_value(int number_1, int number_2) {
int max_val;
if (number_1 > number_2)
max_val = number_1;
else
max_val = number_2;
return max_val;
}
Calling a Function
In order to call a function, we need to invoke the function by mentioning its name and giving a list of
parameters that the function will process. Whenever a function call is made or the system sees that a
function name along with the parameters has been mentioned, it simply transfers control to the called
function.
All the statements given in the body of the function are sequentially executed to perform the required
task. As and when, a return statement is encountered, the control is transferred back to the calling
function and normal course of execution is followed. In case a function does not return anything or is
a void function, then the closing brace of the function transfers control back to the calling function.
The following code calls the function that we implemented previously in this chapter.
#include <iostream>
using namespace std;
// Function declaration
int maximum_value(int number_1, int number_2);
int main () {
int x = 25;
int y = 76;
int ret_val;
// Function called
ret_val = maximum_value(x, y);
cout << "Maximum Value = " << ret_val << endl;
return 0;
}
//Function definition
int maximum_value(int number_1, int number_2) {
int max_val;
if (number_1 > number_2)
max_val = number_1;
else
max_val = number_2;
return max_val;
}
The output of the code is shown in the image given below.
A function can be called in three ways namely, call by value, reference and pointer. All these methods
have been decsribed below.
Call by Value
When a variable is passed as parameter to the function, the system makes a copy of the value of the
parameter and send the same to the function for processing. The value of the parameter is not updated
and hence, the return value is the only way you can check if any processing has occurred.
Call by Pointer
In call by pointer, the address of the parameter is passed into the parameter of the function. Therefore,
any changes made to the value that this address holds, by the function concerned, reflect in the
variable’s value. In this manner, multiple values can be returned from the function indirectly; one
using the return statement and others by accessing the variables that have been manipulated.
Call by Reference
In call by reference, a reference to the variable is passed into the parameter of the function.
Therefore, any changes made to the value that this reference holds, by the function concerned, reflect
in the variable’s value. In this manner, multiple values can be returned from the function indirectly;
one using the return statement and others by accessing the variables through references that have been
manipulated.
The default mode of operation in C++ is call by value, that is the variable’s original value is not
manipulated by the called function.
The most fundamental entity that you will ever work with or manipulate is numbers. Primitive data
types like int, float, double, long and short have been provided for your use. You can manipulate the
range of numbers that a number data type can house by using long short, signed and unsigned
keywords. The sample implementation shown below defines the different types of numbers that are
available in C++.
#include <iostream>
using namespace std;
int main () {
// Defining numbers
int i;
double d;
short s;
float f;
long l;
// Assigning values to numbers
i = 1000;
d = 30949.374;
s = 10;
f = 230.47;
l = 1000000;
cout << "Int:" << i << endl;
cout << "Double:" << d << endl;
cout << "Short:" << s << endl;
cout << "Float:" << f << endl;
cout << "Long:" << l << endl;
return 0;
}
The output for this code is shown in the image given below.
The concept of arrays comes from the standard concept of arrays in data structures, which described
it as a collection of same-type elements. C++ provides support for this data structure. Arrays can be
used to store data values or variables of the same type.
For instance, if you need five integer variables, then instead of declaring five different variables with
names like num1, num2, num3, num4 and num5, you can simply declare an array with the name num[5]
and access variables as num[0], num[1], num[2], num[3] and num[4].
The name of the array is num while 0, 1, 2, 3 and 4 are indexes. An element of the array is accessed
by putting the index inside the square bracket that follow the name of the array. The lowest address
contains the first element while the highest address contains the last element.
Declaring Arrays
In order to declare an array, you must specify the name of the array and the number of elements that
this array is required to contain. The syntax for declaring an array is as follws –
data_type array_name [array_size];
Here, data_type is the data type, array_name is the name of the array that you wish to give and
array_size is the number of elements that the array is expected to have. Since, this array is just one
row of elements, if you can imagine it to be such, this is a single-dimension array.
Please note that the value of array_size must be greater than zero and the data_type must be a valid
data type supported by C++. In order to declare a double array with 10 elements of the name bal, you
need to give the following declaration statement –
double bal [10];
Initializing Arrays
Array values can be initilized at the time of declaration or later in the program, as per your
convenience and needs. If you wish to initialize the array at the time of declaration, then you will
need to use a statement similar to the one given below –
double bal [5] = {35.9, 33.7, 24.6, 11.9, 7.3};
it is important to realize here that the number of values that you give as part of the curly braces must
never exist the value specified inside the square bracket. You may alternatively also use the following
C++ for performing the same operation.
double bal [] = {35.9, 33.7, 24.6, 11.9, 7.3};
This statement automatically assigns the size of 5 to the array. When you initilalize the array without
specifying the size of the array, the system automatically assigns a size that is large enough to
accommodate the mentioned elements.
The individual elements of the array can be accessed by specifying the index of the element. The first
element gets the index 0 and index for other elements after that is simply incremented by 1. For
example, the elements of the array declared above are as follows –
bal [0] = 35.9
bal [1] = 33.7
bal [2] = 24.6
bal [3] = 11.9
bal [4] = 7.3
Individual assignments and re-assignments can also be made by using statements like –
bal [0] = 0.0;
Although, this discussion only includes the basics of arrays in C++, you can move on to advanced
topics like multi-dimensional arrays, pointer to arrays and using arrays with functions.
Chapter 12: Strings
Apart from numbers and sets of numbers, the other category of elements that you can expect to work a
lot with is characters. While we have already discussed characters in data types, this chapter
elaborates on strings. C++ supports two forms of strings.
One of these forms represent strings in the form of character sequences. On the other hand, C++ also
has a class type for strings, which is a part of the standard C++. The former is known as C-style string
while the latter is a C++ addition. We shall discuss both these forms in this chapter.
C-Style Strings
The C style strings, as the name suggests was a concept given in C and C++ as inherited the same
considering the fact that C++ is an enhanced version of C. typically, this type of a string is a character
array that ends will the null character as an indication of string termination. Such a string is also
referred to as null terminated string.
The C-style strings are usually declared and initialized in the following manner.
char sayhello[6] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
therefore, if you wish to store a five-letter word in a c-style string, you will need a character array of
size 6, with the extra element required to store the null character. You can alternatively also use the
following statement for declaring and initializing the array.
char sayhello[] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
In order to demonstrate how these strings operate, let us look at the following example –
#include <iostream>
using namespace std;
int main () {
char sayhello[] = “Hello”;
cout << "Message: ";
cout << sayhello << endl;
return 0;
}
The output for this code is shown in the image given below.
There are a number of functions that you can use for manipulating C-style strings. These functions
include –
strcpy (s1, s2)
This function copies the string given in s2 to the string character array pointed by s1.
strcat (s1, s2)
This function concatenates the string given in s2 to the string pointed by s1.
strlen(s)
This function returns the length of the string.
strcmp (s1, s2)
This function compares the string given in s2 to the string pointed by s1. The value returned by the
function is 0 if the two strings are equal.
strchr (s, ch)
This function finds the character ch in the string s and returns a pointer of the first occurrence of the
same.
strstr (s1, s2)
This function finds the string s2 in the string s1 and returns a pointer of the first occurrence of the
same.
String Class
C++ provides a string class that can be used to create strings by instantiating the class and manipulate
them as objects. The following code demonstrates how string class can be used for string declaration,
definition and manipulation.
#include <iostream>
#include <string>
using namespace std;
int main () {
string str_1 = "My";
string str_2 = "Space";
string str_3;
int strlen ;
//Copy str_1 into str_3
str_3 = str_1;
cout << "str_3 : " << str_3 << endl;
//Concatenate str_1 and str_2
str_3 = str_1 + str_2;
cout << "str_1 + str_2 : " << str_3 << endl;
//Determine the length of str_3
strlen = str_3.size();
cout << "str_3.size() : " << strlen << endl;
return 0;
}
The output generated for this code can be seen in the image given below.
Conclusion
C++ is a programming language that finds application in almost every domain and field. From drivers
to user applications, you name it and it can be created using C++. This is what makes C++ such an
important programming language to learn and master.
Now that we have reached the end of this book, you must be thorough with basic C++ concepts and
programming. You are advised to take this knowledge forward and practice as many examples as you
can. This will help you create a solid foundation for advanced C++ programming.
We expect you to take the learning forward by graduating from these basics to advanced concepts in
C++ programming. We hope this book has been helpful and beneficial for you. We look forward to
receiving any feedback on the book.
C#
Introduction
The C# programming language was developed as part of the .NET framework of Microsoft. Anders
Hejlsberg led this initiative. C# can simply be described as a modern, object-oriented, simple and
general-purpose programming language. This book is a beginner’s guide to C# and covers all the
basic concepts that you need to learn to start writing programs in this language.
As the name suggests, C# is an enhanced version of C and C++. Therefore, if you have background
knowledge of these programming languages, you will find the learning process for C# much simpler.
However, if you have no background of these languages, even then this book should be able to give
you a quick start on C#.
This book includes many examples that you can try to get the real hang of C# programming language.
You may install a local setup or try the online compilers and execution environments available for
C#. Practicing is the key to learning a programming language. The more you practice; the better you
will get! Just going through the concepts will only help you know the rules, but to learn the language,
you will need to actually program in it.
This programming language is object-oriented and general-purpose language that was developed as
part of the .NET framework. It was developed by Microsoft and has earned approval of International
Standards Organization (ISO) and European Computer Manufacturers Association (ECMA).
C# was developed for CLI or Common Language Infrastructure. It has runtime environment and
executable code. Thus, it can be run on different platforms and allows usage of various high-level
languages. Key features of this programming language include –
Object oriented.
General-purpose
Platform-independent
Easy to learn.
Component oriented
Ensures efficient programming
Structured language.
One of the key advantages of using C# is the strong programming features that it includes. Many
features of this programming language are similar to Java, C++ and C. In fact, this programming
language has a good resemblance with Java. Some of the key features in this domain include –
Automatic Garbage Collection
Boolean Conditions
Assembly Versioning
Standard Library
Delegates Management
Properties and Events
Events Management
Indexers
Easy-to-use Generics
Simple Multithreading
Conditional Compilation
Seamless integration with Windows
LINQ and Lambda Expressions
Sample Program
As is the case with every programming language, we start with the Hello World program.
using System;
namespace PrintHelloWorld{
class HWorld {
static void Main(string[] args) {
/* C# Program */
Console.WriteLine("Hello World!");
Console.ReadKey();
}
}
}
Upon execution, the code shall generate the following output.
Writing Comments in C#
Comments are an integral part of any program and are included to make the program readable and
understandable by other programs who may wish to read or edit the code. From the compiler’s
perspective, the text written as comment in the code are simply ignored by the system. C# supports the
single-line and multi-line comment formats available in C and C++. A multi-line comment typically
starts with /* and end with */ and anything that is written inside these character combinations is called
a comment. Sample multi-line comment is as follows –
/*This is a comment.*/
On the other hand, a single-line comment begins with the character combination // and ends as and
when a newline character is encountered. Sample implementation of a single-line comment is as
follows –
//This comment is a single line comment.
Creating Objects
As we mentioned previously, a class is a template, which is used for creation of objects and the
interaction between these objects is the main function of any program. The ExeRectangle class in the
preceding example contains the Main method from where execution of the program begins. It can be
seen in the code that objects of the class Rectangle are created. The object r is instantiated from the
class Rectangle and the functionality of the class member functions is demonstrated.
Identifiers
Evidently, the class uses many words predefined by the programming language. However, there are
many names that are defined by the programmer. These include names of classes, variables and
functions, in addition to many others. The name that a programmer gives to any user-defined item is
referred to as an identifier. There are some rules laid down by the programming language for naming
identifiers. These rules include –
You must always name the identifier in such a manner that the first letter is an alphabet or
underscore. The rest of the letters can contain alphabets, numerals and underscore. Using
numerals as first letters of identifiers is strictly not allowed.
You cannot name an identifier with the same name as that of a keyword. C# prohibits the use
of keywords for any purposes other than the one defined.
The use of other special characters like @, # and !, in addition to several others is not
allowed. An identifier name cannot contain whitespaces.
Keywords
Some words are predefined by C# programming language as keywords or words with special
meanings. There are special functions assigned to these words and they cannot be used as names of
identifier. Besides this, some words have special meanings when considered in the context of the
code. Words like get and set fall under this category and are called contextual keywords.
The keywords defined by C# programming language are as follows –
The table given below lists all the contextual keywords supported by C# programming language.
partial partial
remove select set let orderby
(method) (type)
Before we discuss data types, let us look at variables. C# supports three types of variables namely,
value, pointer and reference type variables. This chapter discusses these types in detail and
introduces the process of type conversion in C#.
Value Type
The variables that can be directly given a value are called value type variables. They belong to the
class called System.ValueType. as is obvious, value type variables contain data, which can be int,
float or char in nature. Whenever you assign a data type to a variable, the system correspondingly
assigns the memory required to save the data value. all further values assigned to that variable are
saved in that memory. The value types available in C# are as follows –
Bool
A boolean variable can contain only two values namely true and false. The default value of such
variables is false.
Byte
Byte is the data type assigned to variables that are required to hold 8 byte integer values. The default
value of such a variable is 0 and it can hold values ranging from 0 to 255.
Char
Char is the data type assigned to variables that are required to hold 16 bit Unicode characters. The
default value of such a variable is \0 and it can hold values ranging from U +0000 to U +ffff.
Decimal
Decimal is the data type assigned to variables that are required to hold 128 bit decimal values. The
default value of such a variable is 0.0M and it can hold values ranging from (-7.9 x 10 28 to 7.9 x 10 28
/ 10 0 to 28.
Double
Double is the data type assigned to variables that are required to hold 64-bit double-precision
floating point type values. The default value of such a variable is 0.0D and it can hold values ranging
from (+/-)5.0 x 10 -324 to (+/-)1.7 x 10 308 .
Float
Float is the data type assigned to variables that are required to hold 32-bit single-precision floating
point type values. The default value of such a variable is 0.0F and it can hold values ranging from
-3.4 x 10 38 to + 3.4 x 10 38 .
Int
Int is the data type assigned to variables that are required to hold 32-bit integer values. The default
value of such a variable is 0 and it can hold values ranging from -2,147,483,648 to 2,147,483,647.
Long
Long is the data type assigned to variables that are required to hold 64-bit integer values. The default
value of such a variable is 0L and it can hold values ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
Sbyte
Sbyte is the data type assigned to variables that are required to hold 8-bit signed integer type. The
default value of such a variable is 0 and it can hold values ranging from -128 to 127.
Short
Short is the data type assigned to variables that are required to hold 16-bit signed integer type. The
default value of such a variable is 0 and it can hold values ranging from -32,768 to 32,767.
Uint
Uint is the data type assigned to variables that are required to hold 32-bit unsigned integer type. The
default value of such a variable is 0 and it can hold values ranging from 0 to 4,294,967,295.
Ulong
Ulong is the data type assigned to variables that are required to hold 64-bit unsigned integer type. The
default value of such a variable is 0 and it can hold values ranging from 0 to
18,446,744,073,709,551,615.
Ushort
Ushort is the data type assigned to variables that are required to hold 16-bit unsigned integer type.
The default value of such a variable is 0 and it can hold values ranging from 0 to 65,535.
The exact size of these data types may vary from one machine to another. In order to find the size of
these data types on your machine, you can use the sizeof() method. This method returns the storage
size of the object concerned in bytes. A sample implementation that returns the size of an int variable
is given below for your reference.
using System;
namespace DemoDataSize {
class DemoProg {
static void Main(string[] args) {
Console.WriteLine("Storage Size for int on this machine is: {0}", sizeof(int));
Console.ReadLine();
}
}
}
Upon execution, the code shall yield the following result.
Reference Type Variables
Such variables do not contain actual data. In fact, they contain a reference to the variable, which
contains that actual data. Therefore, it would not be wrong to state that these variables refer to the
memory location where actual data is saved. Many reference variables may point to the same memory
location. So, if one of these reference variables makes changes to the data concerned, then the rest of
the variables will show the updated data value automatically. Object, string and dynamic are
examples of such variables.
Object Type
Since C# implements object oriented principles, the base class of all data types available in C#
Common Type System (CTS) is Object Type. Object is a short name used for the class,
System.Object. The type of the values assigned to object types can be assigned to other types like
user-defined types and value types by performing a type conversion. This topic will be dealt with
later in this chapter.
However, it is important for you to know at this point that when a variable is converted to object type,
the process is known as boxing. On the other hand, when the variable to converted to value type, the
same is referred to as unboxing. Sample statements for performing boxing is given below –
object obj1;
obj1 = 125;
Dynamic Type
Any type of value can be stored in the dynamic type variable. Moreover, the system checks for the
type for these variables at runtime. A dynamic variable can be declared in the following menner –
dynamic <name_of_variable> = value_of_variable;
Sample declaration is given below for your reference.
dynamic dyn = 45;
The only difference between dynamic types and object type variables is that the type checking for the
former takes place at runtime while the same for the later is done at compile time.
String Type
Variables can be assigned string values using the string type and is a short name used for the class,
System.String. Like all other data types, this type is also derived from the object type. Two types of
string assignments can be performed. One form makes use of quotes and the other form makes use of
quotes preceded by @ sign. Sample implementation of this type is given below for your reference.
String str1 = "I am good.";
On the other hand, @quoted form of the string literal looks something like this –
@"I am good.";
There are many other user-defined reference types like interface, class and delegate. These types are
beyond the scope of this book and can be learnt in advanced C# programing.
Pointer Type
A variable of this type stores the memory address of another variable, which may or may not be this
type. C# pointers are same as C and C++ pointers. A pointer can be declared in C# using the syntax
given below –
data_type* identifier_name;
Sample implementation for pointers are given below for your reference.
char *ptr1;
Type Conversion
The process of converting the data type of a variable from one type to another is referred to as type
conversion. Another term that is commonly used for this process is typecasting. Two types of
typecasting may be performed in C# namely, explicit typecasting and implicit typecasting.
When the type conversion is performed by using pre-defined functions, then the process is called
explicit type conversion. This process requires a cast operator. On the other hand, automatic
conversions take place from smaller to larger integral types and derived classes to base classes. This
tpe of type conversion is called ‘implicit’.
Sample implementation for performing explicit type conversion is given below –
using System;
namespace DemoTypecasting {
class ETypecasting {
static void Main(string[] args) {
double d_var = 67.56;
int i_var;
// Converting double type to int
i_var = (int)d_var;
Console.WriteLine(i_var);
Console.ReadKey();
}
}
}
Upon execution, the code shall yield the following result.
The identifier used to name a storage space that holds a data value is called a variable. It is these
variables that our programs manipulate and work around with. Every variable is required to have a
type. The type of a variable specifies the type of data that it will store and thus, determines the
storage space allocated for the variable in the memory. The type of variable also specifies the range
of values that the variable can take and set of operations allowed on the same.
The fundamental value types provisioned by C# include –
Integral Types
This value type entails all integer type data types like int, ulong, ushort, long and short in addition to
char, sbyte and byte.
Floating Point Types
This value type entails all floating point type data types like double and float.
Decimal Types
This value type entails decimal data type.
Boolean Types
This value type include the values false and true.
Nullable Types
As the name suggests, this value type includes nullable data type.
In addition to the above-mentioned, value types like enum and class are also provided by C#.
Defining Variables
Variables can be defined in C# using the syntax shown below –
data_type name_of_variable;
Here, data_type is the data type and name_of_variable is the identifier used for the variable. You can
define many variables in the same C# statement by specifying them in the form of a comma-separated
list, if they are of the same type, and semi-colon separated C# definition statements, if they are of
different types. Sample definition has been given below for your reference.
int g, k; float h;
In order to initialize these variables, you simply have to use the assignment operator in the following
manner –
g = 100;
You can combine the definition and initialization statements, as shown below.
int g=100;
Your program may behave in an awkward manner is you forget to initialize a variable and use it in the
program. Therefore, it is a good programming practice to initialize every variable you define. You
can also accept user input and assign the inputted value to a variable by using the ReadLine() function
of the Console class.
The function returns the input given by the user in string format. If you wish to assign it to a variable
of different type, you will have to typecast it accordingly. The following example demonstrates how
this functionality can be implemented.
int i;
i = Convert.ToInt32(Console.ReadLine());
The Convert.ToInt32 converts the string object returned by the ReadLine function to int and assigns
the value to the integer variable i.
Constants are variables for which the value cannot be changed during the program’s execution. In
other words, their values are fixed. These fixed values are called literals. Several types of constants
exist. In fact, constants can be of integer, floating point, character, string and enum type in C#. In
simple words, constants are exactly like variables. It is just that the values of variables can be
changed during the course of the program while the same for constants is not true.
Integer Literals
A hexadecimal or integer literal is associated with Integer Literals. The radix of the literal is
determined by the prefix attached to the number. For instance, if the prefix is 0X or 0x, then the
number is hexadecimal else the number is decimal. In addition to this, numbers may have a suffix of U
or L. While U stands for unsigned, L stands for Long. The prefix and suffix may have any case and
appear in any order. Some examples of integer literals include oxFeeL, 85, 212, 30ul, 0X4b and 48u.
Character Literals
It is a practice to enclose character literals within single inverted commas. A character literal can
store characters, special characters and universal characters. Characters that are preceded by a
backslash have special functionality. For instance, \n is the newline character. Similar to this
character combination, several other character combinations also exist in C#. The codes for these
special characters are given below.
\\ \ character
\? ? character
\b Backspace
\a Alert or bell
\n Newline
\f Form feed
\t Horizontal tab
\r Carriage return
\v Vertical tab
Sample implementation of how escape characters function is provided below for your reference.
using System;
namespace DemoEscapeChar {
class DemoProg {
static void Main(string[] args) {
Console.WriteLine("Hello\t\t\tWorld\n\n\n!");
Console.ReadLine();
}
}
}
Upon execution, this code shall generate the result given below.
String Literals
When you have to declare string literals or character sequences, you must do so within double
inverted commas. The string can be a sequence of characters and special characters. Moreover, it can
also be multiple lines that are separated using the newline special character or a character with many
white spaces. Some examples of string literals include –
1. “Hello”
2. “Hello World”
3. “Hello
4. World”.
In order to perform logical and mathematical manipulation on variables and values, an entity called
operators is used. C# supports a rich set of operators, which have been classified under categories
like arithmetic, logical and bitwise operators. Each class of operators is discussed in detail below.
Arithmetic Operators
All mathematical operations are performed using operators that fall under the category of arithmetic
operators. List of supported operators have been given below.
Addition (+)
This operator performs addition between two numbers. If a and b are two variable holding 5 and 5
respectively. Then, c = a+b, will yield c = 10.
Multiplication (*)
This operator performs multiplication between two numbers. If a and b are two variable holding 5
and 5 respectively. Then, c = a*b, will yield c = 25.
Subtraction (-)
This operator performs subtraction between two numbers. If a and b are two variable holding 5 and 5
respectively. Then, c = a-b, will yield c = 0.
Division (/)
This operator performs addition between two numbers. If a and b are two variable holding 5 and 5
respectively. Then, c = a/b, will yield c = 1.
Modulus (%)
This operator returns the remainder left after dividing the two numbers. If a and b are two variable
holding 5 and 5 respectively. Then, c = a%b, will yield c = 0.
Increment (++)
This operator adds 1 to the value of the variable. If a is a variable holding the value 5, then a++ or
++a will yield the value 6.
Decrement (--)
This operator reduces 1 from the value of the variable. If a is a variable holding the value 5, then a--
or --a will yield the value 4.
Relational Operators
All operations involving comparison are performed using relational operators. A list of the operators
supported by this programming language is given below –
NOT EQUAL TO (!=)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns FALSE else it return TRUE. If a and b are two variable holding 5 and 5 respectively. Then,
c = (a!=b), will yield c = FALSE.
EQUAL TO (==)
This operator is applied on two operands. It checks equality between two operands. If they are equal,
it returns TRUE else it return FALSE. If a and b are two variable holding 5 and 5 respectively. Then,
c = (a==b), will yield c = TRUE.
GREATER THAN (>)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than the second operand, it returns TRUE else it return FALSE. If a and b are two
variable holding 5 and 5 respectively. Then, c = (a>b), will yield c = FALSE.
LESS THAN (<)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than the second operand, it returns TRUE else it return FALSE. If a and b are two
variable holding 5 and 5 respectively. Then, c = (a<b), will yield c = FALSE.
GREATER THAN OR EQUAL TO (>=)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is greater than or equal to the second operand, it returns TRUE else it return FALSE. If a and
b are two variable holding 5 and 5 respectively. Then, c = (a>=b), will yield c = TRUE.
LESS THAN OR EQUAL TO (<=)
This operator is applied on two operands. It checks equality between two operands. If the first
operand is less than or equal to the second operand, it returns TRUE else it return FALSE. If a and b
are two variable holding 5 and 5 respectively. Then, c = (a<=b), will yield c = TRUE.
Logical Operators
All the logical operations in Java are performed using logical operators. The list of operators
supported by this programming language is given below.
Logical AND
This operator works on two operands. If both the operands are non-zero, the expression returns
TRUE else it returns FALSE.
Logical OR
This operator works on two operands. If one or both the operands are non-zero, the expression
returns TRUE else it returns FALSE.
Logical NOT
This operator works on one operand. If the operand is zero, this expression returns TRUE else it
returns FALSE.
Bitwise Operators
The only difference between normal operators and bitwise operators is that these operators perform
operations bit-by-bit. Moreover, these operators can be applied on byte, int, short, long and char. The
list of bitwise operators supported in Java include –
Bitwise AND (&)
This operator works on two operands and the output for each set of input bits is 1 if both the inputs
are one else the output is zero.
Bitwise OR (|)
This operator works on two operands and the output for each set of input bits is 1 if one or both of the
inputs is one else the output is zero.
Bitwise XOR (^)
This operator works on two operands and the output for each set of input bits is 1 only if one of the
inputs is one else the output is zero.
Bitwise COMPLEMENT (~)
This operator works on a single operand and negates the values from 0 to 1 and from 1 to 0.
LEFT SHIFT (<<)
This operator works on two operands. The bits of the left operand are shifted left. The number of
places is equal to the number specified as value for the second operand.
RIGHT SHIFT (>>)
This operator works on two operands. The bits of the left operand are shifted right by the number
specified as value for the second operand.
In order to understand how bitwise operations take place, let us take an example. Assume two
variables, a and b, having the values 60 and 13 respectively. The binary equivalent of a and b are as
follows –
a = 00111100
b = 00001101
Using the AND truth table according to which the output is 1 only if both the inputs are 1.
Correspondingly, the output of a&b = 00001100. Similarly other bitwise operations can also be
performed.
Assignment Operators
The list of assignment operators supported by Java include –
Simple Assignment Operator (=)
This operator assigns the value computed by the right hand side to the variable on the left hand side. If
a, b and c are three variable and the expression is c = a+b, then the value of addition of a and b is
assigned to c.
Add AND Assignment Operator (+=)
This operator assigns the value computed by the addition of right hand side and left hand side to the
variable on the left hand side. If a and c are two variable and the expression is c += a, then the value
of addition of a and c is assigned to c.
Subtract AND Assignment Operator (-=)
This operator assigns the value computed by the subtraction of right hand side from left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c -= a, then the
value of c-a is assigned to c.
Multiply AND Assignment Operator (*=)
This operator assigns the value computed by the multiplication of right hand side and left hand side to
the variable on the left hand side. If a and c are two variable and the expression is c *= a, then the
value of c*a is assigned to c.
Divide AND Assignment Operator (/=)
This operator assigns the value computed by the division of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c /= a, then the value
of c/a is assigned to c.
Modulus AND Assignment Operator (%=)
This operator assigns the value computed by the modulus of left hand side with right hand side to the
variable on the left hand side. If a and c are two variable and the expression is c %= a, then the value
of c%a is assigned to c.
Left Shift AND Assignment Operator (<<=)
If a and c are two variable and the expression is c <<= a, then the value of c<<a is assigned to c.
Right Shift AND Assignment Operator (>>=)
If a and c are two variable and the expression is c >>= a, then the value of c>>a is assigned to c.
Bitwise AND Assignment Operator (&=)
If a and c are two variable and the expression is c &= a, then the value of c&a is assigned to c.
Bitwise XOR AND Assignment Operator (^=)
If a and c are two variable and the expression is c ^= a, then the value of c^a is assigned to c.
Bitwise Inclusive OR and Assignment Operator (|=)
If a and c are two variable and the expression is c |= a, then the value of c|a is assigned to c.
Miscellaneous Operators
In addition to the above-mentioned, there are a few more operators that do not fall under any
specified category. These operators are –
sizeof
The sizeof operator is used to determine the size of the variable that is passed as argument to it. The
syntax for using the sizeof() operator is –
X = sizeof(a); //Now variable X will contain the size of the variable a
typeof
The typeof operator is used to determine the type of the class that is passed as argument to it. The
syntax for using the typeof() operator is –
typeof(StreamRedaer);
Pointer Operator (& and *)
The * operator is used to indicate a pointer to a variable. For instance, *p is a pointer variable. On
the other hand, & operator is used to determine the address of a variable. For instance, &a will return
the memory address corresponding to a.
Conditional Operator (?:)
The conditional operator is the replacement of a simple if-else statement. The syntax of the
conditional operator is –
condition?a:y;
When ths C++ statement is given, it checks the condition for truthfulness. If the condition is true,
expression corresponding to a is executed else the expression corresponding to b is executed.
Is Operator
The ‘is’ operator is used to check if an object is of a particular class. For instance, you can put a if
condition that checks if r is an object of the class Rectangle and executes the if block accordingly, in
the following manner –
if(r is Rectangle)
{
…
}
As Operator
The ‘as’ operator is used to typecast a variable and it instructs the system to not raise an exception
even if the typecast fails. Sample implementation is given below for your reference.
StringReader r = obj as StringReader;
Operator Precedence
If an expression uses multiple operators, then operator precedence rules are used to determine the
order to execution of operations. The precedence of operators in terms of whether they will be
evaluated from right to left or left to right is defined for groups of operators in the following manner –
Right to Left
Conditional
Unary
Assignment
Left to Right
Multiplicative
Postfix
Shift
Additive
Equality
Relational
Bitwise XOR
Bitwise AND
Logical AND
Bitwise OR
Logical OR
For example, if we have to evaluate the expression a = 3 + 5 * 5, then multiplication is performed
before addition. Therefore, a = 28 instead of 40.
Chapter 8: Decision Making
There are many situations when you require a block of statements to be executed only if a particular
condition is satisfied or conversely, if the condition concerned is not satisfied. The imlementation of
such programming scenarios require decision making constructs. C# supports many decision making
constructs; most of which are variations of the classic if…else construct. All these decision making
elements of the C# programming language are described in this chapter.
If Statement
The if statement is the most basic decision making construct that tests the condition, which appears in
the if statement. If the condition is found true, the block of statements that follow the if statement is
executed. On the other hand, if the condition is false, the if block is simply ignored by the system and
execution begins from the first statement that lies outside the if block. Sample implementation for the
if statement is given below.
using System;
namespace ConditionalStatements{
class DemoIf{
public static void Main(string[] args)
{
int num = 5;
if (num < 5)
{
Console.WriteLine("Inside If Block”);
}
Console.WriteLine("If Executed.");
}
}
}
The output for this code is shown in the image given below.
If Else Statement
The if else is a modified version of the standard if construct that tests the condition, which appears in
the if statement. If the condition is found true, the block of statements that follow the if statement is
executed. On the other hand, if the condition is found false, the block of statements that follow the else
statement is executed. Sample implementation for the if else statement is given below.
using System;
namespace ConditionalStatements{
class DemoIf{
public static void Main(string[] args)
{
int num = 5;
if (num < 5)
{
Console.WriteLine("Inside If Block”);
}
else
{
Console.WriteLine("Inside Else Block”);
}
Console.WriteLine("If Else Executed.");
}
}
}
The output for this code is shown in the image given below.
Nested If Statements
There may be situations where you may be required to test many conditions; each of which being a
sub-part of the main condition. In other words, if you have a programming scenario that needs to
perform a block of statements if the vehicle is an Audi car. So, firstly, you will need to put a condition
that tests if the vehicle is a car. If this condition is found true, the system must check for a condition
that tests if the car is an Audi. This requires two if statements, one inside another, or a nested if
statement.
You can have multiple if statements, one inside another to test multiple conditions. There is no limit of
the amount of nesting that can be performed for if. However, the higher the number of ifs inside one
another gets, the time complexity of the program increases. Sample code for implementing the nested
if is as follows –
using System;
namespace ConditionalStatements{
class DemoIf{
public static void Main(string[] args)
{
int num1 = 5;
int num2 = 2
if (num1 == 5)
{
Console.WriteLine("Inside If Block 1”);
if (num2 == 2)
{
Console.WriteLine("Inside If Block 2”);
}
}
Console.WriteLine("Nested If Executed.");
}
}
}
The output generated upon the execution of this code can be seen in the image given below.
Switch Statement
In order to mitigate the complexity issues associated with nested if statements, C# also provides
switch statement, which can test one variable for multiple values and execute corresponding
statements for the same. This construct internall creates a table, which is used for making execution
faster. The syntax for implementing switch statement is as follows.
Switch (variable_to_be_tested) {
Value_1:
Statement;
break;
Value_2:
Statement;
break;
Value_3:
Statement;
break;
default:
Statement;
break;
}
Conditional Operator
To simplify the conditional construct, C# also provides a conditional operator (?:). This operator as
been discussed in detail in the chapter on operators.
Chapter 9: Loops
For Loop
The for loop allows the programmer to define and initialize a variable and give a condition that needs
to be true for the loop to execute. The variable can be initialized as well as updated in the for
statement. Moreover, the for statement also check the condition and the for block is executed only if
the condition is true. The syntax for implementing the for loop is as follows –
for(data_type var_name = init_val; condition; var_name update expression){ … }
Here, data_type is the data type of the variable called var_name, which is updated using the
expression given in the last section of the for statement. The condition to be checked for executing the
for block is mentioned in the middle section of the for statement. Sample implementation of the for
loop is as follows –
using System;
namespace DemoLoop
{
class DemoWhile
{
public static void Main(string[] args)
{
int i;
for (i=1; i<=10; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
}
}
The result of the execution of this program is as follows –
While Loop
The while loop only checks the condition that needs to be fulfilled for executing an iteration of the
loop. If the specified condition is found true, the block executes else it breaks. The variable
initilization and updation needs to be managed by the programmer. The syntax for implementing the
while loop is as follows –
while(condition){ … }
Here, the condition to be checked for executing the while block is mentioned in the while statement.
Sample implementation of the for loop is as follows –
using System;
namespace DemoLoop
{
class DemoWhile
{
public static void Main(string[] args)
{
int i=1;
while (i<=10)
{
Console.WriteLine("C# While Loop: Iteration {0}", i);
i++;
}
}
}
}
The result of the execution of this program is as follows –
Do…While Loop
Do…while loop is a variant of the while loop, which executes at least once irrespective of whether
the specified condition is true or false. The condition is checked at the end of the first execution of the
block when the while statement is encountered. The syntax for implementing the do…while loop is as
follows –
Do { … } while(condition);
Here, the condition to be checked for executing the while block is mentioned in the while statement.
Sample implementation of the for loop is as follows –
using System;
namespace DemoLoop
{
class DemoWhile
{
public static void Main(string[] args)
{
int i=1;
do{
Console.WriteLine("C# Do While Loop: Iteration {0}", i);
i++;
} while (i<=10);
}
}
}
The result of the execution of this program is as follows –
Nested Loop
The programmer is free to create a nest of loops, if the situation demands. Moreover, there is no
limitation on the number of loops that are allowed.
A class is a template or blueprint that shall be used to create objects, which are the fundamental
elements in object-oriented programming. The behaviour of a program is determined by the
interaction between these objects.
Since, the class is just a blueprint, the definition of a class does not define any data as such. In other
words, no memory is allocated until the class is instantiated or objects are created using the class.
This brings us to the question: what does a class contain? A class will contain variables and methods
that the object will include.
When you will create an object, the variables will be defined for the object and methods will be
available to the object for manipulation of its data. The variables and methods of a class are also
called class members.
Defining a Class
The syntax used for defining a class uses the keyword class, which is followed by an identifier or
name of the class. Lastly, a block enclosed inside curly braces is used to define the members of the
class. A class can be defined in the following manner –
access_specifier class class_name {
/*Defining a class variable*/
access_specifier data_type var_1;
/*Defining a class method*/
access_specifier return_type method_1 (list_of_parameters) {
/*Body of Method*/
}
}
Here, access_specifier is the keyword that specifies the accessibility rule for the class or members of
the class. In other words, if the access_specifier is public, the entity is accessible by everyone in the
system. On the other hand, private and protected restrict the accessibility of the entity to members of
the class only (for private) and members of the class and classes derived from the class (for
protected).
The default access_specifier for classes is internal, which restricts the accessibility of the class to the
namespace concerned. Moreover, the default access_specifier for members of the class is private.
Besides this, data_type is the data type of the variable and return_type is the data type of the value
that the method is expected to return.
In order to access the members of the class from outside the class, the dot operator must be used. The
implementation of class, its definition and how to access its members is demonstrated in the example
given below.
using System;
namespace DemoApp {
class DemoBox {
public double box_ln; /*Box length*/
public double box_br; /*Box breadth*/
public double box_ht; /*Box height*/
}
class DemoTestBox {
static void Main(string[] args) {
DemoBox Box_1 = new DemoBox(); /*Create first box*/
DemoBox Box_2 = new DemoBox(); /*Create second box*/
double box_vol = 0.0; /*Declare a variable for storing box volume*/
Box_1.box_ht = 5.0;
Box_1.box_ln = 7.0;
Box_1.box_br = 2.0;
Box_2.box_ht = 4.0;
Box_2.box_ln = 3.0;
Box_2.box_br = 5.0;
box_vol = Box_1.box_ht * Box_1.box_ln * Box_1.box_br;
Console.WriteLine("Volume of Box_1 : {0}", box_vol);
box_vol = Box_2.box_ht * Box_2.box_ln * Box_2.box_br;
Console.WriteLine("Volume of Box_2 : {0}", box_vol);
Console.ReadKey();
}
}
}
Upon execution, the code yields the following output –
Encapsulation in C#
The member functions are functions that are defined as part of the class and manipulate data members
of the same. Evidently, member functions have access to all the members of the class and it operates
on objects that are created using the same class. The basis of implementation of encapsulation in C#
lies in the fact that accessibility of data members and member functions can be controlled by the
programmer.
If you do not define a constructor function, the default constructor for the class is called. Although, the
default constructor does not have any parameters, you can create constructors that have parameters.
Such constructors are given the name parameterized constructors. Such constructors are specifically
useful for creating objects with dynamic initial values. Sample code to demonstrate this functionality
is given below –
using System;
namespace DemoApp {
class DemoLine {
private double line_ln; /*Length of line*/
public DemoLine(double len) {
Console.WriteLine("New object created with length = {0}", len);
line_ln = len;
}
public void setLineLn( double len ) {
line_ln = len;
}
public double getLineLn() {
return line_ln;
}
static void Main(string[] args) {
DemoLine line_1 = new DemoLine(7.5);
Console.WriteLine("Length of line_1 : {0}", line_1.getLineLn());
line_1.setLineLn(6.0);
Console.WriteLine("Length of line_1 changed to : {0}", line_1.getLineLn());
Console.ReadKey();
}
}
}
The output for the code is illustrated in the image shown below.
Destructor is the second special function in C#. Just like the constructor is the first method to be
called on object creation, destructor is the last function to be called before the class goes out of
scope. The name of the destructor is also same as the name of the class with the difference that the
name is preceded by the tilde sign (~).
Besides this, a destructor function cannot have any parameters, cannot be overloaded or inherited and
does ot return a value. This special function is typically used to release any memory held by the class
before the program exits. Example of destructor function can be seen in the code given below.
using System;
namespace DemoApp {
class DemoLine {
private double line_ln; /*Length of line*/
public DemoLine() {
Console.WriteLine("New object created");
}
~DemoLine() {
Console.WriteLine("Object destroyed");
}
public void setLineLn( double len ) {
line_ln = len;
}
public double getLineLn() {
return line_ln;
}
static void Main(string[] args) {
DemoLine line_1 = new DemoLine();
line_1.setLineLn(7.5);
Console.WriteLine("Length of line_1 : {0}", line_1.getLineLn());
}
}
}
Upon execution, this code yields the following output –
Static Members of Class
As we mentioned previously, data members for a class are created upon instantiation. Therefore,
there is a copy of each data member for each object of the class. However, static members are
members that have only one copy for all the objects created for the class or only one instance of the
data member for the class exists.
Static members are declared using the keyword static. However, they can be defined inside or outside
the class. Sample implementation to demonstrate the working of static data members is given below –
using System;
namespace DemoApplication {
class DemoStaticVar {
public static int st_num;
public void count() {
st_num++;
}
public int getNumber() {
return st_num;
}
}
class DemoStaticTester {
static void Main(string[] args) {
DemoStaticVar s_1 = new DemoStaticVar();
DemoStaticVar s_2 = new DemoStaticVar();
s_1.count();
s_1.count();
s_1.count();
s_2.count();
s_2.count();
s_2.count();
Console.WriteLine("Variable st_num for s_1: {0}", s_1.getNumber());
Console.WriteLine("Variable st_num for s_2: {0}", s_2.getNumber());
Console.ReadKey();
}
}
}
The result generated by the execution of this code is shown below.
Member functions can also be declared as static. The fundamental difference between normal
functions and static functions is that static function can only access static data members of the class.
Moreover, static member functions begin to exist from the time of class declaration and thus, they
exist even before an object of the class is instantiated.
Chapter 11: Arrays
If you wish to store many elements of the same type and don’t want to create an individual variable
for each of them, then the best data format available for you is an array. The standard definition of
array is a collection of elements that are of the same data type. Moreover, the size of the elements is
fixed and the order of the same is sequential in the way that contiguous memory is allocated for the
storage of the array elements.
One of the best ways to understand arrays is to see it as a collection of variables of the same type.
The name of the array points to the first element of the array. The index of the first element is 0.
Therefore, the first element of the array is name_of_array[0]. Subsequent elements of the array can be
accessed by mentioning the index of the element by using the syntax, name_of_array[0].
Declaring Arrays
In order to declare an array, you need to use the syntax given below –
data_type[] name_of_array;
Here, data_type is the data type of the array, name_of_array is the identifier that will be used for
accessing the array and its elements and [] is the rank or number of elements in the array. An example
of array declaration is given below.
double[] bal;
Initializing Arrays
While the array declaration statement tells the compiler that an array of this name is to be created,
memory for array is actually allocated when the array is initialized. It is only after array initialization
that values can be assigned to the elements of the array. Array is initialized using the new keyword in
the following manner –
double[] bal = new double[5];
This statement initializes the array named bal of the type double to have 5 elements.
Assigning Values
Like we mentioned, individual elements of the array can be accessed by mentioning the index of the
concerned element, inside square brackets, next to the array name in the following manner –
bal[0] = 4.5
This statement initilizes the first element of the array bal to the double value 4.5. The above-
mentioned method initializes individual elements of the array to specific values. Initialization and
assignment can be combined together in the following manner –
double[] bal = {4.5, 66.7, 111.6, 34.0, 98.7};
Alternatively, you may also perform this operation in the following manner –
double[] bal = new bal[5] {4.5, 66.7, 111.6, 34.0, 98.7};
double[] bal = new bal[] {4.5, 66.7, 111.6, 34.0, 98.7};
If you wish to copy an array into another array, you can directly use the statement similar to the one
given below.
double[] cp_bal = bal;
This statement creates an array cp_bal that points to the same location as that of bal. It is important to
mention here that C# also performs auto-initialization of elements depending on the data type of the
array. For instance, if an int array is created, all its values are initialized to 0.
Accessing Elements
Just like array elements are initialized using their index, array elements can be accessed an re-
initialized using the name of the array followed by the index of the element, which is enclosed within
square brackets. An example of this is given below.
double val = bal[4];
This statement assigns the value of the last element of the array to the variable val. The sample code
given below demonstrates the working of arrays in C#.
using System;
namespace DemoApp {
class DemoArray {
static void Main(string[] args) {
int [] num = new int[5]; /* num is an int array of 5 elements */
int x,y;
for ( x = 0; x < 5; x++ ) {
num[ x ] = x + 100;
}
/*Print the values of array elements*/
for (y = 0; y < 5; y++ ) {
Console.WriteLine("Element[{0}] = {1}", y, num[y]);
}
Console.ReadKey();
}
}
}
The output generated upon the execution of this code is shown below.
Foreach Loop
C# provides a special looping construct that uses the contiguous nature of arrays for performing
iterations. The loops iterates through the elements of the array and its syntax is as follows –
foreach (int var_name in array_name)
{
…
}
Here, var_name is the looping variable and array_name is the name of the array, which needs to be
involved for looping. Sample implementation of this looping construct is given below.
using System;
namespace DemoApp {
class DemoArray {
static void Main(string[] args) {
int [] num = new int[5];
for ( int x = 0; x < 5; x++ ) {
num[x] = x + 100;
}
foreach (int y in num ) {
int x = y-100;
Console.WriteLine("Value of Element[{0}] = {1}", x, y);
}
Console.ReadKey();
}
}
}
The output generated upon the execution of this code is shown below.
Arrays in C#
C# supports multi-dimensional arrays and the simplest form of the same is 2-dimensional arrays. Two
dimensional arrays are defined and accessed using the format, array_name[][]. Every new dimension
adds a square bracket combination in front of the array name. C# also supports the concepts of jagged
arrays or arrays of arrays. Besides this, arrays can also be passed as parameters to functions. Lastly,
C# has a defined class in the System namespace for arrays. This is the base class for all arrays, with
inbuilt functions.
Chapter 12: Strings
Strings can be viewed as combination of characters, which are basically data values of the same type.
Therefore, strings are nothing but an array of characters. However, to make operations simpler for the
programmer, C# has a dedicated class called String in the System namespace. Therefore, you can
directly create a string by specifying the string keyword.
Creating Strings
Strings can be created in a variety of ways. The simplest method is to create an object of the string
class, which calls the string constructor. Besides this, you may also assign a string literal to a String
variable for creating a string object. These two methods are direct string creation methods.
In addition to these, some indirect methods also exist. These include the use of string concatenation
operator (+) and calling of a method that returns a string object or a formatting method that converts
the object into its string form. Sample code for demonstration of strings and their manipulation in C#
is given below.
using System;
namespace DemoApp {
class DemoString {
static void Main(string[] args) {
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
/*Creating string using string concatenation operator*/
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
}
}
}
The output generated upon the execution of this code is shown below.
String Class in C#
There are two properties of the String class, which are as follows –
Length
This property stores the length of the concerned String object.
Chars
This property stores the char at the specified location of the concerned String object.
In addition to these properties, String class also includes many methods like Compare, which
compares two strings. Sample code that uses this method is given below. You can explore more
methods of the String class by going through the C# manual.
using System;
namespace DemoApp {
class DemoString {
static void Main(string[] args) {
string str_1 = "It is me";
string str_2 = "It is my";
if (String.Compare(str_1, str_2) == 0) {
Console.WriteLine(str_1 + " and " + str_2 + " are equal.");
}
else {
Console.WriteLine(str_1 + " and " + str_2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}
The output generated upon the execution of this code is shown below.
Conclusion
Now that we have reached the end of this book, you have an idea about the programming
fundamentals of C# language. We had included a good number of coding examples to help you get a
quick grasp of what C# code looks like and get you started with programming in this language right
away.
We expect you to run all the given examples for yourself and see how the code actually behaves in the
programming environment. You can take this learning forward by executing variations of the given
sample codes, even if you end up making errors. This will help you a hands-on experience of C#.
Practice is the key to learning any programming language and the more you will practice, the better
you will become! We hope this book helped you create the foundation for advanced learning. Any
feedback and suggestions are most welcome!