Sunteți pe pagina 1din 505

Computer Programming

Learn Any Programming Language in 2 Hours


And Start Programming Today

This Book Includes:

Computer Programming For Beginners


HTML & CSS
Java
Javascript
SQL
Python
PHP
C++
C#

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

HTML & CSS

Learn HTML & CSS in 2 hours And Start


Programming Today

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.

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 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.

Basic HTML Document


Before moving any further, let us look at a basic HTML document. The example code given below
corresponds to a webpage.
<!DOCTYPE html>
<html>
<head>
<title>Sample Webpage</title>
</head>
<body>
<h1>First Heading</h1>
<p>Content of the webpage will appear here.</p>
</body>
</html>
This code can be saved in any text file created using a text editor. The extension of the file must be
changed from txt to htm or html. When this file is opened as a webpage using any of the browsers
installed on the system, it shall yield the following result.
Tags in HTML
As mentioned previously, HTML is a markup language. It uses tags to tell the browser how it should
format content and display the same on the screen. The tag is typically enclosed within braces (<name
of the tag>). Every tag has an opening form and a closing form, with the exception of a few tags. For
example, the opening tag for a HTML page is <html> and the closing tag for the same is </html>. The
list of HTML tags and their usage is given below for your reference.
S. No. Tag Meaning
1. <!DOCTYPE> This tag is used to tell the browser the type of the document
and the version of HTML that is used to create the same.
2. <html> The whole HTML document is enclosed inside the html tag.
All the other tags like <p></p>, <body></body> and <head>
</head>, in addition to others, shall be enclosed inside this
main tag.
3. <head> This is the first tag that appears inside the html tag. It
represents the head of the document and contains tags like
title and link.
4. <title> This tag is used to mention the title of the document and is the
tag placed inside the head tag.
5. <body> The body of the document is enclosed inside this tag. All
other tags like <p></p>, <h1></h1> and <div></div>, in
addition to others are placed inside this tag.
6. <h1> This tag represents the first level heading. There are tags like
<h2>, <h3> and <h4> that change the font size and attributes
to represent a lower level heading.
7. <p> A paragraph is represented with the help of this tag.

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>

The <DOCTYPE> Declaration


In order to tell the browser the HTML version that is used to create a webpage, the <!DOCTYPE>
declaration is used. HTML-5 makes use of the following type of declaration for document type.
<!DOCTYPE html>
Depending on the version of HTML being used, the declaration for the document type will also
change.
Chapter 2: Basic Tags

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 &nbsp. 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&nbsp;Angry&nbsp;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.

How to Add Metatags


Metatags are typically placed inside <head>…</head> as part of the document’s header. The core
attributes associated with this tag include –
Name
This attribute is used to mention the name of a property, which can be anything from author to
keywords.
Content
The property whose name was mentioned using the name attribute can be given a value using the
content attribute.
Scheme
This property declares the scheme that must be used to interpret the value of the property.
http-equiv
This property is typically used for message headers. Common usages include setting cookies and
refreshing pages.

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>

Document Revision Date


Another important parameters that search engines consider when crawling webpages is that they
crawl pages that are revised recently. Therefore, in order to get the latest content on the webpage
indexed, it is important to set the revision date for the document. This can also be done using the
<meta> tag in the following manner –
<!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" />
</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>

How to Set Cookies


In order to facilitate communication between clients and web server, data is stored in small text files,
which are referred to as cookies. This data is typically used to keep track of the session and the
specific needs of the client. It can also be sued to track user and extract visitor information at the
server end. Sample code to illustrate how this can be implemented on a webpage is shown below –
<!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 = "cookie" content = "userid = abc; expires = Friday, 08-Oct-18 23:59:59
GMT;" />
</head>
<body>
<p>Hello World!</p>
</body>
</html>
If the expiration date and time are not specified for a cookie, it is deleted as soon as the user exits the
browser and is also called a session cookie.

How to Set Author Name


The name of the author of the document can be set using <meta> tags in the following manner –
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Demo</title>
<meta name = "keywords" content = "HTML, sample, Metadata" />
<meta name = "description" content = "Sample page." />
<meta name = "author" content = "Jacob Manuel" />
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Chapter 7: Comments

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>

Valid and Invalid


There are a few mistakes that programmers make while specifying comments. For instance, you
cannot nest comments. Besides this, the two dashes and the start/closing character string should not
have any spaces between them. The comment given above is a valid comment. However, the comment
given below is an invalid comment.
<!DOCTYPE html>
<html>
<head>
<title>Invalid Comment Demo</title>
</head>
<body>
< !-- Invalid comment -->
<p>Document body...</p>
</body>
</html>
Notice the space between the left bracket and exclamation mark. When executed, instead of ignoring
that statement, the code will result in the following output.

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>

The Comment Tag


In some browsers, you may face issues while using the already mentioned format for defining
comments. In such cases, the comment tag may be a good alternative to work with. However, it is
important to mention here that this tag as deprecated from IE5 onwards and its usage is not
recommended. Just for completion of concept, we have provided an example of the comment tag
below.
<!DOCTYPE html>
<html>
<head>
<title> Comment Tag Demo</title>
</head>
<body>
<p>Example: <comment>must not be included</comment> text.</p>
</body>
</html>
How to Incorporate Comments in Script Code
Although, JavaScript is not a part of this tutorial, it is important to mention here that any script or
code added to HTML must be properly put inside comments. An example of how this is typically
done is given below –
<!DOCTYPE html>
<html>
<head>
<title>Commenting Script Demo</title>
<script>
<!-- document.write("Hello!") //-->
</script>
</head>
<body>
<p>Hello, User!</p>
</body>
</html>

How to Comment Style Sheets


Although, we are going to learn about style sheets in the last chapter of this book, it is important to
mention here that unless you put CSS inside proper HTML comments, it will be difficult for older
browsers to understand the same. This can be done in the manner shown below –
<!DOCTYPE html>
<html>
<head>
<title>Demo of Commenting Cascading Style Sheets</title>
<style>
<!-- .example { border:1px solid #4a7d49; } //-->
</style>
</head>
<body>
<div class = "example">Hello , User!</div>
</body>
</html>
Chapter 8: Images

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.

Setting the Height and Width of Images


Setting the corresponding attributes can set the height and width of the image. HTML allows the
programmer to mention height and width in terms of pixels or percentage. Sample code to illustrate
how this can be done is shown below –
<!DOCTYPE html>
<html>
<head>
<title>Set Width and Height of Image Demo</title>
</head>
<body>
<p>Setting width and height of image</p>
<img src = "/html/images/sample.png" alt = "Sample Image" width = "150" height = "100"/>
</body>
</html>

How to Set the Border of Image


By default, images in HTML have a border. You can alter the thickness of the border to get the desired
effect. For instance, you can set the thickness to 0 for a “no border” configuration. Sample code to
illustrate how this can be done is provided below –
<!DOCTYPE html>
<html>
<head>
<title>Set Image Border Demo</title>
</head>
<body>
<p>Setting Border of Image</p>
<img src = "/html/images/sample.png" alt = "Sample Image" border = "3"/>
</body>
</html>

How to Align Images


By default, the images added to a webpage are aligned to the left. However, using the align attribute,
you can change image alignment to center or right. Sample code to demonstrate how this can be done
has been provided below.
<!DOCTYPE html>
<html>
<head>
<title>Set Image Alignment Demo</title>
</head>
<body>
<p>Align Image</p>
<img src = "/html/images/sample.png" alt = "Sample Image" border = "3" align = "center"/>
</body>
</html>
Chapter 9: Tables

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.

Attributes for Cellspacing and Cellpadding


The whitespace in your table can be adjusted using two attributed namely, cellpadding and
cellspacing. The whitespace between the border and table or cell content is called cellpadding. On
the other hand, the whitespace between different cells of the table is referred to s cellspacing. The
sample code given below illustrates how these two attributes can be adjusted for better aesthetics and
readability.
<!DOCTYPE html>
<html>
<head>
<title>Cellpadding and Cellspacing Demo</title>
</head>
<body>
<table border = "1" cellpadding = "5" cellspacing = "5">
<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.

Rowspan and Colspan


HTML also allows programmers to merge columns and rows on their free will. Colspan is used for
merging columns while rowspan performs merger of rows. Sample code to demonstrate how this
concept works is provided below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Colspan/Rowspan Demo</title>
</head>
<body>
<table border = "1">
<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>
The webpage corresponding to this code is shown below for your reference.
Setting Background for Tables
Background can be set using two methods namely, by setting the bgcolor attribute or using the
background attribute. Both these methods can be used to set the background of the whole table or
single cell of the table. Lastly, the color of the border of the table can be set with the help of
bordercolor attribute. Sample code to demonstrate how background for tables can be set is provided
below.
<!DOCTYPE html>
<html>
<head>
<title>Set Table Background Demo</title>
</head>
<body>
<table border = "1" bordercolor = "green" bgcolor = "yellow">
<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>
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>

Setting Height and Width of Tables


The width and height attributes can be used for setting the cooresponding parameters. HTML allows
programmers to specify the desired height and width in terms of pixels or percentage. Sample code to
illustrate how this can be done is provided below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Demo Table Width/Height</title>
</head>
<body>
<table border = "1" width = "400" height = "150">
<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.

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.

Header, Footer and Body of Table


The division of a table into header, footer and body can be related to the header, footer and body of
word documents. While header and footer include extra information about the document, the body has
the main content. The tags used for setting each of these are <thead>, <tfoot> and <tbody>. The first
two tags create a separate header and footer section of the table. However, the last tag indicates the
main table body.
Chapter 10: Lists

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 –

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 –

The sample code given below uses the value “A”.


<!DOCTYPE html>
<html>
<head>
<title>Demo: Ordered List</title>
</head>
<body>
<ol type=A>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ol>
</body>
</html>
The webpage corresponding to this code is shown below –

The sample code given below uses the value “a”.


<!DOCTYPE html>
<html>
<head>
<title>Demo: Ordered List</title>
</head>
<body>
<ol type=a>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ol>
</body>
</html>
The webpage corresponding to this code is shown below –
The default value of the first element of the list is 1. However, HTML allows you to change this value
at will using the start attribute. Sample code to illustrate how the start attribute of <ol> tag can be
used to alter the list is provided below.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Ordered List</title>
</head>
<body>
<ol start=”4”>
<li>ABC</li>
<li>DEF</li>
<li>GHI</li>
<li>JKL</li>
</ol>
</body>
</html>
The webpage corresponding to this code is shown below –
Definition Lists
In order to create lists for index of terms, name/value lists and glossary, the items must appear as they
do in a dictionary. Definition lists is HTML’s way to create such lists.
Three tags namely <dl>, <dt> and <dd> are used in definition lists. The <dl> tag is used to indicate
the beginning of the list. The tag <dt> represents a term and the definition of the term is provided
using<dd>. The list must be closed using the closing tag, </dl>.
Sample code to demonstrate how definition lists may be created is provided below for your
reference.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Definition List</title>
</head>
<body>
<dl>
<dt><b>HTTP</b></dt>
<dd> Hyper Text Transfer Protocol</dd>
<dt><b>HTML</b></dt>
<dd> Hyper Text Markup Language</dd>
</dl>
</body>
</html>
The webpage corresponding to this code is shown below –
Chapter 11: Links

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.

Internal Style Sheet


This is the preferred method of usage when you wish to apply a CSS to a single HTML document. As
mentioned previously, in this method, the style sheet is defined in the header section of the HTML
document using the <style> tag. It is important to mention here that if there is an external style sheet
with similar style rules, the internal style sheet overrides the same.
Sample code to illustrate how internal style sheets can be implemented is given below –
<!DOCTYPE html>
<html>
<head>
<title>Demo: Internal CSS</title>
<style type = "text/css"> .
red {
color: red;
}
.thick{
font-size:20px;
}
.green {
color:green;
}
</style>
</head>
<body>
<p class = "thick">Thick</p>
<p class = "red">Red</p>
<p class = "thick green">Thick and Green</p>
<p class = "green">Green</p>
</body>
</html>

External Style Sheets


This is the preferred method for embedding CSS in HTML if you want a common style to be used for
many webpages. This will reduce the scope of error and repetitive coding effort. As mentioned
previously, the externam style sheet is a file created with the extension .css and needs to be linked to
HTML document using the <link> tag for it to be used appropriately.
Sample CSS file is given below for your reference.
.red
{
color: red;
}
.thick
{
font-size:20px;
}
.green
{
color:green;
}
This CSS file defines three CSS rules, which will apply to three different classes of HTML tags.
Their usage in the HTML file has been demonstrated in the code given below –
<!DOCTYPE html>
<html>
<head>
<title>Demo: External CSS</title>
<link rel = "stylesheet" type = "text/css" href = "/html/sample.css">
</head>
<body>
<p class = "thick">Thick</p>
<p class = "red">Red</p>
<p class = "thick green">Thick and Green</p>
<p class = "green">Green</p>
</body>
</html>

Inline Style Sheet


HTML also supports an attribute called style, which can be used to embed CSS in specific elements
of an HTML document. Therefore, this is the preferred method of usage when you wish to style
specific elements of the webpage. If there is external CSS and internal CSS available with the same
rules defined, then the inline CSS overrides both of them. Sample code to illustrate how inline style
sheets can be used to style specific elements of a webpage is provided below for your reference.
<!DOCTYPE html>
<html>
<head>
<title>Demo: Inline CSS</title>
</head>
<body>
<p style = "font-size:20px;">Thick</p>
<p style = "color:red;">Red</p>
<p style = "color:green;font-size:20px;">Thick and Green</p>
<p style = "color:green;">Green</p>
</body>
</html>

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

Learn Java in 2 hours and Start Programming


Today

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!  

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: Getting Started With Java

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

Requirements to Get Started


In order to get started with Java programming, you need to first have a working computer with Linux
or Windows or Macintosh. On this system, you are going to use two tools for Java programming. The
first of these tools is a text editor. If you are working on Windows, you can use Notepad.
For other operating systems, you can try TextEdit or VI or whichever text editor is locally available.
The second requirement for Java programming is Java 8. You will need to install Java 8 on your
system. If you do not wish to work on a local environment setup, you can also try one of the online
options available to compile and run your java programs.

Getting a Local Setup Ready


Assuming that you have the system ready and you already have a text editor installed on the system,
we are directly jumping to the installation of Java on the system. To start with, you will need to
download Java. Java SE is the free version that you can download using the link that Google Search
for the same provides. Be sure to download the version that is developed for your operating system.
Once the download is complete, you will have an executable, which you are required to run for
installation. Upon completion of installation, you will get a message stating the same. However, you
are not done yet. Java will not work until you set environment variables. You can set the environment
variables on your system using the following instructions –
Windows
In all probability, the Java version that you installed by clicking on the .exe file that came along with
the installation package must have installed in the directory: c:\Program Files\java\jdk. Assuming this,
you just need to open properties by right clicking on ‘My Computer’. In the dialog box that appears,
open ‘Advanced’ and go to ‘Environment variables’. Append the existing contents of the field by ‘,
c:\Program Files\java\jdk\bin’.
Linux/FreeBSD/Unix/Solaris
As a rule, the path of the environment variable is the path at which the binaries of the Java installation
are placed. You can look for these binaries on your system to get the actual path and then edit the
.bashrc file. After you open this file using any text editor, you need to add the statement:
export PATH = /path/to/java:$PATH
While the standard way to run Java programs is to create .java files in Notepad or any text editor for
that matter and then execute the file using command-line commands. However, over all these years,
several IDEs have also come into existent to make this task hassle-free for the programmer. Netbeans
and Eclipse are two such popular IDEs. You can read about them online to see if they interest you.
Chapter 2: Writing Your First Java Program

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 –

Assert abstract Break boolean

Catch char byte case

const class Default continue

else enum do double

final extends Float finally

if implements For goto

instanceof import Interface int

new package long native

protected private Return public

strictfp super short static

synchronized switch Throw this

try void throws transient

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.

Primitive Data Types


Java supports eight primitive data types and there is a keyword corresponding to each of these data
types to allow declaration of variables under this data type. These data types include –
byte
Maximum value = 127 (inclusive)(2^7 -1)
Minimum value = -128 (-2^7)
8-bit signed 2’s complement integer
Default value = 0
This data type is generally used in cases where memory is to be saved.
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an integer.
short
Maximum value = 32,767 (inclusive) (2^15 -1)
Default value = 0.
Minimum value = -32,768 (-2^15)
16-bit signed 2’s complement integer
It is another data type that is used when memory saving is desired.
int
Default value = 0
Maximum value = 2,147,483,647(inclusive) (2^31 -1)
32-bit signed 2’s complement integer.
Minimum value = - 2,147,483,648 (-2^31)
This is the default data type used for all integral values.
long
Default value is 0L
Minimum value = -9,223,372,036,854,775,808(-2^63)
64-bit signed 2’s complement integer
Maximum value = 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
This is used when the variable is expected to hold large numbers.
float
Default value = 0.0f
32-bit IEEE 754 floating point
Single-precision
This data type is used as the default data type for storing floating point numbers.
The use of this data type for storing values that require precise calculations must be avoided.
double
64-bit IEEE 754 floating point
Double-precision
Default value = 0.0d
This data type is used for variables that need to store decimal values. However, like float,
the value of variables stored using double may vary. Thus, these data types are not used for
critical calculations like that concerning currency.
boolean
Default value = false
1 bit
Possible values: True and False
This data type is used for implementing flags.
char
Maximum value = '\uffff' (or 65,535 inclusive)
Minimum value = '\u0000' (or 0)
16-bit Unicode character
This data type is specifically used for storing characters.

Reference Data Types


As the name suggests, reference variables that variables that are used for accessing an object. They
are usually created using class constructors and their type, once defined, cannot be changed. Array
variables and class objects are reference variables. Lastly, the default value in this case is null.

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.

Making Use of Command Line Arguments


There are some programs that require you to pass parameters while executing the program at runtime.
Such parameters can be passed to the program in the form of command line arguments. These
parameters are given to the program along with the name of the program while giving the execution
command on the command line.
The manner in which these parameters can be accessed inside a program has been shown in the
sample code given below.
public class commandLineArgDemo {
public static void main(String args[]) {
for(int x = 0; x<args.length; x++) {
System.out.println("args[" + x + "]: " + args[x]);
}
}
}
Give the following command from the command line to execute the program and see what result you
get.
$java commandLineArgDemo 200 100 10 8 7 6 this is
The finalize () Method
You are dealing with a lot of objects in Java programming and all these objects take up their space in
the memory. If you are working on a large scale code, you may be required to clear up the space
occupied by these objects before terminating the program. To facilitate this operation, a garbage
collector method is available in Java, which is called finalize() method.
This method can be used to implement all the operations that you would like the program to do before
it terminates. Some of these operations include closing all the files opened, deleting all the objects
created and releasing any other memory occupied by program elements. This method is implemented
in the following manner –
protected void finalize( ) {
/*Implementation*/
}
The access modifier ‘protected’ is used in the declaration of the finalize() method to prevent any
external program from destroying the code even before it executes.

Declaration Rules for Source File


There are some rules that you need to follow while writing import statement, class declarations and
package statements in the source file. These rules are as follows –
A source file cannot have more than one public class.
There are be many non-public classes in a source file.
The name of the source file should be same as the name of the public class in that file.
Moreover, the extension of the file should be .java.
If you are working on a package and the class being implemented as part of the package, then
the first statement in the source file must be a package statement.
The package statement must be the first statement in the source file. Any other import
statements must follow this package statement. Lastly, the class implementation must be
present.
It is important for you to understand that the package and import statements are common to all
the classes in the source file. It is not possible to have different package and import
statements for different classes in one source file.
Before we end this discussion, let us give you a closing statement on packages. It is just a form of
classification for interfaces and classes. When you work on large Java projects, the use of packages
helps in organizing the code and making it manageable as well as readable.
When you are using a class in a source file, but the implementation of the class is present in another
file, then you will need to tell the compiler the location of this file. This is where import statements
get their use. Using import statement, you link source files and classes that are used in the concerned
source file, but their implementation is present in other files.
Chapter 7: Decision Making

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.

For Loop Implementation


public class forDemo {
public static void main(String args[]) {
int [] numberArray = {100, 300, 500, 700, 900};
for(int i=0; i<5; i++) {
System.out.print(numberArray[i]);
System.out.print(",");
}
System.out.print("\n");
}
}
The output of this code upon execution is as follows –

While Loop Implementation


public class whileDemo {
public static void main(String args[]) {
int [] numberArray = {100, 300, 500, 700, 900};
int i = 0;
while(i<5) {
System.out.print(numberArray[i]);
System.out.print(",");
i++;
}
System.out.print("\n");
}
}
The output of this code upon execution is as follows –

Do While Loop Implementation


public class doWhileDemo {
public static void main(String args[]) {
int [] numberArray = {100, 300, 500, 700, 900};
int i = 0;
do {
System.out.print(numberArray[i]);
System.out.print(",");
i++;
} while (i<5);
System.out.print("\n");
}
}
The output of this code upon execution is as follows –

Enhanced For Loop


Java also supports an enhanced loop structure, which can be used for array elements. The syntax for
this loop construct is –
for(declaration : expression) {
/*Body*/
}
The declaration part of the Enhanced for loop is used to declare a variable. This variable shall be
local to the ‘for loop’ and must have the same type as the type of the array elements. The current value
of the variable is always equal to the array element that is being traversed in the loop. The expression
is an array or a method call that returns an array.
Sample implementation of the enhanced for loop has been given below -
public class forArrayDemo {
public static void main(String args[]) {
int [] numberArray = {100, 300, 500, 700, 900};
for(int i : numberArray ) {
System.out.print( i );
System.out.print(",");
}
System.out.print("\n");
}
}
The output of this code upon execution is as follows –
Chapter 9: File Handling

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.

Implementing Multiple Catch Blocks


A block of code may lead to multiple exceptions. In order to cater for this requirement,
implementation of multiple catch blocks is also allowed. The syntax for such implementation is given
below.
try {
/*Protected Code*/
}catch(ExpType1 exp1) {
/*Catch block 1*/
}catch(ExpType2 exp2) {
/*Catch block 2*/
}catch(ExpType3 exp3) {
/*Catch block 3*/
}
The syntax shown above has illustrated the implementation of three catch blocks. However, you can
implement as many catch blocks as you want. When this code is executed, the protected is executed. If
an exception occurs, the type of exception is matched with the exception of the first catch block.
However, if the exception type does not match, the catch block 1 is ignored and the exception type for
the second catch block is tried for matching. Whichever catch block has the same exception type as
that of the raised exception, the corresponding catch block is executed.

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 programming language that is designed for developing network-centric applications.


There is automatic integration of JavaScript with Java. In fact, this programming language
complements Java. Moreover, in order to implement JavaScript, the code needs to be merged into an
HTML file. The two main features of this programming language are its cross-platform nature and
open-source availability.
This book is an introductory course on JavaScript that aims to teach you how JavaScript works and
can be used for development of web applications and dynamic web pages. Although, you don’t need
to have any prior experience of working in JavaScript to read this book, it shall be a good idea to
have some knowledge of object oriented programming principles and online application
development. Besides this, since JavaScript is embedded in HTML, it is important to know HTML
basics to get the best out of this book.
As we embark on this journey, it is a humble advice to you that you must try all the examples given in
this book. It is impossible to learn a programming language unless you actually see the code and get
down to execute it. The use of a personal setup for JS development and testing is recommended.
However, you may also use one of the online options that are available for this purpose. We hope this
book achieves the objectives that you had set when you decided to pick it up. We wish you happy
programming and bug-less 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: Basics of JavaScript

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.

ECMA-262 Specification for JavaScript


The core JavaScript language has been standardized by ECMA-262 Specification, according to
which JavaScript is –
Designed to facilitate development of network-centric applications.
Lightweight.
Interpreted and not compiled.
Cross-platform
Open
Besides this, it needs to be integrated with HTML and Java and complements these two programming
languages well.

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.

JavaScript vs. Traditional CGI Server-Side Scripting


Another type of client-server interaction scripting is traditional CGI server-side scripting. However,
JavaScript offers several advantages over the traditional scripting. Javascript reduces the response
time by performing functions like field checking and trapping user input such as link navigation and
button clicks at the client end. The use of JavaScript offers many advantages. Some of these include –
Since the user input is validated at the client end, server is contacted for a query only once
the query has been adjudged as valid. This reduces server traffic and in turn decreases the
server load.
Since the page immediately responds if the user has inputted a wrong value, the user does
have to wait for the page to reload to get a response or know that the value they have entered
are correct.
JavaScript allows trapping of user events, which also means that it allows pages to be
reactive to hovers. As a result, the webpages are more interactive than ever before.
The inclusion of interactive elements like sliders and drag-and-drop components makes the
interfaces extremely rich and appealing.
With that said, JavaScript also lacks some features. For instance, file reading and writing are not
supported. This feature has been left out intentionally for the simple reason that allowing files
interactions can lead to serious security issues. Besides this, JavaScript also lacks multi-processor
ability and multithreading. Lastly, JavaScript is not a proper programming language because of which
it cannot be used for development of comprehensive networking applications.

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

As mentioned previously, JavaScript needs to be embedded in the HTML document or has to be


referenced from the same. In order to embed the script, the script needs to be placed with the script
tag, which looks like –
<script>…</script>
The script enclosed within these tags must be placed inside the HTML document. Although, this script
can appear anywhere inside the HTML document, its placement inside the <head>…</head> is
recommended. All the JavaScript code written within the <script>…</script> block is interpreted by
the browser. Two attributes can be provided along with the script tag. These attributes are –
Type
The type attribute is used to specify the scripting language that is being used. In this case, type must be
set to the value “text/javascript”.
Language
This attribute has now been phased out. However, earlier versions of HTML still use it. Its value
must typically be set to “javascript”.
The JavaScript part of the code will now look like –
<script language="javascript" type="text/javascript">

</script>

Writing Your First JavaScript


Assuming that you have some experience of coding in HTML, let us work through our first example.
This piece of code prints ‘Hello World!’ As you can see, the code is embedded into an HTML
document. The output for the code is shown in the image that appears below it.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World..")
//-->
</script>
</body>
</html>

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.

Line Breaks and Whitespaces


You are free to use whitespaces, tabs and newlines in your code to make it readable and well
organized. These characters are completely ignored by JavaScript.

Optional Use of Semicolons


Most conventional programming languages like C, Java and C++ require you to place semicolon at
the end of each statement to indicate the termination of an statement. However, in Java, if you have
written code in such a manner that each statement is on a different line, then you can omit the use of
semicolons. Example of this concept is the code shown below –
<script language="javascript" type="text/javascript">
<!--
variab1 = 15
variab2 = 35
//-->
</script>
However, if all the statements are written in continuity, then you must use semicolons to tell
JavaScript where a statement ends and a new one starts. Sample code to demonstrate the use of
semicolon is given below –
<script language="javascript" type="text/javascript">
<!—
variab1 = 15;
variab2 = 35;
//-->
</script>
With this said, it is important to mention that the use of semicolon is recommended as it is considered
a good programming practice.

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.

Internet Explorer (IE)


In order to enable or disable JavaScript on IE, you need to follow the steps given below –
In the IE panel, go to Tools and from the menu, open Internet Options. Look for Security tab and select
the same. Choose the button named Custom Level. Now scroll down and you will see an option of the
name, Scripting. Under this heading, select the radio button that says Active Scripting. Click ok and
you will be back to the browser.
If you wish to disable JavaScript, you need to follow the same set of steps and at the point where you
choose Active Scripting you must choose the Disable button.

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’.

Programming in JavaScript for Non-JavaScript Browsers


If you are writing a JavaScript and the same is run by a user on a non-JavaScript browser, then you
can print a message for the user with the help of the <noscript> tag. This concept can be implemented
in the following manner.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World…")
//-->
</script>
<noscript>
Warning: JavaScript Required!
</noscript>
</body>
</html>
This message ‘Warning: JavaScript Required!’ will be displayed to the user if the user attempts to run
the script on a non-JavaScript browser.
Chapter 4: Placement of JavaScript in Files

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>

Writing JavaScript into External Files


The more pages you have in your website, the more you will realize that you are writing the same
JavaScript code in all these different pages or at least some of these pages. JavaScript allows you to
manage identical code used in different HTML documents by writing the JavaScript code in external
files, which can then be linked with the page to call the required JavaScript functionality. You can
link external files by using the src attribute of the script tag. Sample code to illustrate this
functionality has been given below.
<html>
<head>
<script type="text/javascript" src="sample.js" ></script>
</head>
<body>
</body>
</html>
Here, sample.js is the JavaScript file containing the script. The code within this file can be used by
the HTML document just like you used the JavaScript written within the script tag. Please note that the
JavaScript code needs to be written into any text file and must be saved with the extension .js. For
instance, your sample.js can look like this –
function printHW() {
alert("HelloWorld!")
}
Chapter 5: Variables

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.

Declaration and Initialization of Variables


The containers that hold values of different data types are called variables. The data concerned can
be manipulated by accessing the same with the help of containers. As a rule, you must declare every
variable that you are using in the program, before the first use. In order to declare variables, var
keyword is used. Sample usage of this keyword has been illustrated in the code given below –
<script type="text/javascript">
<!--
var emp_name;
var emp_salary;
//-->
</script>
Multiple variables can also be declared in the same line in the manner shown below –
<script type="text/javascript">
<!--
var emp_name, emp_sal;
//-->
</script>
Initialization of variables can be performed at the time of declaration or later in the program as and
when the programmer wishes to use the variable. Examples of both these cases have been given
below.
<script type="text/javascript">
<!--
var emp_name = "James";
var emp_sal;
emp_sal = 5000.25;
//-->
</script>
Please note that a variable can be declared only once in the program. Re-declaration is not allowed.
Subsequently, the use of var keyword for a variable can also be done only once. Unlike in the case of
other programming languages, you don’t need to specify the data type of the variable at the time of
declaration. You can put any data in any variable. In fact, a variable might hold a string in one part of
the program and you may put a number into it, if you desire, in another part of the program. JavaScript
is an un-typed language and all such data related issues are automatically handled.

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.

Keywords or Reserved Words in JavaScript


Just like other programming languages, some words are reserved for use. These keywords have been
given below.

else abstract switch instanceof

int Synchronized boolean enum

Export break this interface

long throw byte Extends


False case throws native

new Transient catch Final

Finally char true null

package try class Float

For const typeof private

protected Var continue Function

Goto debugger void public

return volatile default If

implements delete while short

static with do import

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 –

The if else 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, the
expression inside the else if is tested. If the expression returns true, statements inside the else if block
will be executed, else the statements in the else block are executed. The syntax of this construct is as
follows –
if (expression1){
//Statements to be executed if the expression1 returns true
}
else if (expression2){
//Statements to be executed if the expression2 returns true
}
else{
//Statements to be executed if none of the blocks are executed
}
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 if( i<15 ){
document.write("<b>Inside else 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 –
Switch
Switch is a special type of conditional construct that allows the developer to perform an otherwise
heavily nested if…else...if construct in a performance-effective manner. The syntax for
implementation of switch is as follows –
Switch (variable){
case value1:
//statement
break;
case value2:
//statement
break;
case value3:
//statement
break;
default:
//statement
break;
}

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>

Controlling the Loop


Although, once the loop starts, it terminates only when the expression stated for condition holds false,
there are certain ways in which the developer can control the loop. There may be situation where you
might want to terminate the loop in between execution if a special case occurs or you may want to
start a new iteration on the occurrence of a scenario. In order to control and implement all these
conditions, JavaScript has provided continue and break statements.

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.

Dealing With Function Parameters


Information can be passed from the calling code to the function implementation with the help of
function parameters. These parameters are local variables for the function that can be accessed and
manipulated inside the function. Multiple parameters can be passed into a function by separating each
of them with a comma. The sample code, given below, implements a function with two parameters.
<html>
<head>
<script type="text/javascript">
function printHW(emp_name, emp_age) {
document.write (emp_name + " is " + emp_age + " years of age.");
}
</script>
</head>
<body>
<p>Click the button to invoke a function</p>
<form>
<input type="button" onclick="printHW('James', 45)" value="Print name and age">
</form>
</body>
</html>
The output of the code has been illustrated in the image shown below.

On clicking the button, the following output is generated.


Return Statement
Some functions may also return a value. This is implemented using the return statement. Typically, this
statement is the last statement in the function. For example, if you have implemented a function that
adds two numbers and you are sending the two numbers as parameters to the function, then the added
value can be returned by the function.

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.

onClick Event Type


This event type is used to trap events related to the user clicking the left button of the mouse. Many
responses like validations and warnings can be placed against this event to code webpage reactions.
The sample code shown below demonstrates the implementation and use of this event type.
<html>
<head>
<script type="text/javascript">
<!--
function printHW() {
alert("HelloWorld!")
}
//-->
</script>
</head>
<body>
<p>Click the Button!</p>
<form>
<input type="button" onclick="printHW()" value="Print Hello" />
</form>
</body>
</html>
Try to execute this code to see how the dialog box pops up.

onSubmit Event Type


This event type is typically used with forms. As soon as the user clicks on the submit button for the
form, this event type is invoked. Typical responses against this event type include form validation and
related response generation to the user.
The sample code given below demonstrates the implementation and use of the onSubmit event type.
The code implements a valid function. If this function returns true, the form data is sent to the server,
else it returns a warning to the user.
<html>
<head>
<script type="text/javascript">
<!--
function valid() {
//write code for validation
//return true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return valid()">
<input type="submit" value="Submit" />
</form>
</body>
</html>

Onmouseover and Onmouseout


This event type is used to create effects on webpages. Onmouseover is an event that occurs when the
user hovers or brings the mouse to the image or text. On the other hand, Onmouseout is an event that
occurs when the user takes the mouse away from the image or text. The sample code given below
illustrates the implementation and use of this event type.
<html>
<head>
<script type="text/javascript">
<!--
function demomouseover() {
document.write ("Mouse is over the HTML element");
}
function demomouseout() {
document.write ("Mouse is out of the HTML element");
}
//-->
</script>
</head>
<body>
<p>Change the position of the mouse to see how the result changes!</p>
<div onmouseover="demomouseover()" onmouseout="demomouseout()">
<h2> Division encountered! </h2>
</div>
</body>
</html>
Try to execute this code to see how the dialog box pops up.
Standard Events in HTML 5
This section includes a list of JavaScript events and the description of the same for your reference.
This table can be used as quick reference for events implementation.

Attribute Description

Onabort This event is triggered when an event is


aborted.
Offline This event is triggered when the webpage
goes offline.

onbeforeonload This event is triggered when the webpage


first loads.

onafterprint This event is triggered when the webpage is


printed.

onblur This event is triggered when the focus of the


window is lost.

onbeforeprint This event is triggered before the webpage is


printed.

oncanplaythrough This event is triggered when the media


concerned can be played without interruption
due to buffering till the very end.

oncanplay This event is triggered when the media


concerned may be interrupted during play
because of buffering.

onclick This event is triggered when a mouse click


event is trapped.

onchange This event is triggered when an element


experience changes.

ondblclick This event is triggered when a double click


of the mouse is trapped.

oncontextmenu This event is triggered when the context menu


is triggered.

ondragend This event is triggered when the drag


operation is done. It is important to mention
here that this event is triggered at the end of
the drag.

ondrag This event is triggered when an element is


dragged.

ondragleave This event is triggered when an HTML


element is being dragged over a valid drop
target.

ondragenter This event is triggered when an HTML


element is being dragged on a valid drop
target.

ondragstart This event is triggered when the drag


operation starts.

ondragover This event is triggered when the drag


operation starts.

ondurationchange This event is triggered when the media length


is altered.

ondrop This event is triggered when the element is


being dropped.

onended This event is triggered when the media is


played to its completion and has ended.

onemptied This event is triggered when the source of the


media suddenly becomes empty.

onfocus This event is triggered when the window


comes in focus.

onerror This event is triggered on the occurrence of


an error.

onforminput This event is triggered when the user inputs


data into a form.

onformchange This event is triggered when changes are


made to a form.

oninput This event is triggered when the element


receives user input.

onhaschange This event is triggered when changes have


been made to the document.

onkeydown This event is triggered when a key is pressed.

oninvalid This event is triggered on invalid element.


onkeyup This event is triggered on the release of a
key.

onkeypress This event is triggered on the pressing and


release of the key.

onloadeddata This event is triggered on the loading of the


media data.

onload This event is triggered on the loading of the


document.

onloadstart This event is triggered when the browser


starts loading data.

onloadedmetadata This event is triggered when the data related


to the media is loaded.

onmousedown This event is triggered on the pressing of the


mouse button.

onmessage This event is triggered on the triggering of a


message.

onmouseout Triggers when the mouse pointer moves out


of an element

onmousemove This event is triggered on the movement of


the mouse pointer.

onmouseup This event is triggered on the release of the


mouse button.

onmouseover This event is triggered on the movement of


mouse pointer over an element.

onoffline This event is triggered when a document goes


offline.

onmousewheel This event is triggered on the rotation of the


mousewheel.

ononline This event is triggered when the document


come online.
onoine This event is triggered when the document
come online.

onpageshow This event is triggered when the visibility of


the window is attained.

onpagehide This event is triggered when the window is


hidden.

onplay This event is triggered when the media is


about to start playing.

onpause This event is triggered on the pausing of


media data.

onpopstate This event is triggered when the history of the


window changes.

onplaying This event is triggered on the playing of


media data.

onratechange This event is triggered when changes in the


rate of playing of media data are
experienced.

onprogress This event is triggered when the browser is


fetching media data.

onredo This event is triggered when a redo operation


is performed on a document.

onreadystatechange This event is triggered when changes in the


ready state are made.

onscroll This event is triggered when the scrollbar of


the element is scrolled.

onresize This event is triggered when the resizing of


the window occurs.

onseeking This event is triggered when the seeking


attribute is true and the operation of seeking
has begun.

onseeked This event is triggered when the seeking


operation has ended and the value of seeking
attribute has been changed to false.

onstalled This event is triggered when the operation of


fetching media data has experienced an error.

onselect This event is triggered on the selection of an


element.

onsubmit This event is triggered on the submission of a


form.

onstorage This event is triggered on the loading os a


document.

ontimeupdate This event is triggered when the playing


position of the media is changed.

onsuspend This event is triggered when the browser has


been fetching media data, but the operation
was stopped before all the data could be
fetched.

onunload This event is triggered on the user’s leaving


of a document.

onundo This event is triggered when a undo


operation is performed on the document.

onwaiting This event is triggered on stopping of the


playing of media data. However, the browser
expects the operation to resume.

onvolumechange This event is triggered when changes are


made to the volume of media data. This event
is also triggered when the mute button is
clicked.
Chapter 11: Cookies

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.

How Cookies Work


A cookie is data that the server sends to the browser. This data needs to be accepted by the visitor
before it can be stored in the form of a text record on the visitor’s hard disk. When the visitor opens
another page of the same website, the browser sends a cookie to the server and once the server is
able to comprehend this cookie, it instantly knows and remembers all about the user.
As mentioned previously, a cookie is a text record. It contains five records of variable lengths, which
are described below.
Domain
This field contains the domain name of the website.
Expires
This field contains the date when the cookie is expected to expire. However, this field may be left
blank in some cases. In this case, the cookie expires as soon as the visitor quits the browser.
Name-Value
The setting and retrieval of cookies are done in the from of key-value pairs.
Secure
If this field contains the value ‘secure’, there is a restriction on the cookie that a secure server can
only perform its retrieval. On the other hand, if this field is blank, no such restriction exists.
Path
This field indicates the path of the webpage or directory that needs to be used for setting the cookie. If
there is no restriction on which page or directory must be used for cookie retrieval, this field can be
left blank.
The concept of cookies is typically used for CGI programming. There is automatic transmission of
data between the web server and web browser. Therefore, CGI scripts can directly read the cookie
data saved on the client. Cookies are manipulated by using Document object’s cookie property.
Operations like reading, modifying, creating and deleting cookies specific to the current webpage are
allowed in JavaScript.

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.

Setting Expiry Date


Assigning the ‘expires’ attribute of the document.cookie object, a value, can set the time beyond
which the cookie will not be valid. This attribute takes time and date as value. Sample code given
below illustrates how the expiry date of a cookie can be extended by 1 month.
<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 ("Store 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>
The output of the code is illustrated in the image shown below.

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.

Working of Page Redirection


This section gives two examples of code for page redirection. You can study the code to see how
page redirection has been implemented for different scenarios. The first sample code is a simple code
for redirecting a webpage to another webpage.
<html>
<head>
<script type="text/javascript">
<!--
function demoPageRedirect() {
window.location="http://www.google.com";
}
//-->
</script>
</head>
<body>
<p>Click on the button for demo of page redirection…</p>
<form>
<input type="button" value="Page Redirect " onclick="demoPageRedirect();" />
</form>
</body>
</html>
It is a good practice to intimate the users that they are being redirected. In order to do the same, you
will need to display a message on the screen before the new webpage loads. This requires you to
delay the loading of the new page, which can be implemented using setTimeout().
This function when called, delays the execution of the function that follows it in execution. The
sample code given below demonstrates the implementation and working of this function along with
page redirection.
<html>
<head>
<script type="text/javascript">
<!--
function demoPageRedirect() {
window.location="http://www.google.com";
}
document.write("Redirection will have in 5 seconds.");
setTimeout('Redirect()', 5000);
//-->
</script>
</head>
<body>
</body>
</html>
Chapter 13: Dialog Boxes

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.

Dialog Box for Alert Messages


This type of a dialog box is used for giving warning messages to the user. For example, if the user
was filling an HTML form and he or she forgot to enter a field value or gave an incorrect input to a
field, then the alert dialog box can be invoked to give a warning signal or pass an important message
to the user.
The main feature of the alert dialog box is that it has only one OK button, the clicking of which
indicates that the user has read the message. Sample code to demonstrate the working of this concept
has been given below.
<html>
<head>
<script type="text/javascript">
<!--
function demoWarnDB() {
alert ("Warning!");
document.write ("Test message.");
}
//-->
</script>
</head>
<body>
<p>Click on the button to see demo:</p>
<form>
<input type="button" value="Click Demo" onclick="demoWarnDB();" />
</form>
</body>
</html>

Dialog Boxes for Confirmation


This type of dialog boxes are typically used for taking user’s con sent. It consists of two buttons
namely, OK and Cancel. If the user clicks on the OK button, the user is consenting for the action and
the confirm () method of the window will return true. On the other hand, if the user clicks the Cancel
button, then the confirm () method returns false. Confirmation dialog boxes can be implemented in the
following manner.
<html>
<head>
<script type="text/javascript">
<!--
function demoConfirmationDB(){
var returnVal = confirm("Should we continue?");
if( returnVal == true ){
document.write ("Confirmation received!");
return true;
}
else{
document.write ("User wants to discontinue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click for demo: </p>
<form>
<input type="button" value="Click Demo" onclick="demoConfirmationDB();" />
</form>
</body>
</html>

Dialog Boxes for Prompt


The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it
enables you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt () which takes two parameters: (i) a label
which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method
prompt () will return the entered value from the text box. If the user clicks the Cancel button, the
window method prompt ()returns null.
<html>
<head>
<script type="text/javascript">
<!--
function demoPromptDB(){
var returnVal = prompt("Name: ", "enter your name here");
document.write("Name entered by you: " + returnVal);
}
//-->
</script>
</head>
<body>
<p>Click for demo: </p>
<form>
<input type="button" value="Click Demo" onclick=" demoPromptDB();" />
</form>
</body>
</html>
Chapter 14: Page Printing

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

Learn SQL in 2 hours And Start Programming


Today

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!

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 of SQL

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;

SQL ROLLBACK Statement


ROLLBACK;
SQL COMMIT Statement
COMMIT;
Chapter 5: Data Types

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

Data and Time


These data types are used to declare objects that can hold date and time values. The different data
types that are part of this category include –
smalldatetime
datetime
time
date
It is important to note here that the accuracy of smalldatetime is 1 minute while the same for datetime
is 3.33 milliseconds.

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)

Unicode Character Strings


These data types are used to declare objects that can hold Unicode character strings. The different
data types that are part of this category include –
nchar
nvarchar
nvarchar(max)
ntext

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)

Miscellaneous Data types


Besides the above-mentioned, there are some other data types, which are also available as part of
SQL. These data types include –

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;

Inserting Records Into Tables


Now that you know how to create and delete tables, the next thing that you would want to know is
how to insert records in a table to create a working table. The SQL statement used for performing this
operation is INSERT INTO. Each statement of INSERT INTO is used to insert a record into the table.
In fact, multiple records can also be inserted using this SQL statement. The syntax for this SQL
statement is given below –
INSERT INTO t_name (col1, col2, col3,...colN) VALUES (v1, v2, v3,...vN);
Here, col1, col2, col3,...colN are the column names for the table concerned, t_name is the table name
and v corresponds to the field values that are to be inserted to the table. You are not required to give
the name of the column for which the value is being inserted. However, the order of the values must
be in the same order as the order of the fields. The syntax for this SQL statement is as follows –
INSERT INTO t_name VALUES (v1,v2,v3,...vN);
In order to demonstrate how this SQL statement needs to be written and executed, let us take an
example.
INSERT INTO CUST (ID, NAME, AGE, SALARY) VALUES (98701, ‘Rohan’, 45, 50000.00);
INSERT INTO CUST (ID, NAME, AGE, SALARY) VALUES (98675, ‘Amit’, 32, 37000.00);
INSERT INTO CUST (ID, NAME, AGE, SALARY) VALUES (98706, ‘Shayla’, 22, 12000.00);
INSERT INTO CUST (ID, NAME, AGE, SALARY) VALUES (98718, ‘Mathews’, 37, 41000.00);

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];

Selecting Records From Tables


The SQL statement used to retrieve records from a table is SELECT. The result of the query is a table,
which is also known as result-sets. The syntax for performing this operation is as follows –
SELECT col1, col2, colN FROM t_name;
The query shown above outputs the n columns of the records from the table named t_name. In order to
fetch all the fields of the record, then the following syntax can be used.
SELECT * FROM t_name;
Consider the table named CUST with the following set of records.
ID Name Age Salary
98701 Rohan 45 50000.00
98675 Amit 32 37000.00
98706 Shayla 22 12000.00
98718 Mathews 37 41000.00
Now, let us give the query –
SELECT ID, Name FROM CUST;
The output corresponding for this query is as follows –

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

An example of how this can be implemented can be found below.


DELETE FROM CUST WHERE ID = 98675;
This query deletes the record that has the ID = 98675. Now, if you see the contents of the table after
the execution of this query, you will see the following records in the table.

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.

The AND Operator


The AND operator is used as part of the WHERE clause and is typically used when the developer
wishes to filter out records that satisfies both the conditions specified with the AND operator. The
syntax for the implementation of AND conjunctive operator is as follows –
SELECT col1, col2, colN FROM t_name WHERE [cond1] AND [cond2]...AND [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 AND operator. It is important to note that the records that are chosen need to fulfil
both the conditions mentioned as part of the WHERE clause that is using the AND 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 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 –

SELECT DISTINCT col1, col2,.....colN FROM t_name WHERE


[cond];
Here, col is the name of the column, t_name is the name of the table and cond is the condition given
alongside WHERE clause for filtering records on the basis of user requirements. In order to provide
you with examples for this keyword, let us consider the table named CUST with the following data –
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 standard SQL query for displaying the values corresponding to the field ‘NAME’ in the CUST
table is –

SELECT NAME FROM CUST;


The result of the execution of this query shall yield the following table –
As you can see, this result table also has duplicates. You may remove these duplicates using the query
given below.

SELECT DISTINCT NAME FROM CUST;


The result for this query shall be as follows –
Name
Rohan
Amit
Shayla
Mathews

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 –

SELECT DISTINCT NAME FROM CUST ORDER BY NAME;


The execution of this query will generate the following result –
Chapter 16: Joins

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

The data for the table CORDER is assumed to be as follows –


CID ORDER_AMT
98675 3700.00
98706 4200.00
98718 1200.00

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 –

SQL Right Join


In the right join, all the rows of the second table are included in the table even if no match on the same
for the first table are found. From the first 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 right
join is as follows –
SELECT t1.col1, t2.col2... FROM t1 RIGHT 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 right join on
the two table CUST and ORDER given above, the following query needs to be fired.
SELECT ID, NAME, ORDER_AMT FROM CUST RIGHT JOIN CORDER ON CUST.ID =
CORDER.CID;
The result of the execution is as follows –
SQL Full Join
If you need to combine all the fields of both the tables, then a full join needs to be perfomed. This join
operation is a combination of left and right joins. Records from both the tables will be present in the
resultant table. However, for any fields that do not find a match, NULL values are inserted. The syntax
for performing this operation is as follows –
SELECT t1.col1, t2.col2... FROM t1 FULL 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 full join on
the two table CUST and ORDER given above, the following query needs to be fired.
SELECT ID, NAME, ORDER_AMT FROM CUST FULL JOIN CORDER ON CUST.ID =
CORDER.CID;
Some versions of SQL do not support Full Join, which is the case with MySQL. However, MySQL
supports UNION ALL as an alternative to full join.
SELECT ID, NAME, ORDER_AMT FROM CUST LEFT JOIN ORDER ON CUST.ID = ORDER.ID
UNION ALL SELECT ID, NAME, ORDER_AMT FROM CUST RIGHT JOIN ORDERS ON
CUST.ID = ORDER.ID
The output of the query is shown below.

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

Learn Python in 2 hours And Start


Programming Today

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!

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

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 of Python have been described below –


Easy to read, learn and maintain
The presence of simple structures, clearly-defined syntax and English-language keywords makes
Python a easy to learn, read and maintain language.
Availability of Standard Library
The standard library available as part of the Python package is cross-platform and highly portable.
So, irrespective of the platform you decide to work on, be it Macintosh, Microsoft Windows or
Linux/Unix, you should not face any problems in using the inbuilt functionality.
Hardware Portability
Python supports operation on multiple hardware platforms. Moreover, the interface for all the
different hardware platforms is the same. Therefore, minimal effort is required on the programmer’s
end to shift from one hardware platform to another.
Allows Interaction Between Developer and Interpreter
Python code can be tested and debugged using an interactive mode of operation that allows the
programmer to communicate with the interpreter.
Scalable
Unlike shell scripting that only supports small programs, Python enables programmers to write big
programs with ease.
GUI Programming
GUI applications usually require the use of system calls and library functions. The ability of Python to
support and work well with hardware of different configurations allows programmers to write
portable GUI applications.
Databases
Python allows programmers to use a any of the multiple databases supported by it. In fact, Python
supports almost all commercial databases.
Extendable
Small modules can be added to the Python interpreter. In this manner, Python allows customization of
its tools for higher efficiency.

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

As we mentioned previously, Python is available on a wide range of hardware and software


platforms. Therefore, you can work on Python programming irrespective of the hardware or software
platform that you are working on. However, you will have to set up a working environment for the
same. This chapter illustrates the method for setting up a local environment for Python programming.

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.

Setting the PATH


The executable files and programs related to the installation may be placed at different locations.
This makes it difficult for the system to track which path needs to be accessed when. In order to solve
this issue, the OS keeps a search path with it, which it uses for searching executable files, and is
saved in an environment variable. By communicating this variable, the information is made available
to the command shell and other programs that may require it.
This variable is known by the name PATH in Unix and Path in Windows. Please mind the difference
in the case of the letters. This different is present due to the fact that Unix/Linux is case-sensitive and
exactly the name PATH must be used. However, Windows is case-insensitive and as long as the string
is path, the operating system will be fine with it. Lastly, in case of Macintosh, the path details are
automatically handled. The Python directory must be added to your path for invoking the Python
interpreter.

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.

First Python Program


The standard ‘first’ program for learning any programming language is the ‘Hello World!’ program.
Let us write the code and execute the same in interactive and script mode of Python programming.
While working in the interactive mode, all you need to do is type python to invoke the interpreter.
Typing the following command shall print the string ‘Hello World!’ on the screen.
print "Hello World!"
Some versions of Python may require you to place the string to be printed inside parentheses, as can
be seen below –
print ("Hello World!")
Running this command shall yield the following result –

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.

exec and not

assert or finally

for break pass

class print from

global continue raise

def return if

import del try

elif while in

is else with
except Yield lambda

Lines and Indentation


One of the fundamental differences between Python and other programming languages, as far as syntax
is concerned, is that Python does not provide any braces to indicate block of code, which is usually
available to indicate definitions of class and functions. On the contrary, Python enforces flow control
in such cases with the help of indentation.
Any number of statements that appear within a block must be indented by the same number of spaces.
The number of spaces used for this purpose is user’s discretion. An example of how this is done is
given below for your reference.
if True: print "This is True" else: print "This is False"
Both the statements inside the if block are separated by one tab. On the other hand, if you execute the
code given below, you will inadvertently get an error.
if True: print "Answer" print "True" else: print "Answer" print "False"
Therefore, it can be generalized that any number of statements that are indented by the same number of
spaces are assumed to be part of a block.

Multiple Line Statements


As a rule, the newline character is the line termination character and as and when the same is
encountered, it is assumed that the Python statement has terminated. However, if you wish to write
Python statements over a span of multiple lines, you can do so by using the character ‘\’. The presence
of this character at the end of the line indicates that the line is continued. An example of this concept
is given below for your reference.
total = item_1 + \ item_2 + \ item_3
It is important to mention here that statements that are contained within brackets need not use the
continuation character to indicate that the line is continued. When we say, ‘statements with brackets’,
we mean to indicate a statement that is similar to the one written below.
week_day = [‘Sunday’, 'Monday', ' Tuesday ', ‘Wednesday’, 'Thursday', 'Friday']

The Use of Quotations


In order to indicate string literals, you may use single, double or triple quotes. However, be sure to
use the same type of quote to begin as well as end a string literal. For example, if you have started a
string literal with a double quote, you must end the same with a double quote. Mixing types of
quotations will give rise to errors. It is a practice to use triple quotes for string literals that span
across many lines.

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.

Waiting for User


There are many programming scenarios that require you to take input from the user. Python provides a
function for implementing this functionality called the row_input() function. You can implement this
functionality using the syntax shown below.
#!/usr/bin/python raw_input("\nPress a key")
This functionality is usually used to keep the console open until the programmer sees the program
result. The program ends as soon as the user presses a key.

Many Statements on One Line


While you can write a single statement across multiple lines, Python also allows you to write multiple
statements on the same line. However, these statemenets must be separated by semicolon (;). Sample
implementation is given below for your reference.
import sys; x = 'tree'; sys.stdout.write(x + '\n')

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.

Assigning Values to Variables


No explicit declaration is required for reserving memory space for Python variables. Therefore,
every single time you assign a data value to a variable, memory space is automatically assigned to it.
In order to assign a data value to variables, the equal sign (=) is used. On the left of the ‘=’ sign is the
name of the variable that needs to be assigned a value while the right hand side has the data value.
Sample implemenatation is as follows –
#!/usr/bin/python x = 77 # An integer assignment

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.

Standard Data Types in Python


Different types of data requires different data types for storage. For instance, if you wish to store the
age of an employee, you will need a numeric variable. On the other hand, in order to store the
employee’s name, a string variable is required. To suffice such programming scenarios, many data
types are allowed in Python. A data type defines the storage requirements and allowed operations on
the data value concerned. Five data types are allowed in Python, which have been described below.

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.

Data Type Conversion


You may be faced with programming scenarios where you might have to convert an object from one
data type to another. In Python, you just need to use the type name as a function, to perform this. The
built-in functions available in Python include –
int(x, [,base])
This function converts the data type of x to int. In case x is string, base defines the base of the
converted integer.
long(x, [,base])
This function converts the data type of x to long. In case x is string, base defines the base of the
converted long.
float(x)
This function converts the data type of x to float.
complex(real [,imag])
This function creates a complex number.
str(x)
This function converts the object x to its string representation.
repr(x)
This function converts the object x to an expression string.
eval(str)
This function evaluates a string and converts it into an object.
tuple(s)
This function converts s to a tuple.
list(s)
This function converts s to a list.
set(s)
This function converts s to a set.
dict(d)
This function creates a dictionary where d is a sequence of key-value pairs or tuples.
frozenset(s)
This function converts s to a frozen set.
chr(x)
This function converts x to character.
unichr(x)
This function converts x to Unicode character.
ord(x)
This function converts a single character x to integer.
hex(x)
This function converts a integer x to hexadecimal string.
oct(x)
This function converts a integer x to octal string.
Chapter 5: Operators

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.

Operator Precedence in Python


The order of precedence for operators in Python is described below. The list is ordered in such a
manner that the operator coming before is higher in prececdence than the operator that comes after.
Moreover, the operators listed under the same point have the same precedence order.
Exponentiation (**)
Unary Operators like Complement (~), Unary Plus (+@) and Unary Minus (-@).
Floor (//), Division (/), Modulus(%), Multiplication (*) and Division (/)
Addition (+) and Subtraction (-)
Bitwise Left Shift (<<) and Right Shift (>>)
Bitwise AND (&)
Bitwise OR (|) and Exclusive OR (^)
Comparison Operators like Greater Than (>), Less Than (<),Greater Than Or Equal To (>=)
and Less Than Or Equal To (<=).
Equality Operators like Equal To (==) and Not Equal To (!=, <>)
Assignment Operators like Equal To (=), ADD and Assignment (+=), SUBTRACT and
Assignment (-=), MULTIPLY and Assignment (*=), DIVIDE and Assignment (/=),
MODULUS and Assignment (%=), FLOOR and Assignment and Exponent and Assignment
(**=),
Identity Operators like Is and Not Is
Membership Operators like In and Not In
Logical Operators like NOT, OR and AND.
Chapter 6: Decision Making

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.

Single Statement Suites


The complete if statement can be specified as one statement if there is only one statement in the if
block. An example of such a statement is given below for your reference.
var_1 = 109 if ( var_1 == 109 ) : print "The If Condition is True!"
Upon execution, this code shall produce the following result –
Chapter 7: Loops

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

The import Statement


Any Python source can be used as a module for executing the import statement, which is used in
another Python source file. The syntax for using the import statement is as follows –
import module1[, module2[,... moduleN]
Upon encountering this statement, the interpreter looks for the module using the search path. If the
module is found, the same is imported into the source file concerned. It is important to mention here is
the search path is a list of directories that are used by the interpreter to look for the module. For
example, if you wish to import the module support.py in your source, you need to give the following
import statement.
import support
Once imported, the functions of the module can be called using a statement similar to the one given
below –
support.print_func("Hello")
No matter how many times you import a module, it is loaded just once. In this manner, the system
avoids multiple executions of the module.

The from…import Statement


In case you wish to import specific attributes of a module to the present namespace, you can do so
using the from…import statement. The syntax for this statement is given below for your reference –
from module_name import name_1[, name_2[, ... name_N]]
Sample implementation of this statement is as follows –
from module_1 import sum_add
Here, module_1 is the name of the module and sum_add is an attribute of the module. In this manner,
you can just import the attribute you require without giving the system an overhead of importing the
entire module.

The from…import * Statement


All names from the specified module can be imported into the current namespace by using the
‘from…import *’ statement. Sample implementation of this statement is given below for your
reference.
from module_1 import *
Although, this statement is the best way to import all the names from a module, but its use must be
avoided because of the overhead that it may incur.

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;

Scoping and Namespaces


As we already know, a variable typically maps to a Python object. A namespace is a list of variables
and the objects they correspondingly map to. In other words, a namespace is a dictionary that contains
keys (variables) and values (objects).
Any statement in Python has access to the global and local namespace. It is important to note here that
the global and local namespace may have the same name. In such a scenario, the local namespace is
give preference. Besides this, every function has a local namespace. When it comes to class methods,
they follow the same rules as functions for namespaces and scoping.
A variable’s scope is decided on the basis of an intelligent guess. For instance, if a variable is
assigned a value inside a function, then it is assumed that the variable belongs to the local namespace
of the function. If you wish to assign value to a global variable inside a function, you must first
declare it using the keyword global.

The dir() Function


This is an inbuilt function that returns a sorted list of names that are present in a module. Therefore,
whenever you use this function, a list of modules and the names and variables available in the module
is generated.

The locals() and globals() Functions


If you wish to see the global and local namespaces registered with the system, you can use the
globals() and locals() functions respectively. The values returned by these functions depend on the
place from where they are called.
For example, if you call the locals() function from within a function, it will return the names of all the
variables that can be accessed from within this function. On the other hand, if globals() function is
used from within a function, it will return all the global names for which the function has access.
Lastly, both these functions return a dictionary, which has key-value pairs of identifiers and their
attached objects. The names can be derived from this dictionary using the keys() function.

The reload() Function


As we mentioned previously, no matter how many times you import a module, the top-level code of
the module is executed only once for a source. There may be scenarios where you may want to re-
execute this top-level code of the module. The reload() function allows you to perform this operation.
The syntax for using this function is given below for your reference.
reload(name_of_module)

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

Learn PHP in 2 hours And Start Programming


Today

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.

Characteristics and Uses


Some of the key uses of PHP include –
Supports easy handling of forms, allowing data gathering, data saving on the file, sending
data via email and returning data to the user.
Supports execution of system functions like opening, creating, deleting and writing onto files
on the system.
Supports database operations like adding, modifying and deleting elements inside the
database via PHP.
Allows access and setting of cookies.
Allows placing of restrictions on some pages that can be set by the programmer as
inaccessible for the user.
Allows data encryption.
PHP has five key characteristics namely flexibility, efficiency, security, simplicity and familiarity.
First PHP Program
To start with, let us look the at the simplest PHP script and try to understand how the same is working.
This script prints the string ‘Hello World!’ on the screen. As we have already mentioned, PHP scripts
are embedded in HTML. What this means is that PHP statements are written inside normal HTML
code. Sample code is given below for your reference.
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<?php echo "Hello, World..";?>
</body>
</html>
Upon execution, this code yields the following result.

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.

Installing Parser for PHP


To start with, the first thing that you must do is open the browser and type the following address in the
browser’s address box.
http://127.0.0.1/info.php
If the broswer opens a valid webpage with PHP-related information, then it can be assumed that the
Web server and PHP are properly installed on the system. On the other hand, if this is not the case,
then you will have to install Apache and PHP for your system. You can simply Google for Apache and
PHP installation on the platform that you are using. This shall give you a set of instruction, which you
can follow step by step.
Chapter 2: Syntax

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>"); }

Executing a PHP Script


You can execute a PHP script from the command prompt. Assuming that you have placed your code in
a PHP file named test.php. The code present in the file is as follows –
<?php echo "Hello PHP.."; ?>
In order to run the script, you need to give the following command from the prompt.
$php test.php
The execution of this command will print the text Hello PHP.. on the screen.
Chapter 3: Variables

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.

Giving Names to Variables


There are specific rules that need to be followed while naming a variable. These rules include –
The name of a variable can only begin with underscore (_) or an alphabets. The use of
numbers as the first character in the name of a variable is not allowed.
The use of special characters like %, + and -, in addition to others, is also not allowed. In
other words, apart from underscore, you cannot use any other special character.
Lastly, there is no limit on the size of a variable.
Chapter 4: Constants

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.

Difference Between Constants and Variables


With the mention of constants, its comparison with variables is obvious. Some of the key differences
are as follows –
The mentioning of a dollar sign ($) is the first evident difference between constants and
variables. Variables have to be preceded by a dollar sign while constants are specified
without it.
Variables are assigned values using the simple assignment. However, constants cannot be
defined in this manner. Constants can only be defined using the define() function.
Variables can be assigned, reassigned and un-defined. However, constants cannot be
modified in any way during the course of the program.
The variable scoping rules do not apply to constants. They can be accessed and defined
anywhere.

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.

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.

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.

The else if Statement


Sometimes many conditions have to be tested together. The else if construct allows the programmer to
mention many conditions in a single if block. The syntax for implementing else if statement is given
below –
if (condition1)
Code block to be executed if the condition1 is found true;
else if (condition2)
Code block to be executed if the condition2 is found true;
else
Code block to be executed if both the conditions are 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!";
elseif ($d == "Sun")
echo "Happy Sunday!";
else
echo "Have a nice day anyway!";
?>
</body>
</html>
Upon execution, this code yields the following result.
Switch Statement
The switch statement is a very useful programming construct in scenarios where a single variable is
to be tested for different values. The same programming scenario can be implemented using nested if
statements. However, the switch is a more efficient option for this as it creates a table of values and
according to the value received, the execution directly jumps to the code block corresponding to that
value.The syntax for using the switch statement is as follows –
switch (expression){
case value1:
Code block if the expression evaluates to a value equal to value1;
break;
case value2:
Code block if the expression evaluates to a value equal to value2;
break;
default:
Code block if the expression evaluates to a value that is not equal to value1 or value2;
}
Sample code that implements this concept has been given below for your reference.
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "It is Monday!";
break;
case "Tue":
echo " It is Tuesday!";
break;
case "Wed":
echo " It is Wednesday!";
break;
case "Thu":
echo " It is Thursday!";
break;
case "Fri":
echo " It is Friday!";
break;
case "Sat":
echo " It is Saturday!";
break;
case "Sun":
echo " It is Sunday!";
break;
default:
echo "Unpredictable result!";
}
?>
</body>
</html>
Upon execution, this code yields the following result.
Chapter 7: Loops

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.

The for Statement


The for statement is typically used in programming scenarios where a block of code needs to be
repeatedly executed until a condition is true and the condition involves a looping variable, which is
initialized and updated as part of the for statement. The syntax for this looping construct is given
below –
for (initialization; condition; expression for updating looping variable)
{
Block of code;
}
The initialization statement initializes the looping variable by declaring it and giving it an initial
value. The condition is the expression that needs to yield TRUE for the loop to execute. If the
condition is found FALSE, the loop is terminated. The third part of the looping statement includes the
expression that updates the looping variable. The looping variable is typically declared as $i. Sample
implementation of this programming construct is given below for your reference.
<html>
<body>
<?php
$x = 0;
$y = 0;
for( $i = 0; $i<3; $i++ ) {
$x += 1;
$y += 2;
}
echo ("The values of x and y are x = $x and y = $y" );
?>
</body>
</html>
Upon execution, the code yields the following output –

The while Statement


The while statement is typically used in programming scenarios where a block of code needs to be
repeatedly executed until a condition is true. The syntax for this looping construct is given below –
while (condition)
{
Block of code;
}
The condition is the expression that needs to yield TRUE for the loop to execute. If the condition is
found FALSE, the loop is terminated. Sample implementation of this programming construct is given
below for your reference.
<html>
<body>
<?php
$x = 0;
$y = 0;
$i = 0;
while( $i <3 ) {
$x += 1;
$y += 2;
$i++;
}
echo ("While Loop: The values of x and y are x = $x and y = $y" );
?>
</body>
</html>
Upon execution, the code yields the following output –

The do…while Statement


The do…while statement is typically used in programming scenarios where a block of code needs to
be repeatedly executed until a condition is true. However, the one point that sets the do…while and
while loops apart is the fact that the condition is tested after one iteration for the former. On the other
hand, in case of while loop, the condition is tested before performing the first iteration. Therefore, the
do…while loop is executed at least once. The syntax for this looping construct is given below –
do{
Block of code;
} while (condition);
The condition is the expression that needs to yield TRUE for the loop to execute. If the condition is
found FALSE, the loop is terminated. Sample implementation of this programming construct is given
below for your reference.
<html>
<body>
<?php
$x = 0;
$y = 0;
$i = 0;
do{
$x += 1;
$y += 2;
$i++;
} while( $i <3 );
echo ("Do…While Loop: The values of x and y are x = $x and y = $y" );
?>
</body>
</html>
Upon execution, the code yields the following output –

The foreach Statement


In order to loop through array, the foreach statement can be used. Every pass or iteration of the loop
takes in the current value of the array and increments the pointer to the array by one element.
Therefore, in the next pass, the next element will be processed. The syntax for implementing this loop
construct is as follows –
foreach (array as value) {
Code to be executed;
}
Sample implementation of this programming construct is given below for your reference.
<html>
<body>
<?php
$x_array = array( 9, 8, 7, 6);
foreach( $x_array as $value ) {
echo "Value of the element for this iteration = $value <br />";
}
?>
</body>
</html>
Upon execution, the code yields the following output –

The break Statement


In order to terminate loops prematurely, the keyword break may be used. It is placed inside the loop
block and is usually used as a conditional loop breaking statement. In other words, an if block is
implemented and if the condition inside the if statement is TRUE, the loop breaks, else the loop
continues to function as normal. Once the break statement is encountered, the first statement that
appears after the loop block is executed. Sample implementation to help you understand the concept
better is provided below.
<html>
<body>
<?php
$i = 0;
while( $i < 5) {
$i++;
if( $i == 2 )
break;
}
echo ("Loop stopped at i = $i " );
?>
</body>
</html>
Upon execution, the code yields the following result –

The continue Statement


In order to halt the execution of present loop and take the execution to the next iteration, the keyword
continue may be used. It is placed inside the loop block and is usually used as a conditional loop
manipulation statement. In other words, an if block is implemented and if the condition inside the if
statement is TRUE, the present iteration halts, else the loop continues to function as normal. Once the
continue statement is encountered, the control is shifted to the loop statement. Sample implementation
to help you understand the concept better is provided below.
<html>
<body>
<?php
$i = 0;
while( $i < 5) {
$i++;
if( $i == 2 )
continue;
echo ("Loop executed for i = $i <br />" );
}
?>
</body>
</html>
Upon execution, the code yields the following result –
Chapter 8: Arrays

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.

Finding String Length


PHP provides a function strlen(), which can be used for finding the length of strings. This
functionality has been used in the sample code given below.
<?php
echo strlen("I am possible.");
?>
The result of execution of this sample code is illustrated in the image given below.

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.

Finding Character or String in a String


PHP provides a function named strpos() to search for a character or string within a string. If the string
or character is not present, FALSE is returned. However, as and when the first match is found, the
position of the character or the first character of the string is returned. Sample code to demonstrate the
functioning of this concept is given below –
<?php
echo strpos("I am possible","possible");
?>
Upon execution, the code yields the following result –
You must be wondering that the position of the letter p of possible in the string “I am possible” is 6,
but the result is 5. The reason for this is that the position of the first character of the string is 0 and
accordingly, the position of all the other characters is one less than their actual value. be sure to
remember this point while programming with strings as you may end up having a few logical errors in
your program, otherwise.
Chapter 10: Functions

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.

How to Create Functions in PHP


In order to create functions in PHP, the name of the function must be preceded by the keyword
function and followed by its definition, which must be enclosed with curly braces. Please note that
every function that you intend to use in your PHP script must be defined before its first usage. To help
you understand how functions are created in PHP, sample code has been provided below.
<html>
<head>
<title>How to Create Functions in PHP</title>
</head>
<body>
/*Function Defined*/
<?php
function DisplayMsg() {
echo "Have a great day!";
}
/*Function Called*/
DisplayMsg();
?>
</body>
</html>
When executed, the code will give the following result –

Giving Input to Functions


Like functions in any other programming language, it is possible to give parameters to functions.
Moreover, you may pass any number of parameters that you want. These parameters are like local
variables for the function and can be accessed freely by the function. Sample implementation of how
parameters can be sent to a function is given below.
<html>
<head>
<title>Implementing Functions with Parameters</title>
</head>
<body>
<?php
function demoFunction($num_1, $num_2) {
$result = $num_1 + $num_2;
echo "Result of addition : $result";
}
demoFunction(5, 6);
?>
</body>
</html>
The execution of this function shall give the following output –
As the passed arguments act like local variables to the function, a local copy of the variable is made
for the function. The values of the variables, if edited inside the function, are available in their edited
versions only inside the function.
In case you want the variables to reflect the changes even outside the function, then parameters need
to be passed by reference to the function. Sample code to demonstrate how parameters can be passed
by reference to a function is provided below.
<html>
<head>
<title>Passing Arguments to Function by Reference</title>
</head>
<body>
<?php
function demoFunc1($num) {
$num += 1;
}
function demoFunc2(&$num) {
$num += 5;
}
$orig_num = 10;
demoFunc1( $orig_num );
echo "Base Value is $orig_num<br />";
demoFunc2( $orig_num );
echo "Base Value is $orig_num<br />";
?>
</body>
</html>
Once executed, the following result shall appear on the screen.

Returning Values from Functions


The return statement is used to return control from the function to the calling function. Moreover, it is
also used to return values from the function to the calling function. The syntax of using this statement
is the keyword return followed by the value or valriable whose value needs to be returned. PHP
allows returning arrays if there is a requirement to return more than one value to the calling function.
Sample code to demonstrate the functioning of this statement is given below –
<html>
<head>
<title>Returning values from functions</title>
</head>
<body>
<?php
function demoFunc($num_1, $num_2) {
$result = $num_1 + $num_2;
return $result;
}
$value = demoFunc(4, 7);
echo "Value returned : $value";
?>
</body>
</html>
After the execution of this code, the following result shall appear on the screen –

Giving Function Parameters Default Values


In order to make the system self-sufficient and not respond to issues like lesser parameters received
than expected, you can set default values for parameters. Therefore, if a calling function doesn’t
provide value for a parameter, it automatically assumes a default value. This concept can be
implemented in the following manner –
<html>
<head>
<title>Setting Default Values for Parameters</title>
</head>
<body>
<?php
function demoPara($para_val = NULL) {
print $para_val;
}
demoPara ("Test Call!");
demoPara ();
?>
</body>
</html>
Once executed, you can expect the following result –

Dynamic Function Calls


PHP allows programmers to assign names of functions to variables. These names are assigned as
strings to the variables concerned and thence, can be used by the programmer as and when required.
This behaviour is depicted in the sample code given below –
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function demoDynFunc() {
echo "Hey there!<br />";
}
$function_name = "demoDynFunc";
$function_name();
?>
</body>
</html>
The output for this code is given below for your reference –
Chapter 11: Files in PHP

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.

The include() Function


This function simply takes the text in the specified file and uses it for the file concerned as and when
it is required. There may be issues in loading a file and as a result, only a warning for the same is
generated. However, this will not stop the file from getting executed.
A good example of a scenario where you might require file inclusion is when you may want to create
a common menu for all your webpages. The contents of the file, which can be named as menu.php,
given below, can be referred for code.
<a href="www.google.com">Google</a> -
<a href="www.yahoo.com">Yahoo</a> -
<a href="www.facebook.com">Facebook</a> <br />
The menu created using this file will have links for the three website namely Google, Yahoo and
Facebook. Moreover, the text corresponding to the same will be displayed. In order to include this
file, a code similar to the one given below must be written.
<html>
<body>
<?php include("menu.php"); ?>
<p>Demo of file inclusion</p>
</body>
</html>

The require() Function


This function basically copies text from the specified file and places it into the target file. Therefore,
it is as good as writing the code without the programmer having to put in the effort for it. However, if
there is a problem in loading the file, the program’s execution halts and generates a fatal error.
In entirety, the include() and require() functions are the same with the only difference in the way they
handle their error conditions. With that said, the use of require() is recommended as against include()
because the execution of a script in the absence of missing files can lead to unpredictable behaviour.

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.

Identification of Browser and Platform


When the PHP environment is setup, PHP creates some useful environment variables. You can view
these variables in the phpinfo.php file. The HTTP_USER_AGENT variable contains information
about the platform and operating system being used. you can access the value of the environment
variable using the function getenv().
The information provided by this environment variable is used to create browser-friendly content.
The sample code given below helps you to identify the platform and operating system of the client.
<html>
<body>
<?php
function demoBrowser() {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$b_name = 'Unknown';
$user_platform = 'Unknown';
$user_version = "";
/*Code for determining platform*/
if (preg_match('/linux/i', $u_agent)) {
$user_platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
$user_platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $user_agent)) {
$user_platform = 'windows';
}
/*Code for determining user name*/
if(preg_match('/MSIE/i',$user_agent) && !preg_match('/Opera/i',$user_agent)) {
$b_name = 'Internet Explorer';
$ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$user_agent)) {
$b_name = 'Mozilla Firefox';
$ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$user_agent)) {
$b_name = 'Google Chrome';
$ub = "Chrome";
}
elseif(preg_match('/Safari/i',$user_agent)) {
$b_name = 'Apple Safari';
$ub = "Safari";
}
elseif(preg_match('/Opera/i',$user_agent)) {
$b_name = 'Opera';
$ub = "Opera";
}
elseif(preg_match('/Netscape/i',$user_agent)) {
$b_name = 'Netscape';
$ub = "Netscape";
}
/*Determining version number*/
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $user_agent, $matches)) {
/*There is no match, so continue!*/
}
$i = count($matches['browser']);
if ($i != 1) {
if (strripos($user_agent,"Version") < strripos($user_agent,$ub)){
$user_version= $matches['version'][0];
}
else {
$user_version= $matches['version'][1];
}
}
else {
$user_version= $matches['version'][0];
}
if ($user_version == null || $user_version == "") {
$user_version = "?";
}
return array( 'userAgent' => $user_agent, 'name' => $b_name,
'version' => $user_version, 'platform' => $user_platform, 'pattern' =>
$pattern );
}
$ua = demoBrowser();
$yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] .
" reports: <br >" . $ua['userAgent']; print_r($yourbrowser);
?>
</body>
</html>
Run this code and see the result. The results will vary from one computer to another and depends
solely on the machine that it is run on.
Random Display of Images
PHP provides a function named rand(), which generates random numbers. This function may generate
similar number series or patterns of numbers if it is not seeded. For this, srand() may be used. This
function accepts seed as an argument and generates a new pattern of random number for every call of
the function.
As an example, we have taken the case where we have 4 images and we wish to display a random
image every single time. The sample code for this case study has been provided below.
<html>
<body>
<?php
srand( microtime() * 1000000 );
$num_image = rand( 1, 4 );
switch( $num_image ) {
case 1:
$file_image = "/php/images/logo.png";
break;
case 2:
$file_image = "/php/images/php.jpg";
break;
case 3:
$file_image = "/php/images/logo.png";
break;
case 4:
$file_image = "/php/images/php.jpg";
break;
}
echo "Image Randomly Generated: <img src=$file_image />";
?>
</body>
</html>
You can run this code and see how it performs. However, before you execute this code, be sure to
upload the images required by the program and specify their exact, absolute path in the space
provided for the same.

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.

The GET Method


When the GET method is used for sending information to the web server, it send the same along with
the page URL. The URL is appended by the encoded information and the question mark sign (?)
separates the former from the latter. Some of the key things to note about the use of this method
include –
Since this method appends the page URL, the sent information will also appear in logs of the
server.
The maximum number of characters that can be sent using the GET method is 1024
characters.
There is an inherent issue of compromised confidentiality with this method. Therefore, its use
must be avoided when you are sending passwords or critical information to the web server.
Another inherent limitation of the GET method is that documents and images cannot be sent to
the server using this method.
Besides the above-mentioned, it is also possible to access the data sent using this method by
retrieving the QUERY_STRING environment variable. Therefore, data is not safe.
It is possible to access all the sent information using this method by accessing $_GET, which
an associative array provided by PHP for this purpose.
You can try the sample code given below to understand how this method is used.
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>

The POST Method


An alternative to the GET method is POST method. This method makes use of HTTP headers to
transfer information from the client to the server. The encoded information is put into the header.
Some of the things that you must know about the use of this method for information transfer has been
listed below –
Unlike GET method, there is no limitation on the number of characters that can be sent using
this method.
It is possible to send binary as well as ASCII data using this method.
As far as the security of data is concerned, data security totally lies in the hands of the HTTP
protocol. You can ensure higher security of data by using HTTP Secure.
All the data using the POST method can be accessed using the $_POST associative array.
You can try the sample code given below to understand how this method is used.
<?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 $_REQUEST Variable


The contents of $_GET and $_POST are available in $_REQUEST. Besides this, $_REQUEST also
contains data associated with $_COOKIE. The form data sent to the web server using both the
methods namely GET and POST can be accessed by accessing this variable.
Here $_PHP_SELF variable contains the name of self script in which it is being called.

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++

Learn C++ in 2 hours And Start Programming


Today

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!

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

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.

The ANSI Standard


Before we move forward, it is important to explain what the ANSI standard means with respect to
programming languages. The ANSI standard is an attempt to standardize the programming language to
ensure portability of the code. It is another way to ensure that the code you write compiles and
executes without errors or warnings on another system if it does the same on one system. Almost all
of the C++ compilers that are commercially available support ANSI standard C++ and therefore, its
use is highly recommended.

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.

auto Explicit operator this

asm Export new throw

break else protected true


bool Enum private try

catch Float register typedef

case for public typeid

Class friend return typename

Char Goto reinterpret_cast union

const_cast if Signed unsigned

const inline Short using

default extern Static virtual

continue False Sizeof void

Do mutable Struct volatile

delete namespace static_cast wchar_t

dynamic_cast int template while

double Long Switch

Classes and Objects


A C++ program can be described as a collection of objects. All through the execution of the program,
these objects basically interact with each other by calling each other’s methods or accessing
variables. Before moving forward, let us discuss what these terms mean. The heart and soul of a C++
program is a class, which is template that declares variables and methods.
The variables are like any other variables, which are just identifiers that can be assigned a value. On
the other hand, a method describes the behaviour of the class. Objects are created by instantiating
these classes. Therefore, objects are real-time entities that are created using the template called
class.

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.

Built-in Data Types


The basic data types supported in C++ are as follows –
Boolean
The boolean data type holds only two values namely, true and false. The keyword ‘bool’ is used to
declare variables of this type.
Character
This data type can hold any character, including special characters. The keyword used to declare a
variable of this type is ‘char’. The memory allotted for char is 1 byte.
Integer
This data type can hold any integer. The keyword used to declare a variable of this type is ‘int’. The
memory allotted for bool is 4 bytes.
Floating Point
This data type can hold any number along with its fractional part in the form of decimal point
numbers. The keyword used to declare a variable of this type is ‘float’. The memory allotted for bool
is 4 bytes.
Double Floating Point
This data type can hold any number along with its fractional part in the form of decimal point
numbers. Its capacity to store digits that appear after the decimal point is double that of float. The
keyword used to declare a variable of this type is ‘double’. The memory allotted for double is 8
bytes.
Valueless
Some variables do not have a data type and are usually typecasted as per the needs of the program.
Such variables are declared as ‘void’ or typeless.
Wide Character
The memory space alloted to this data type is more than that allotted to char. Characters that require a
larger memory space can be declared as wide characters using the keyword ‘wchar_t’. The memory
allotted for wide char is 2 or 4 bytes.
The memory allotted to each of these data types can also be manipulated by using one of the following
type modifiers –
unsigned
signed
long
short
For instance, using short with int decreases its memory allocation to 2 bytes. Besides this, these type
modifiers are used to change the range of values that the data type will support. For example,
unsigned data type will only have positive values while a signed data type will have positive as well
as negative values. The size of a data type on a computer is also hardware-dependent. Therefore, it is
good to check the same. You can execute the following program on your computer to see how the
sizes vary on your system.
#include <iostream>
using namespace std;
int main() {
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of float : " << sizeof(float) << endl;
return 0;
}
The program uses endl, which is just a newline character. So, the program asks the system to print a
newline after every line is printed. This shall make the output more readable. The execution of the
code on your system shall yield a result similar to the one shown below –
Typedef Declarations
This is a method by which the C++ ecosystem allows the programmer to rename existing data types
according to their convenience and the needs of their program. The syntax for using typedef is as
follows –
typedef data_type new_name;
Here, the data_type is the data type that needs to be renamed and new_name is the name that you wish
to give this data type. Sample implementation for typedef is as follows –
typedef int measurement;
Now, wherever measurement will be used as a data type, the variable will internally be declared as
an integer. Variables can be declared of the type, ‘measurement’, using the following syntax –
measurement length;
measurement width;

Enumerated Data Types


C++ also allows the programmer to declare a data type of his or her own. Enumerated data types can
be given a name and a set of values that they can hold. Therefore, every enumerator is a constant and
the data type of this constant is the enumeration. In order to create an enum, the following syntax must
be used.
enum name_of_enum {values} var_name;
Here, enum is the keyword, name_of_enum is the name that you wish to provide for the enumerator
you are creating, values is the list of values that the enum can hold and var_name is the name of the
variable that is declared for the enum. Sample implementation for enum is given below for your
reference.
enum color {white, black, blue, red, green} c_name;
c_name = white;
The C++ statements given above create an enum called color that can hold five values namely, white,
black, blue, red and green. A variable c_name is declared as the enum, color and then, it is assigned
the value white. Internally, the list of values defined inside the curly brackets is assigned the values 0,
1, 2 and so on. Therefore, white will internally have the value 0 and green will have the value 4. You
can change the value by mentioning the same in the enum declaration. For example, the code shown
below assigns the value 5 to blue.
enum color {white, black, blue = 5, red, green} c_name;
It is important to understand that the values of the enumerators will now be –
white = 0
black = 1
blue = 5
red = 6
green = 7
The values are assigned in such a manner because the value of the succeeding enumerator is always
one greater than that of the preceding enumerator.
Chapter 4: Variables

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.

Rvalues and Lvalues


Expressions are divided into two categories namely lvalue and rvalue. If an expression refers to a
memory location, then it is referred to as lvalue. This expression may appear on the left or right-hand
side of the C++ statement. On the other hand, data values are called rvalues and they can only appear
on the right-hand side of the C++ statement.
Basically, data values cannot be assigned a value as they are values in themselves. Therefore, putting
them on the left-hand side of the C++ statement violates their basic nature. A valid C++ statement is
shown below.
X = 10;
Here, 10 is a data value and X is a name referring to a memory location. Therefore, X is the lvalue
and 10 is the rvalue. The following statement is also valid.
X = X + 10;
X, being an lvalue, can appear on left as well as right-hand side of the statement. However, the
following statement is invalid –
10 = X;
It is important to mention here that constants and literals are rvalues and they cannot appear on the
left-hand side of a C++ statement.

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.

Floating Point Literals


Floating Point literals are literals that possess a fractional or exponential part in addition to the
integer part. Therefore, they may be represented in decimal form where the integer part is followed
by a decimal point and fractional component or in the exponential form.

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.

Escape sequence Meaning

\' ' character

\\ \ character

\? ? character

\" " character

\b Backspace
\a Alert or bell

\n Newline

\f Form feed

\t Horizontal tab

\r Carriage return

\ooo Octal number

\v Vertical tab

\xhh . . . Hexadecimal number

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.

Declaring and Defining Constants or Literals


Constants can be defined using two methods, which have been described below –
The first method makes use of the keyword const which must be the first word in the
declaration statement of a constant to declare it as such. The syntax for declaring a constant
variable is as follows –
const data_type variable_name = value;
Here, data_type is the data type and variable_name is the identifier for the variable that is to
be used. Sample code to illustrate how this can be done is given below.
#include <iostream>
using namespace std ;
int main () {
const int SIDE = 15 ;
const char NEWLINE = '\n' ;
int sq_area ;
sq_area = SIDE * SIDE ;
cout << sq_area ;
cout << NEWLINE ;
return 0 ;
}
The output for the code is as shown –

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.

Loop Control Statements


Loop control statements redirect the flow of execution from the normal sequence. Moreover, any
objects created within the scope that was being executed are also destroyed. C++ supports three loop
control statements namely goto, break and continue, which have been described below.
Break
The break statement is used to redirect control from the loop block to the statement that appears after
the loop block. In this way, the loop ceases to execute once this statement is encountered. The syntax
for its implementation is –
break;
Continue
The continue statement is used to redirect control from the loop block to the first statement of the
loop, which is the for, do and while statements for the three loop constructs. This statement halts the
execution of the present iteration and initiates the execution of the next iteration. The syntax for its
implementation is –
continue;
Goto
Although the use of goto statement is strictly prohibited as it exposes the code to external attacks,
there may be times when its use may be inevitable. For such scenarios, this statement has been
included here. the goto statement redirects the execution to the statement that correponds to the label
specified as part of the goto statement. The syntax for its implementation is –
goto label_name;

The Infinite Loop


Like we said in all the loop constructs, they execute until the condition remains true. So, if we create
a scenario where the condition never becomes false, then the loop will execute infinitely. Infinite
loops can be created by omitting the condition in the loop constructs. A sample implementation for
this concept is as follows –
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
cout << “This is an infinite loop.\n”
}
return 0;
}
This program will continue printing the message until you kill the process using Control+C keys.
Chapter 8: Decision Making

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 –

Nested switch statements


In addition to these, C++ also supports the conditional operator (?:), which has already been
discussed in the chapter on operators.
Chapter 9: Functions

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;
}

Declaring and Defining a Function


The function statement or the function header is the declaration and tells the compiler the way in
which the function needs to be called. A function may just be declared at the beginning of the program
and can be defined later. In order to declare the function maximum_value, the following statement
needs to be given at the beginning of the program.
int maximum_value(int number_1, int number_2);
Alternatively, you may also just use the following statement for function declaration –
int maximum_value(int, int);
It tells the compiler that a function named maximum_value exists and it can take integer parameters. It
is a good practice to declare your functions at the beginning of the program. However, it is
particularly used in cases where you have the function definition in one file and the function is being
used in another file.

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.

Setting Default Values for Parameters


C++ allows programmers to set default values for parameters of a function. This is a particularly
useful functionality in cases where function calls are made without the exact number of arguments. If
the corresponding parameter value is left blank by the calling function, the default value is used for
processing. Default values can be set for all parameters of the function using the assignment operator.
The sample implementation given below illustrates hw default values can be set for function
parameters.
#include <iostream>
using namespace std;
int add_val(int x, int y = 5) {
int add_result;
add_result = x + y;
return (add_result);
}
int main () {
int x = 10;
int y = 20;
int ret_val;
ret_val = add_val(x, y);
cout << "Result when both values given : " << ret_val << endl;
ret_val = add_val(x);
cout << "Result when only x value given : " << ret_val << endl;
return 0;
}
The output generated for this code is shown in the image given below.
Chapter 10: Numbers

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.

Performing Mathematical Functions


Although, you can write code for any mathematical function that you wish to perform in your program,
there are a set of functions that are provided as part of the C++ library. You can directly use them to
get your work done without the hassle of coding them from scratch. In order to use these function, you
will need to include the header file, <cmath>, in your program.
Some of the inbuilt functions include –
double cos(double)
This function returns the cosine of the angle provided as argument.
double sin(double)
This function returns the sine of the angle provided as argument.
double tan(double)
This function returns the tan of the angle provided as argument.
double log(double)
This function returns the natural log of the number provided as argument.
double pow(double, double)
This function returns the value computed by putting first argument raised to the power corresponding
to the second argument.
double hypot(double, double)
This function returns the hypotenuse of a right triangle for which the two side lengths are given in the
arguments.
double sqrt(double)
This function returns the square root of the number provided as argument.
int abs(int)
This function returns the absolute value of the integer provided as argument.
double fabs(double)
This function returns the absolute value of the decimal number provided as argument.
double floor(double)
This function returns the integer lower than or equal to the number provided as argument.
The sample implementation given below demonstrates how these mathematical operations can be
performed.
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// Defining numbers
int i = -1000;
double d = 200.374;
short s = 10;
float f = 230.47;
long l = 100000;
// Performing mathematical operations
cout << "pow( d, 2) :" << pow(d, 2) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "sin(d) :" << sin(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "floor(d) :" << floor(d) << endl;
return 0;
}
The output of this code is shown in the image given below.
Random Numbers
There may be scenarios where you might need random number generation. C++ provides two
functions for this purpose namely rand() and srand(). The first function only returns a pseudo random
number. However, this problem can be fixed by using srand(). The following implementation
demonstrates how random numbers can be generated.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main () {
int x,y;
// The seed is set.
srand( (unsigned)time( NULL ) );
/* This code will generate 5 random numbers */
for( x = 0; x < 5; x++ ) {
// Generate random number
y = rand();
cout <<" Generated Random Number = " << y << endl;
}
return 0;
}
The output for this code has been shown in the image given below.
Chapter 11: Arrays

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;

Accessing Elements of Array


Evidently, if you need to access the elements of the array, you just need to write the name of the array,
followed by the index within square brackets. A sample to show you how values of array elements
can be assigned to other variables is given below.
double mysal = bal [0];
The statement given above will simply assign the value 0.0 to the variable mysal. The following
sample code summarizes all the concepts related to arrays and how they can be implemented in C++.
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw; //used for formatting
int main () {
//Array declaration
int num[ 10 ];
//Assigning values to array elements
for ( int x = 0; x < 5; x++ ) {
num[x] = x + 100;
}
cout << "Element" << setw( 13 ) << "Value" << endl;
for ( int y = 0; y < 5; y++ ) {
cout << setw( 7 )<< y << setw( 13 ) << num[y] << endl;
}
return 0;
}
The output of the code can be seen in the image given below.

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#

Learn C# in 2 hours And Start Programming


Today

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.

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: Getting Started

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

The .NET Framework


As mentioned previously, the C# programming language is a part of the .NET framework, which is a
platform used for creating web services, web applications and Windows applications. Moreover, this
platform can be accessed from many languages like COBOL, Jscript, C++, C# and Visual Basic. The
platform allows seamless communication between the platform and these languages. In fact, these
languages can communicate with each other as well.
The key components of .NET that are used for application development include –
The .Net Framework Class Library
Common Language Runtime (CLR)
Common Type System
Common Language Specification
Windows Forms
Metadata and Assemblies
ADO.Net
ASP.Net and ASP.Net AJAX
Windows Presentation Foundation
Windows Workflow Foundation (WF)
LINQ
Windows Communication Foundation (WCF)

Integrated Development Environment for C#


The tools available under the Microsoft brand name for C# development include –
Visual Web Developer
Visual C# 2010 Express (VCE)
Visual Studio 2010 (VS)
All kinds of C# programs can be written using these three tools. In fact, the range of applications
starts from command line programs and ends at complex applications. Another option that exists for
you is to write the C# program using any text editor program and compile the same using the
command-line compiler. This compiler is a part of the .NET framework.
Visual Web Developer and Visual C# Express are reduced versions of Visual Studio. You can
download and install any of these tools depending on your convenience and requirements of your
project. All you need to get started with the installation is an active Internet connection.
While these tools are available on Windows only, you can still write C# programs on Linux and Mac
OS. One open-source version of .NET framework is Mono. It includes the C# compiler and can be
run on a variety of platforms. In addition to bringing .NET platform to Mac and Linux, Mono also
allows the availability of better development tools for Linux. Apart from Linux and Mac OS, Mono
can be run on Solaris, Windows, BSD and Android.
Chapter 2: Program Structure

In order to understand the fundamental building blocks of the C# programming language, it is


important to know about the program structure. This chapter introduces the basic program structure of
C# to help you get started and have a reference that you can use for future programming lessons on
this language.

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.

The program consists of the following key elements –


Comments
A class
Namespace declaration
Class attributes
Class methods
Expressions
Statements
A Main method
We will discuss each of these elements in detail now. The first statement is the using statement that
declares the namespace that needs to be included to the program. A program can have many using
statements. System is the namespace that the program instructs the compiler to include. The
namespace declaration follows the using statement and instructs the compiler that the set of classes
included fall under the namespace PrintHelloWorld. Therefore, namespace declaration declares the
namespace that consists of the collection of classes defined below under. Here, the namespace
PrintHelloWorld consists of the class HWorld.
The next line in this code is the class declaration. The variables and methods used for implementing
the functionality are declared inside the class declaration. The behaviour of the class is determined
by the methods of the class. In the code given above, only one method named Main is defined. The
Main method is the entry point. It is the method from which program starts execution.
The next line, /* C# Program */, is a comment. Any text written inside the /* … */ module is ignored
by the compiler. It is for the programmer to improve code readability and understandability. The
main statement that actually prints ‘Hello World!’ on the screen is the Console.WriteLine method that
is called with the string to be printed. This method is available in the Console class, which is a part
of the System namespace.
The last statement of the program is the Console.ReadKey method. Usually, the program will execute,
print Hello World! and exit. Therefore, you will not be able to see the result. In order to make the
program wait until you have read the result, this method is used. This method waits until the user
presses a key and exits after that.
There are some things that are worth noting at this juncture. Firstly, C# is a case sensitive language.
Therefore, this and This are two different words for the system. As a rule, you must terminate every
C# statement with a semicolon (;). Your program must have a Main method as program execution
starts from this method. You can put any name as filename. Unlike Java, there is no such compulsion
in C# that the name of the file must be same as class name.

Compiling and Executing Programs


In order to compile and execute a program in C#, you need to follow the following steps –
Open Visual Studio by double clicking on its icon.
Take a look at the bar menu and find the word File. Under, File, click on New and then,
Project.
From the templates, choose Visual C# and then, click on Windows.
The system will ask you the type of application you wish to create. Choose Console
Application from the available list of options.
The system will now ask you to provide a name for your project. Give a name and click OK.
Now that you are through with the main steps, you will see that a new project has been
created in the Solutions Explorer section of the IDE.
The code editor can be used for writing code.
In order to compile and execute the code, press F5 or the Run button on the menu bar. Upon
execution, you will see that a command promp has been generated that has the output of your
code.
If you don’t have the IDE installed or wish to use the command line prompt for compiling and
executing the prompt, you can use the following steps.
Using any text editor, create a text file and write the code in the same.
Give the file a name with the extension .cs. For instance, you can name the file hworld.cs.
Open the command line and redirect the same to the directory where the target file is saved
using multiple cd statements.
In order to compile the file, enter csc hworld.cs.
If there are no compilation errors, the compiler will go ahead and create an executable file
with the name hworld.exe.
You can execute the program by simple typing hworld.
You shall see the output of the program on the screen after this step.
Chapter 3: Syntax

As we have mentioned previously, C# is an object-oriented programing language. What this means is


that a C# program consists of many objects that interact with each other in the form of actions. The
actions mentioned here are determined by the methods that are defined as part of the class. Class is a
template that decribes the characteristics and behavior of the objects instantiated using this class.
The class and object analogy can be best understaood by taking the exeample of a rectangle. There
can be many rectangles with different length and breadth. Moreover, the rectangle will be initialized
in the same manner. Besides this, the area computation for any rectangle will be the same. However,
the value of area for every rectangle will be different. Therefore, rectangle is a template or class and
every rectangle is an object created using the template.
Sample implementation of the rectangle class is given below for your better understanding.
using System;
namespace DemoRectangle {
class Rectangle {
double rect_width;
double rect_length;
public void InitRectangle() {
rect_length = 14.53;
rect_width = 33.52;
}
public double AreaRectangle() {
return rect_length * rect_width;
}
public void Display() {
Console.WriteLine("Rectangle’s Length: {0}", rect_length);
Console.WriteLine("Rectangle’s Width: {0}", rect_width);
Console.WriteLine("Rectangle’s Area: {0}", AreaRectangle());
}
}
class ExeRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.InitRectangle();
r.Display();
Console.ReadLine();
}
}
}
Upon execution, this code shall produce the following result –

The using Keyword


Every C# program includes the using statement. In fact, you must have noticed that it is the first
statement of every program. This keyword is used for including any namespaces that may be required
by the program. A program may have one or more than one using statements. Sample statement for the
implementation of this C# statement is given below for your reference.
using System;

The class Keyword


The second most common keyword that you will encounter in C# programs is the class keyword. This
keyword is typically used for declaring a class for the program.

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.

Members of the Class


A class may contain variables and/or functions. Variables of the class are data members that store
data related to the class. In the example of Rectangle class given above, the variables, rect_length
and rect_width, are the member variables of the class. The variables of the class can be manipulated
using member functions. Every function performs a specific task and adds to the modularity of the
program. The Rectangle class in the example has three member functions namely, InitRectangle,
AreaRectangle and Display.

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 –

catch char checked class const continue decimal


abstract as base bool break byte case
explicit extern false finally fixed float for
default delegate do double else enum event

interface internal is lock long namespace new


in (generic
foreach goto if implicit in int
modifier)
private protected public readonly ref return sbyte
ulong unchecked unsafe ushort using virtual void
out
null object operator out (generic override params
modifier)
switch this throw true try typeof uint

sealed short sizeof stackalloc static string struct


volatile while

The table given below lists all the contextual keywords supported by C# programming language.

partial partial
remove select set let orderby
(method) (type)

add alias ascending descending dynamic from get

global group into join


Chapter 4: Data Types

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.

Type Conversion Methods


C# provides some inbuilt methods for type conversion. These methods are described below –
ToBoolean
ToByte
ToChar
ToDateTime
ToDecimal
ToDouble
ToInt16
ToInt32
ToInt64
ToSByte
ToSingle
ToString
ToUInt16
ToUInt32
ToUInt64
ToType
While all these methods converts the type to the type mentioned in their names, the last method in this
list converts the type of the variable into the type specified in one of the parameters of the method
while it is called. The sample implementation given below converts the type to string type.
using System;
namespace DemoTypeConversion {
class DemoConvertToString {
static void Main(string[] args) {
float f_var = 56.125f;
int i_var = 46;
bool b_var = true;
double d_var = 1234.9876;
Console.WriteLine(f_var.ToString());
Console.WriteLine(i_var.ToString());
Console.WriteLine(b_var.ToString());
Console.WriteLine(d_var.ToString());
Console.ReadKey();
}
}
}
Upon execution, this code shall yield the following result.
Chapter 5: Variables

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.

Rvalue and Lvalue Expressions


Expressions are classified under two categories namely Lvalue and Rvalue. An expression that can
appear on both the left and right hand side of a statement is called lvalue while a rvalue expression
can only appear on the right hand side of the statement.
Literals are rvalues and can only appear on the right hand side. For example, int g = 10, is a valid
statement because the rvalue 10 is appearing on the right hand of the expression and g, which is a
lvalue, is appearing on the left. Moreover, g = g+10, is also a valid statement. However, 10 = g is
invalid.
Chapter 6: Constants and Literals

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.

Floating Point Literals


Floating Point literals are literals that possess a fractional or exponential part in addition to the
integer part. Therefore, they may be represented in decimal form where the integer part is followed
by a decimal point and fractional component or in the exponential form.
Some examples of floating point literals are 510E, 3.14159 and 210E-5F. However, literals like .e55
are not allowed because they do not have an integer component. Likewise, constants like 210f are
also invalid as they lack a decimal or exponent component. Therefore, the decimal form must have
exponent or/and decimal and the exponential form must have fractional part and/or integer part.

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

\? ? character

\" " character

\b Backspace
\a Alert or bell

\n Newline

\f Form feed

\t Horizontal tab

\r Carriage return

\xhh . . . Hexadecimal number of one or more digits

\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”.

Declaring and Defining Constants or Literals


Constants can be defined by writing a const keyword before them in the concerned C# statement. The
syntax for defining a constant is given below for your reference.
const data_type name_of_constant = value_of_constant;
Here, const is the keyword, data_type is the data type assigned to the constant, name_of_constant is
the identifier given to the constant and value_of_constant is the value that the constant will hold.
Sample code to demonstrate the working of constants is given below.
using System;
namespace DemoConst {
class DemoProg {
static void Main(string[] args) {
/*Declaration of constant*/
const double pi_value = 3.14159;
double r_circle;
Console.WriteLine("Enter Radius of the Circle: ");
r_circle = Convert.ToDouble(Console.ReadLine()); double area_circle = pi_value *
r_circle * r_circle;
Console.WriteLine("Radius of Circle: {0}, Area of Circle: {1}", r_circle, area_circle);
Console.ReadLine();
}
}
}
Upon execution, the program shall yield the following output.
Chapter 7: Operators

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;
}

Nested Switch Statements


There may be programming scenarios that may require you to test multiple variables and this shall
require multiple nested switch statements. C# allows programmers to use nested switch statements
and there is no limit on the amount of nesting that can be performed.

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

An important programming construct that is commonly available in all programming languages is


looping. These constructs allow you to perform multiple iterations of the same block of statements
provided a condition is met. C# provides three programming constructs namely for, while and do…
while. Each of these constructs are described in detail in this chapter.

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.

Loop Control Statements


Loop constructs give rise to situations of varied types. For instance, the condition specified for a loop
may always be true and as a result, the loop may go into infinite loop. Alternatively, the condition for
iteration may involve multiple variables and the standard constructs puts a limit on the same. If your
programming scenario is likely to create a scenario of this type, you may want to put statements inside
the loop that can help you control the loop. C# provides three such statements, which have been
described below –
Break
The break statement is used to redirect control from the loop block to the statement that appears after
the loop block. In this way, the loop ceases to execute once this statement is encountered. The syntax
for its implementation is –
break;
Continue
The continue statement is used to redirect control from the loop block to the first statement of the
loop, which is the for, do and while statements for the three loop constructs. This statement halts the
execution of the present iteration and initiates the execution of the next iteration. The syntax for its
implementation is –
continue;
Goto
The goto statement redirects the execution to the statement that correponds to the label specified as
part of the goto statement. With that said, it is important to mention that this keyword must be used in a
very limited manner and its usage must be avoided wherever possible. The syntax for its
implementation is –
goto label_name;

The Infinite Loop


Whenever you don’t give a condition to the loop, it automatically becomes an infinite loop. In such a
case, the loop block is executed infintely, until you stop the same by pressing the Control+C keys or a
hardware interrupt. Sample implementation of an infinite loop is given below for your reference.
using System;
namespace DemoInfinteLoop {
class DemoProg {
static void Main(string[] args) {
for (; ; ) {
Console.WriteLine("This is an Infinte Loop!");
}
}
}
}
You can compile and execute this code to see what happens.
Chapter 10: Classes and Objects

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.

Constructors and Destructors


C# has provision for two special types of member functions namely constructors and destructors. The
constructor function is automatically called upon creation of an object and possesses the same name
as the class. Besides this, it is the only member function that does not have a return type. Sample
implementation for constructors is given below for your understanding and reference.
using System;
namespace DemoApp {
class DemoLine {
private double line_ln; /*Data member for line length*/
public DemoLine() {
Console.WriteLine("New object created!");
}
public void setLineLn( double len ) {
line_ln = len;
}
public double getLineLn () {
return line_ln;
}
static void Main(string[] args) {
DemoLine line_1 = new DemoLine(); /*set line length*/
line_1.setLineLn(7.5);
Console.WriteLine("Line’s Length = {0}", line_1.getLineLn ());
Console.ReadKey();
}
}
}
Upon execution, the code yields the following output –

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!

S-ar putea să vă placă și